@donotdev/core 0.0.18 → 0.0.19
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.
- package/functions/index.d.ts +1 -1448
- package/i18n/locales/lazy/crud_ar.json +20 -0
- package/i18n/locales/lazy/crud_de.json +20 -0
- package/i18n/locales/lazy/crud_en.json +20 -0
- package/i18n/locales/lazy/crud_es.json +20 -0
- package/i18n/locales/lazy/crud_fr.json +20 -0
- package/i18n/locales/lazy/crud_it.json +20 -0
- package/i18n/locales/lazy/crud_ja.json +20 -0
- package/i18n/locales/lazy/crud_ko.json +20 -0
- package/index.d.ts +613 -98
- package/index.js +39 -39
- package/next/index.d.ts +15 -777
- package/next/index.js +15 -15
- package/package.json +10 -10
- package/server.d.ts +570 -94
- package/server.js +1 -1
- package/vite/index.d.ts +17 -779
- package/vite/index.js +29 -29
package/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var zi=Object.create;var Ot=Object.defineProperty;var Ki=Object.getOwnPropertyDescriptor;var Yi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,Xi=Object.prototype.hasOwnProperty;var Xr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Qi=(t,e)=>{for(var r in e)Ot(t,r,{get:e[r],enumerable:!0})},Zi=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yi(e))!Xi.call(t,i)&&i!==r&&Ot(t,i,{get:()=>e[i],enumerable:!(n=Ki(e,i))||n.enumerable});return t};var Qr=(t,e,r)=>(r=t!=null?zi(Ji(t)):{},Zi(e||!t||!t.__esModule?Ot(r,"default",{value:t,enumerable:!0}):r,t));var Hi=Xr(E=>{"use strict";var Wr=Symbol.for("react.transitional.element"),Oc=Symbol.for("react.portal"),Dc=Symbol.for("react.fragment"),Nc=Symbol.for("react.strict_mode"),Lc=Symbol.for("react.profiler"),Uc=Symbol.for("react.consumer"),Mc=Symbol.for("react.context"),Fc=Symbol.for("react.forward_ref"),Vc=Symbol.for("react.suspense"),Bc=Symbol.for("react.memo"),Li=Symbol.for("react.lazy"),Hc=Symbol.for("react.activity"),xi=Symbol.iterator;function $c(t){return t===null||typeof t!="object"?null:(t=xi&&t[xi]||t["@@iterator"],typeof t=="function"?t:null)}var Ui={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mi=Object.assign,Fi={};function ke(t,e,r){this.props=t,this.context=e,this.refs=Fi,this.updater=r||Ui}ke.prototype.isReactComponent={};ke.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};ke.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Vi(){}Vi.prototype=ke.prototype;function qr(t,e,r){this.props=t,this.context=e,this.refs=Fi,this.updater=r||Ui}var Gr=qr.prototype=new Vi;Gr.constructor=qr;Mi(Gr,ke.prototype);Gr.isPureReactComponent=!0;var Oi=Array.isArray;function $r(){}var A={H:null,A:null,T:null,S:null},Bi=Object.prototype.hasOwnProperty;function jr(t,e,r){var n=r.ref;return{$$typeof:Wr,type:t,key:e,ref:n!==void 0?n:null,props:r}}function Wc(t,e){return jr(t.type,e,t.props)}function zr(t){return typeof t=="object"&&t!==null&&t.$$typeof===Wr}function qc(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var Di=/\/+/g;function Hr(t,e){return typeof t=="object"&&t!==null&&t.key!=null?qc(""+t.key):e.toString(36)}function Gc(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then($r,$r):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function Re(t,e,r,n,i){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(o){case"bigint":case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case Wr:case Oc:s=!0;break;case Li:return s=t._init,Re(s(t._payload),e,r,n,i)}}if(s)return i=i(t),s=n===""?"."+Hr(t,0):n,Oi(i)?(r="",s!=null&&(r=s.replace(Di,"$&/")+"/"),Re(i,e,r,"",function(d){return d})):i!=null&&(zr(i)&&(i=Wc(i,r+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(Di,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=n===""?".":n+":";if(Oi(t))for(var u=0;u<t.length;u++)n=t[u],o=c+Hr(n,u),s+=Re(n,e,r,o,i);else if(u=$c(t),typeof u=="function")for(t=u.call(t),u=0;!(n=t.next()).done;)n=n.value,o=c+Hr(n,u++),s+=Re(n,e,r,o,i);else if(o==="object"){if(typeof t.then=="function")return Re(Gc(t),e,r,n,i);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return s}function kt(t,e,r){if(t==null)return t;var n=[],i=0;return Re(t,n,"","",function(o){return e.call(r,o,i++)}),n}function jc(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ni=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}},zc={map:kt,forEach:function(t,e,r){kt(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return kt(t,function(){e++}),e},toArray:function(t){return kt(t,function(e){return e})||[]},only:function(t){if(!zr(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};E.Activity=Hc;E.Children=zc;E.Component=ke;E.Fragment=Dc;E.Profiler=Lc;E.PureComponent=qr;E.StrictMode=Nc;E.Suspense=Vc;E.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A;E.__COMPILER_RUNTIME={__proto__:null,c:function(t){return A.H.useMemoCache(t)}};E.cache=function(t){return function(){return t.apply(null,arguments)}};E.cacheSignal=function(){return null};E.cloneElement=function(t,e,r){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var n=Mi({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!Bi.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(n[o]=e[o]);var o=arguments.length-2;if(o===1)n.children=r;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];n.children=s}return jr(t.type,i,n)};E.createContext=function(t){return t={$$typeof:Mc,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:Uc,_context:t},t};E.createElement=function(t,e,r){var n,i={},o=null;if(e!=null)for(n in e.key!==void 0&&(o=""+e.key),e)Bi.call(e,n)&&n!=="key"&&n!=="__self"&&n!=="__source"&&(i[n]=e[n]);var s=arguments.length-2;if(s===1)i.children=r;else if(1<s){for(var c=Array(s),u=0;u<s;u++)c[u]=arguments[u+2];i.children=c}if(t&&t.defaultProps)for(n in s=t.defaultProps,s)i[n]===void 0&&(i[n]=s[n]);return jr(t,o,i)};E.createRef=function(){return{current:null}};E.forwardRef=function(t){return{$$typeof:Fc,render:t}};E.isValidElement=zr;E.lazy=function(t){return{$$typeof:Li,_payload:{_status:-1,_result:t},_init:jc}};E.memo=function(t,e){return{$$typeof:Bc,type:t,compare:e===void 0?null:e}};E.startTransition=function(t){var e=A.T,r={};A.T=r;try{var n=t(),i=A.S;i!==null&&i(r,n),typeof n=="object"&&n!==null&&typeof n.then=="function"&&n.then($r,Ni)}catch(o){Ni(o)}finally{e!==null&&r.types!==null&&(e.types=r.types),A.T=e}};E.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()};E.use=function(t){return A.H.use(t)};E.useActionState=function(t,e,r){return A.H.useActionState(t,e,r)};E.useCallback=function(t,e){return A.H.useCallback(t,e)};E.useContext=function(t){return A.H.useContext(t)};E.useDebugValue=function(){};E.useDeferredValue=function(t,e){return A.H.useDeferredValue(t,e)};E.useEffect=function(t,e){return A.H.useEffect(t,e)};E.useEffectEvent=function(t){return A.H.useEffectEvent(t)};E.useId=function(){return A.H.useId()};E.useImperativeHandle=function(t,e,r){return A.H.useImperativeHandle(t,e,r)};E.useInsertionEffect=function(t,e){return A.H.useInsertionEffect(t,e)};E.useLayoutEffect=function(t,e){return A.H.useLayoutEffect(t,e)};E.useMemo=function(t,e){return A.H.useMemo(t,e)};E.useOptimistic=function(t,e){return A.H.useOptimistic(t,e)};E.useReducer=function(t,e,r){return A.H.useReducer(t,e,r)};E.useRef=function(t){return A.H.useRef(t)};E.useState=function(t){return A.H.useState(t)};E.useSyncExternalStore=function(t,e,r){return A.H.useSyncExternalStore(t,e,r)};E.useTransition=function(){return A.H.useTransition()};E.version="19.2.3"});var Kr=Xr(($g,$i)=>{"use strict";$i.exports=Hi()});var In={};Qi(In,{DEFAULT_ERROR_MESSAGES:()=>oe,DoNotDevError:()=>k,SingletonManager:()=>Yt,addMonths:()=>Ue,addYears:()=>Xt,calculateSubscriptionEndDate:()=>es,captureErrorToSentry:()=>zt,commonErrorCodeMappings:()=>Ne,compactToISOString:()=>Dt,createAsyncSingleton:()=>Ko,createErrorHandler:()=>$,createMetadata:()=>io,createMethodProxy:()=>Yo,createSingleton:()=>Le,createSingletonWithParams:()=>zo,detectErrorSource:()=>qt,filterVisibleFields:()=>Zo,formatDate:()=>Zr,formatRelativeTime:()=>po,generateCodeChallenge:()=>vn,generateCodeVerifier:()=>gn,generatePKCEPair:()=>Bo,getCurrentTimestamp:()=>ao,getVisibleFields:()=>Jt,getWeekFromISOString:()=>lo,handleError:()=>v,hasRoleAccess:()=>it,hasTierAccess:()=>jo,isCompactDateString:()=>Nt,isFieldVisible:()=>bn,isPKCESupported:()=>Ho,isoToCompactString:()=>oo,lazyImport:()=>Go,mapToDoNotDevError:()=>jt,maybeTranslate:()=>Vo,normalizeToISOString:()=>so,parseDate:()=>Lt,parseDateToNoonUTC:()=>ho,parseISODate:()=>ts,parseServerCookie:()=>os,showNotification:()=>Fo,timestampToISOString:()=>uo,toDateOnly:()=>mo,toISOString:()=>co,translateArray:()=>eo,translateArrayRange:()=>ro,translateArrayWithIndices:()=>no,translateObjectArray:()=>to,updateMetadata:()=>Jo,validateCodeChallenge:()=>Wo,validateCodeVerifier:()=>$o,validateEnvVar:()=>is,validateMetadata:()=>ns,validateUrl:()=>rs,withErrorHandling:()=>Mo,withGracefulDegradation:()=>qo});function eo(t,e,r,n={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=n;return Array.from({length:r},(c,u)=>{let d=`${e}.${u}`;return t(d)}).filter((c,u)=>{let d=`${e}.${u}`;return!(c===d||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function to(t,e,r,n){return Array.from({length:r},(i,o)=>{let s=`${e}.${o}.${String(n[0])}`;if(t(s)===s)return null;let u={};for(let d of n){let g=`${e}.${o}.${String(d)}`;u[d]=t(g)}return u}).filter(i=>i!==null)}function ro(t,e,r,n,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:n-r},(u,d)=>{let g=r+d,T=`${e}.${g}`;return t(T)}).filter((u,d)=>{let g=r+d,T=`${e}.${g}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,g))})}function no(t,e,r,n={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=n;return Array.from({length:r},(c,u)=>{let d=`${e}.${u}`;return{item:t(d),originalIndex:u}}).filter(({item:c,originalIndex:u})=>{let d=`${e}.${u}`;return!(c===d||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function io(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}function Dt(t){let e=t.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!e||e.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${t}`);let r=e[1],n=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(r,10),parseInt(n,10)-1,parseInt(i,10),parseInt(o,10),parseInt(s,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${t}`);return c.toISOString()}function oo(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0");return`${r}${n}${i}:${o}${s}`}function Nt(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function so(t){if(!t)return new Date().toISOString();if(t instanceof Date){if(isNaN(t.getTime()))throw new Error("Invalid Date object");return t.toISOString()}if(typeof t=="string"){if(Nt(t))return Dt(t);let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid date string: ${t}`);return e.toISOString()}if(typeof t=="number"){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid timestamp: ${t}`);return e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")return e.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof t}`)}function ao(){return new Date().toISOString()}function co(t){return t.toISOString()}function uo(t){return new Date(t).toISOString()}function lo(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let r=new Date(e.getFullYear(),0,1),n=Math.floor((e.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((n+r.getDay()+1)/7)}, ${e.getFullYear()}`}var N={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function po(t,e="en",r={}){if(!t)return"";let{style:n="long",numeric:i="auto",fallbackThreshold:o=N.WEEK}=r,s;if(t instanceof Date)s=t;else if(typeof t=="string")s=new Date(t);else if(typeof t=="number")s=new Date(t);else if(typeof t=="object"&&"toDate"in t)s=t.toDate();else return"";if(isNaN(s.getTime()))return"";let c=new Date,u=s.getTime()-c.getTime(),d=Math.round(u/1e3),g=Math.abs(d);if(g>o)return Zr(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:n,numeric:i});return g<N.MINUTE?T.format(d,"second"):g<N.HOUR?T.format(Math.round(d/N.MINUTE),"minute"):g<N.DAY?T.format(Math.round(d/N.HOUR),"hour"):g<N.WEEK?T.format(Math.round(d/N.DAY),"day"):g<N.MONTH?T.format(Math.round(d/N.WEEK),"week"):g<N.YEAR?T.format(Math.round(d/N.MONTH),"month"):T.format(Math.round(d/N.YEAR),"year")}function fo(t){switch(t){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function Zr(t,e="en",r="long"){if(!t)return"";let n;if(t instanceof Date)n=t;else if(typeof t=="string")n=new Date(t);else if(typeof t=="number")n=new Date(t);else if(typeof t=="object"&&"toDate"in t)n=t.toDate();else return"";if(isNaN(n.getTime()))return"";let i=typeof r=="string"?fo(r):r;return new Intl.DateTimeFormat(e,i).format(n)}function Lt(t){if(t!=null){if(t instanceof Date)return isNaN(t.getTime())?void 0:t.toISOString();if(typeof t=="string"){let e=t.trim();if(!e)return;if(Nt(e))try{return Dt(e)}catch{return}let r=new Date(e);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof t=="number"){if(!Number.isFinite(t))return;let e=new Date(t);return isNaN(e.getTime())?void 0:e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")try{let r=e.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,r=e.seconds*1e3+(e.nanoseconds||0)/1e6,n=new Date(r);return isNaN(n.getTime())?void 0:n.toISOString()}}}function ho(t){let e=Lt(t);if(!e)return;let r=new Date(e);return r.setUTCHours(12,0,0,0),r.toISOString()}function mo(t){let e=Lt(t);return e&&e.split("T")[0]||""}var V={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function iu(t){Object.assign(V,t)}var Oe={FREE:"free",PRO:"pro",PREMIUM:"premium"};function ou(t){Object.assign(Oe,t)}var Ut={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function su(t){Object.assign(Ut,t)}var Mt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function au(t){Object.assign(Mt,t)}import*as l from"valibot";var fe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function uu(t){Object.assign(fe,t)}var tt={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function lu(t){Object.assign(tt,t)}var du={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function pu(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var en={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},fu={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var tn=a.object({userId:a.string(),productId:a.optional(a.string()),priceId:a.string(),successUrl:a.pipe(a.string(),a.url()),cancelUrl:a.pipe(a.string(),a.url()),customerEmail:a.optional(a.pipe(a.string(),a.email())),userEmail:a.optional(a.pipe(a.string(),a.email())),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean()),mode:a.optional(a.picklist([tt.PAYMENT,tt.SUBSCRIPTION]))}),rn=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),nn=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(fe)),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),on=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(fe)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),sn=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),an=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function gu(t){return a.safeParse(tn,t)}function vu(t){return a.safeParse(rn,t)}function yu(t){return a.safeParse(nn,t)}function Eu(t){return a.safeParse(on,t)}function bu(t){return a.safeParse(sn,t)}function Iu(t){return a.safeParse(an,t)}var go=a.object({type:a.literal("StripePayment"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.pipe(a.string(),a.minLength(1,"Duration is required")),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),vo=a.object({type:a.literal("StripeSubscription"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),yo=a.variant("type",[go,vo]),Tu=a.record(a.string(),yo),Eo=a.record(a.string(),a.object({name:a.string(),price:a.string(),currency:a.string(),description:a.optional(a.string()),features:a.optional(a.array(a.string())),priceId:a.string(),allowPromotionCodes:a.optional(a.boolean())})),bo=a.record(a.string(),a.object({type:a.picklist(["StripePayment","StripeSubscription"]),name:a.string(),price:a.number(),currency:a.string(),priceId:a.string(),tier:a.string(),duration:a.string(),description:a.optional(a.string()),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean())}));function Su(t){return a.parse(Eo,t)}function _u(t){return a.parse(bo,t)}function Au(){let t={createCheckoutSessionRequest:a.safeParse(tn,{}),createCheckoutSessionResponse:a.safeParse(rn,{}),subscriptionData:a.safeParse(nn,{}),subscriptionClaims:a.safeParse(on,{}),webhookEvent:a.safeParse(sn,{}),checkoutSessionMetadata:a.safeParse(an,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var cn=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(V))),customClaims:l.optional(l.record(l.string(),l.any()))}),Ft=l.object({userId:l.string(),tier:l.picklist(Object.values(Oe)),status:l.picklist(Object.values(fe)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),un=l.object({role:l.optional(l.picklist(Object.values(V))),subscription:l.optional(Ft),features:l.optional(l.array(l.picklist(Object.values(Ut)))),permissions:l.optional(l.array(l.picklist(Object.values(Mt)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function Du(t){return l.safeParse(cn,t)}function Nu(t){return l.safeParse(Ft,t)}function Lu(t){return l.safeParse(un,t)}function Uu(){let t={authUser:l.safeParse(cn,{}),userSubscription:l.safeParse(Ft,{}),customClaims:l.safeParse(un,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(t).every(e=>e.success),results:t}}var Fu={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Vu(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var C={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},ie={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},D={CLIENT:"client",SERVER:"server",BUILD:"build"},L={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},De={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Gu={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},ju={USER:"user",GLOBAL:"global",SESSION:"session"},zu={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},Ku={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Yu={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};import*as h from"valibot";var Vt={create:"admin",read:"guest",update:"admin",delete:"admin"};var rt=/^[0-9a-zA-Z]+$/,rl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),data:h.record(h.string(),h.unknown()),idempotencyKey:h.optional(h.string())}),nl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),il=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required")),data:h.record(h.string(),h.unknown()),merge:h.optional(h.boolean(),!1)}),ol=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),sl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),limit:h.optional(h.pipe(h.number(),h.minValue(1),h.maxValue(1e3)),50),offset:h.optional(h.pipe(h.number(),h.minValue(0)),0),orderBy:h.optional(h.string()),orderDirection:h.optional(h.picklist(["asc","desc"]),"desc"),where:h.optional(h.array(h.object({field:h.string(),operator:h.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:h.any()})))});var Bt={"permission-denied":{type:"PERMISSION_DENIED",message:"You do not have permission to perform this action"},"not-found":{type:"NOT_FOUND",message:"The requested resource was not found"},"already-exists":{type:"ALREADY_EXISTS",message:"The resource already exists"},"invalid-argument":{type:"VALIDATION_ERROR",message:"Invalid argument provided"}},ln=class extends Error{type;originalError;constructor(e,r,n){super(r),this.name="EntityHookError",this.type=e,this.originalError=n}},k=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,r="internal",n){super(e),Object.setPrototypeOf(this,t.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var ml={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var vl={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var El={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Il={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Sl={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Ht={mobile:0,tablet:768,laptop:1024,desktop:1440},Io={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function To(t){return t>=Ht.desktop?"desktop":t>=Ht.laptop?"laptop":t>=Ht.tablet?"tablet":"mobile"}function Ul(t,e){let r=Io[e];return t>=r.min&&t<=r.max}function Ml(t,e){let r=To(t);return{current:r,width:t,height:e,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}var Vl="landing",Bl={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var dn=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var $t=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),So=f.picklist([...dn]),Jl=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:$t,permission:f.optional(So,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),Xl=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:$t}),Ql=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:$t}),Zl=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),ed=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),td=f.object({provider:f.string()}),rd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var cd={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as m from"valibot";var pn=m.object({name:m.string(),color:m.string(),icon:m.string(),customParameters:m.optional(m.record(m.string(),m.string())),button:m.object({backgroundColor:m.string(),textColor:m.string(),borderColor:m.string(),hoverBackgroundColor:m.string(),focusOutlineColor:m.string(),fontWeight:m.optional(m.string(),"500"),textKey:m.optional(m.string())})}),_o=m.object({...pn.entries,type:m.picklist(["auth","both"]),scopes:m.optional(m.array(m.string())),firebaseProviderId:m.optional(m.string())}),nt=m.union([m.literal(""),m.pipe(m.string(),m.url())]),Ao=m.object({authUrl:nt,tokenUrl:nt,profileUrl:nt,revokeUrl:m.optional(nt)}),Co=m.object({authentication:m.optional(m.array(m.string())),"api-access":m.array(m.string())}),wo=m.optional(m.object({pkce:m.optional(m.boolean(),!1),codeChallengeMethod:m.optional(m.picklist(["S256","plain"]),"S256")})),Po=m.object({...pn.entries,type:m.picklist(["oauth","both"]),scopes:Co,endpoints:Ao,capabilities:wo}),he={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},Wt={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},Ro=m.record(m.string(),_o),ko=m.record(m.string(),Po);function ld(){return m.safeParse(Ro,he)}function dd(){return m.safeParse(ko,Wt)}function xo(t){return t in he}function Oo(t){return t in Wt}var fn={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},yd={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Ed={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:fn.ANALYTICS},marketing:{requiresConsent:fn.MARKETING}};function qt(t){return t instanceof Error&&"source"in t&&typeof t.source=="string"?t.source:typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("auth/")?"auth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("oauth/")?"oauth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(t.code)?"firebase":typeof t=="object"&&t!==null&&"issues"in t&&Array.isArray(t.issues)&&"name"in t&&t.name==="ValiError"?"validation":t instanceof Error&&t.name==="EntityHookError"?"entity":typeof t=="object"&&t!==null&&("response"in t||"status"in t||"statusText"in t)?"api":typeof t=="object"&&t!==null&&"componentStack"in t?"ui":"unknown"}import*as mn from"valibot";function $(t){return(e,r)=>{if(e instanceof k)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new k(r||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let n;t.extractErrorCode?n=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(n=e.code);let i=t.defaultErrorCode;n&&t.errorCodeMapping&&n in t.errorCodeMapping&&(i=t.errorCodeMapping[n]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),n&&t.friendlyMessageMapping&&n in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[n]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},n&&(s.originalCode=n)),"originalError"in s||(s.originalError=e),new k(r||o,i,{details:s,source:t.errorSource})}}var Ne={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var oe={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Do={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},Gt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",...Ne},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...Ne},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(Do).map(([t,e])=>[t,e])),friendlyMessageMapping:{},extractErrorCode:t=>{if(typeof t!="object"||t===null)return;let e;return"response"in t&&t.response&&"status"in t.response?e=t.response.status:"status"in t&&typeof t.status=="number"&&(e=t.status),e?.toString()},processMetadata:t=>{let e={originalError:t};return typeof t!="object"||t===null||("response"in t&&t.response?("status"in t.response&&(e.statusCode=t.response.status),"data"in t.response&&(e.responseData=t.response.data)):"status"in t&&(e.statusCode=t.status)),e}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:Ne,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:oe.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:t=>{let e={originalError:t};return typeof t=="object"&&t!==null&&"componentStack"in t&&(e.componentStack=t.componentStack),e}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:oe["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:oe.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},No=t=>t instanceof mn.ValiError?new k(oe["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(Z.validation)(t),Lo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in Gt){let e=t,r=Gt[e.type]||"unknown";return new k(e.message||oe[r],r,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Bt[t.code]){let e=t,r=Bt[e.code];if(r){let n=Gt[r.type]||"unknown";return new k(r.message||oe[n],n,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(Z.entity)(t)},hn={auth:$(Z.auth),oauth:$(Z.oauth),api:$(Z.api),firebase:$(Z.firebase),ui:$(Z.ui),validation:No,entity:Lo,unknown:$(Z.unknown)};function jt(t,e,r){return t instanceof k?t:(hn[e]||hn.unknown)(t,r)}function zt(t,e,r={}){let n=globalThis.Sentry;n&&n.withScope(i=>{i.setTag("errorSource",e),i.setTag("errorCode",t.code),t.details&&Object.entries(t.details).forEach(([o,s])=>{if(typeof s!="function"&&o!=="originalError")try{i.setExtra(o,s)}catch{i.setExtra(o,`[${typeof s}]`)}}),Object.entries(r).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||r.userId)&&i.setUser({id:t.details?.userId||r.userId,email:t.details?.userEmail||r.userEmail}),n.captureException(t)})}function Uo(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!0}function v(t,e){let r=typeof e=="string"?{userMessage:e}:e||{},{userMessage:n,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=r,d=qt(t),g=t instanceof k?t:jt(t,d,n);if(n&&!g.userMessageProvided&&(g.message.includes("Error")||g.message.includes("Failed")||g.message.length<10?g=new k(n,g.code,{details:{...g.details,originalMessage:g.message},source:d,userMessageProvided:!0}):g=new k(g.message,g.code,{details:{...g.details,userMessage:n},source:d,userMessageProvided:!0})),o){let T=Uo()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:g.code,message:g.message,source:d};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&zt(g,d,i),g}function Mo(t,e){return async(...r)=>{try{return await t(...r)}catch(n){throw v(n,e)}}}function Fo(t,e="info",r){let n=Date.now().toString();return n}function Vo(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function gn(){let t=new Uint8Array(32);return crypto.getRandomValues(t),yn(t)}async function vn(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return yn(new Uint8Array(n))}async function Bo(){let t=gn(),e=await vn(t);return{codeVerifier:t,codeChallenge:e}}function yn(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ho(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function $o(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function Wo(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function qo(t,e,r){try{return await t()}catch{return e(),!1}}var Kt=new Map;function Go(t,e){if(Kt.has(e))return Kt.get(e);let r=t();return Kt.set(e,r),r}var En={[V.GUEST]:0,[V.USER]:1,[V.ADMIN]:2,[V.SUPER]:3};function it(t,e){if(!t)return!1;let r=En[t]??-1,n=En[e]??1/0;return r>=n}function jo(t,e,r){if(!t)return!1;let n=r??en,i=n[t]?.level??-1,o=n[e]?.level??1/0;return i>=o}function Le(t,...e){let r=null,n=!1;return function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?r=new t(...e):r=t(),r}finally{n=!1}}}function zo(t){let e=null,r=!1;return function(...i){if(e!==null)return e;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{r=!1}}}function Ko(t){let e=null,r=!1,n=null;return async function(){if(e!==null)return e;if(r&&n)return n;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return n=t(),e=await n,e}finally{r=!1,n=null}}}function Yo(t,e){return new Proxy({},{get(r,n){if(e.includes(n)){let o=t(),s=o[n];return typeof s=="function"?s.bind(o):s}return t()[n]}})}var Yt=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,r,n={}){if(this.instances.has(e))return this.instances.get(e);if(this.initialized.has(e))return this.instances.get(e);if(this.initializing.has(e))throw new Error(`Circular dependency detected for singleton: ${e}`);if(n.ssrSafe===!1&&typeof window>"u"){if(n.fallbackFactory){let i=n.fallbackFactory();return this.instances.set(e,i),this.initialized.add(e),i}throw new Error(`Singleton ${e} requires client-side environment`)}this.initializing.add(e);try{let i=await r();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(n.cacheFailures&&this.initialized.add(e),n.fallbackFactory){let o=n.fallbackFactory();return this.instances.set(e,o),this.initialized.add(e),o}throw i}finally{this.initializing.delete(e)}}static isInitialized(e){return this.initialized.has(e)}static clear(e){this.instances.delete(e),this.initialized.delete(e),this.initializing.delete(e)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function Jo(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}import"valibot";import"valibot";function Xo(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function Qo(t){if(Xo(t))return t.visibility}function bn(t,e){let r=t??"guest";return r==="hidden"?!1:r==="technical"?it(e,"admin"):it(e,r)}function Jt(t,e){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let n=r.entries,i=[];for(let[o,s]of Object.entries(n)){let c=Qo(s);bn(c,e)&&i.push(o)}return i}function Zo(t,e,r){if(!t)return{};let n=Jt(e,r),i={};for(let o of n)Object.prototype.hasOwnProperty.call(t,o)&&(i[o]=t[o]);return i}function Ue(t,e){let r=new Date(t),n=r.getDate();return r.setMonth(r.getMonth()+e),r.getDate()!==n&&r.setDate(0),r}function Xt(t,e){let r=new Date(t),n=r.getDate();return r.setFullYear(r.getFullYear()+e),r.getDate()!==n&&r.setDate(0),r}function es(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return t==="1month"?r=Ue(e,1):t==="3months"?r=Ue(e,3):t==="6months"?r=Ue(e,6):t==="1year"?r=Xt(e,1):t==="2years"?r=Xt(e,2):r=Ue(e,1),r.toISOString()}function ts(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function rs(t,e="URL"){try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return t}catch(r){throw new Error(`Invalid ${e}: ${t}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function ns(t){let e={};for(let[r,n]of Object.entries(t)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let i=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(i.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);e[r]=i}return e}function is(t,e=!0){let r=process.env[t];if(e&&!r)throw new Error(`Required environment variable '${t}' is not set`);return r||""}function os(t,e){if(!t)return null;let r=`${encodeURIComponent(e)}=`,n=t.split(";");for(let i=0;i<n.length;i++){let o=n[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(r)===0)return decodeURIComponent(o.substring(r.length,o.length))}}return null}import*as W from"valibot";import*as p from"valibot";var Me=new Map;function b(t,e){Me.set(t,e)}function ef(t){return Me.has(t)}function tf(){return Array.from(Me.keys())}function rf(){Me.clear()}function _(t,e){return e?t:p.nullish(t)}var ot=t=>{let e=[];t.validation?.minLength!==void 0&&e.push(p.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)),t.validation?.maxLength!==void 0&&e.push(p.maxLength(t.validation.maxLength,`Must be at most ${t.validation.maxLength} characters`)),t.validation?.pattern&&e.push(p.regex(new RegExp(t.validation.pattern),"Invalid format"));let r=e.length>0?p.pipe(p.string(),...e):p.string();return _(r,t.validation?.required)},ss=t=>{let e=p.pipe(p.string(),p.email("Invalid email address"));return _(e,t.validation?.required)},as=t=>{let e=t.validation?.minLength!==void 0?p.pipe(p.string(),p.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)):p.string();return _(e,t.validation?.required)},cs=t=>{let e=p.pipe(p.string(),p.url("Invalid URL"));return _(e,t.validation?.required)},Qt=t=>{let e=[];t.validation?.min!==void 0&&e.push(p.minValue(t.validation.min,`Must be at least ${t.validation.min}`)),t.validation?.max!==void 0&&e.push(p.maxValue(t.validation.max,`Must be at most ${t.validation.max}`));let r=e.length>0?p.pipe(p.number(),...e):p.number();return _(r,t.validation?.required)},Zt=t=>{let e=p.boolean();return _(e,t.validation?.required)},me=t=>{let e=p.pipe(p.string(),p.isoTimestamp("Invalid date format"));return _(e,t.validation?.required)},An=p.object({url:p.string(),filename:p.string(),size:p.number(),mimeType:p.nullish(p.string()),uploadedAt:p.nullish(p.string())}),Tn=t=>{let e=p.nullable(An);return _(e,t.validation?.required)},Sn=t=>{let e=p.array(An);return _(e,t.validation?.required)},Cn=p.object({fullUrl:p.string(),thumbUrl:p.string()}),us=t=>_(Cn,t.validation?.required),ls=t=>{let e=p.array(Cn);return _(e,t.validation?.required)},ds=t=>{let e=p.object({lat:p.number(),lng:p.number()});return _(e,t.validation?.required)},ps=t=>{let e=p.object({formatted_address:p.string(),latitude:p.number(),longitude:p.number(),street_number:p.nullish(p.string()),route:p.nullish(p.string()),locality:p.nullish(p.string()),administrative_area_level_1:p.nullish(p.string()),administrative_area_level_2:p.nullish(p.string()),country:p.nullish(p.string()),postal_code:p.nullish(p.string())});return _(e,t.validation?.required)},fs=t=>{let e=p.record(p.string(),p.unknown());return _(e,t.validation?.required)},hs=t=>{let e=p.array(p.unknown());return _(e,t.validation?.required)},er=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let n=e.map(o=>o.value),i=p.picklist(n);return _(i,t.validation?.required)}let r=p.union([p.string(),p.number()]);return _(r,t.validation?.required)},ms=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let n=e.map(o=>o.value),i=p.array(p.picklist(n));return _(i,t.validation?.required)}let r=p.array(p.string());return _(r,t.validation?.required)},gs=t=>{let e=p.pipe(p.string(),p.regex(rt,"Invalid ID format"));return _(e,t.validation?.required)},tr=t=>{let e=p.string();return _(e,t.validation?.required)},vs=t=>{let e=p.string();return _(e,t.validation?.required)},_n=()=>p.never(),ys=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let n=[e.checkedValue,e.uncheckedValue],i=p.picklist(n);return _(i,t.validation?.required)}let r=p.boolean();return _(r,t.validation?.required)};function Es(){b("text",ot),b("textarea",ot),b("richtext",ot),b("color",ot),b("email",ss),b("password",as),b("url",cs),b("tel",vs),b("number",Qt),b("range",Qt),b("year",Qt),b("boolean",Zt),b("checkbox",Zt),b("gdprConsent",Zt),b("date",me),b("datetime-local",me),b("time",me),b("week",me),b("month",me),b("timestamp",me),b("file",Tn),b("files",Sn),b("document",Tn),b("documents",Sn),b("image",us),b("images",ls),b("geopoint",ds),b("address",ps),b("map",fs),b("array",hs),b("select",er),b("multiselect",ms),b("radio",er),b("combobox",er),b("switch",ys),b("reference",gs),b("hidden",tr),b("avatar",tr),b("badge",tr),b("submit",_n),b("reset",_n)}Es();function Fe(t){if(t.validation?.schema){let n=t.validation.schema;return _(n,t.validation?.required)}let e=Me.get(t.type);if(e){let n=e(t);if(n!==null)return n}let r=p.unknown();return _(r,t.validation?.required)}var rr=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],sf="available",af=["draft","deleted"],ge=["id","createdAt","updatedAt","createdById","updatedById"],bs=[...ge,"status"];function cf(t){return bs.includes(t)}function uf(t){return ge.includes(t)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...rr]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:rt.source}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};function Ve(t,e){return Object.assign(t,{visibility:e})}function se(t,e){let r=t;return r.metadata={collection:e.collection,entity:e.name},r}function wn(t){let e=Fe(t);return Ve(e,t.visibility)}function Pn(t){let e=Fe({...t,validation:{...t.validation,required:!1}});return Ve(e,t.visibility)}function Is(t){let e=t.fields,r={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(r[R]=wn(P));let n=se(W.object(r),t),i={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(ge.includes(R)||(i[R]=wn(P)));let o=se(W.object(i),t),s={};for(let[R,P]of Object.entries(e))if(P.visibility!=="hidden"&&!ge.includes(R))if(R==="status"){let Y=W.literal("draft");s[R]=Ve(Y,P.visibility)}else s[R]=Pn(P);let c=se(W.object(s),t),u={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(ge.includes(R)||(u[R]=Pn(P)));u.id=Ve(Fe(w.id),"technical");let d=se(W.object(u),t),g;if(t.listFields&&t.listFields.length>0){let R=["id","status"],P=[...new Set([...R,...t.listFields])];g={};for(let Y of P){let xe=r[Y];xe&&(g[Y]=xe)}}else g=r;let T=se(W.object(g),t),O,F=t.listCardFields??t.listFields;if(F&&F.length>0){let R=["id","status"],P=[...new Set([...R,...F])];O={};for(let Y of P){let xe=r[Y];xe&&(O[Y]=xe)}}else O=r;let ne=se(W.object(O),t),et=se(W.object({id:Ve(Fe(w.id),"technical")}),t);return{create:o,draft:c,update:d,get:n,list:T,listCard:ne,delete:et}}import"valibot";function yf(t,e){let r=t;return r.metadata=e,r}var Ts={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var Rn=function(t){let e=[],r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=i&63|128):(i&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=i&63|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=i&63|128)}return e},Ss=function(t){let e=[],r=0,n=0;for(;r<t.length;){let i=t[r++];if(i<128)e[n++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[r++];e[n++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[r++],s=t[r++],c=t[r++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[n++]=String.fromCharCode(55296+(u>>10)),e[n++]=String.fromCharCode(56320+(u&1023))}else{let o=t[r++],s=t[r++];e[n++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},kn={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();let r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let i=0;i<t.length;i+=3){let o=t[i],s=i+1<t.length,c=s?t[i+1]:0,u=i+2<t.length,d=u?t[i+2]:0,g=o>>2,T=(o&3)<<4|c>>4,O=(c&15)<<2|d>>6,F=d&63;u||(F=64,s||(O=64)),n.push(r[g],r[T],r[O],r[F])}return n.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(Rn(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):Ss(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let r=e?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let i=0;i<t.length;){let o=r[t.charAt(i++)],c=i<t.length?r[t.charAt(i)]:0;++i;let d=i<t.length?r[t.charAt(i)]:64;++i;let T=i<t.length?r[t.charAt(i)]:64;if(++i,o==null||c==null||d==null||T==null)throw new ir;let O=o<<2|c>>4;if(n.push(O),d!==64){let F=c<<4&240|d>>2;if(n.push(F),T!==64){let ne=d<<6&192|T;n.push(ne)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},ir=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},_s=function(t){let e=Rn(t);return kn.encodeByteArray(e,!0)},sr=function(t){return _s(t).replace(/\./g,"")},ar=function(t){try{return kn.decodeString(t,!0)}catch{}return null};function cr(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function B(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function xn(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(B())}function On(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Dn(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Nn(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Ln(){try{return typeof indexedDB=="object"}catch{return!1}}function Un(){return new Promise((t,e)=>{try{let r=!0,n="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(n);i.onsuccess=()=>{i.result.close(),r||self.indexedDB.deleteDatabase(n),t(!0)},i.onupgradeneeded=()=>{r=!1},i.onerror=()=>{e(i.error?.message||"")}}catch(r){e(r)}})}var As="FirebaseError",q=class t extends Error{constructor(e,r,n){super(r),this.code=e,this.customData=n,this.name=As,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,J.prototype.create)}},J=class{constructor(e,r,n){this.service=e,this.serviceName=r,this.errors=n}create(e,...r){let n=r[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?Cs(o,n):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new q(i,c,n)}};function Cs(t,e){return t.replace(ws,(r,n)=>{let i=e[n];return i!=null?String(i):`<${n}?>`})}var ws=/\{\$([^}]+)}/g;function st(t){let e=[];for(let[r,n]of Object.entries(t))Array.isArray(n)?n.forEach(i=>{e.push(encodeURIComponent(r)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return e.length?"&"+e.join("&"):""}function ve(t){let e={};return t.replace(/^\?/,"").split("&").forEach(n=>{if(n){let[i,o]=n.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function ye(t){let e=t.indexOf("?");if(!e)return"";let r=t.indexOf("#",e);return t.substring(e,r>0?r:void 0)}function Mn(t,e){let r=new or(t,e);return r.subscribe.bind(r)}var or=class{constructor(e,r){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=r,this.task.then(()=>{e(this)}).catch(n=>{this.error(n)})}next(e){this.forEachObserver(r=>{r.next(e)})}error(e){this.forEachObserver(r=>{r.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,r,n){let i;if(e===void 0&&r===void 0&&n===void 0)throw new Error("Missing Observer.");Ps(e,["next","error","complete"])?i=e:i={next:e,error:r,complete:n},i.next===void 0&&(i.next=nr),i.error===void 0&&(i.error=nr),i.complete===void 0&&(i.complete=nr);let o=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),o}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let r=0;r<this.observers.length;r++)this.sendOne(r,e)}sendOne(e,r){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{r(this.observers[e])}catch{}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}};function Ps(t,e){if(typeof t!="object"||t===null)return!1;for(let r of e)if(r in t&&typeof t[r]=="function")return!0;return!1}function nr(){}var Sf=14400*1e3;function Be(t){return t&&t._delegate?t._delegate:t}Ts.NODE_CLIENT=!0;var X=class{constructor(e,r,n){this.name=e,this.instanceFactory=r,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var Rs=[],S;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(S||(S={}));var ks={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},xs=S.INFO,Os={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},Ds=(t,e,...r)=>{if(e<t.logLevel)return;let n=new Date().toISOString(),i=Os[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},Ee=class{constructor(e){this.name=e,this._logLevel=xs,this._logHandler=Ds,this._userLogHandler=null,Rs.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in S))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?ks[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,S.DEBUG,...e),this._logHandler(this,S.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,S.VERBOSE,...e),this._logHandler(this,S.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,S.INFO,...e),this._logHandler(this,S.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,S.WARN,...e),this._logHandler(this,S.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,S.ERROR,...e),this._logHandler(this,S.ERROR,...e)}};var Ns=(t,e)=>e.some(r=>t instanceof r),Fn,Vn;function Ls(){return Fn||(Fn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Us(){return Vn||(Vn=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Bn=new WeakMap,lr=new WeakMap,Hn=new WeakMap,ur=new WeakMap,pr=new WeakMap;function Ms(t){let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{r(G(t.result)),i()},s=()=>{n(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(r=>{r instanceof IDBCursor&&Bn.set(r,t)}).catch(()=>{}),pr.set(e,t),e}function Fs(t){if(lr.has(t))return;let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{r(),i()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});lr.set(t,e)}var dr={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return lr.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Hn.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return G(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function $n(t){dr=t(dr)}function Vs(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(at(this),e,...r);return Hn.set(n,e.sort?e.sort():[e]),G(n)}:Us().includes(t)?function(...e){return t.apply(at(this),e),G(Bn.get(this))}:function(...e){return G(t.apply(at(this),e))}}function Bs(t){return typeof t=="function"?Vs(t):(t instanceof IDBTransaction&&Fs(t),Ns(t,Ls())?new Proxy(t,dr):t)}function G(t){if(t instanceof IDBRequest)return Ms(t);if(ur.has(t))return ur.get(t);let e=Bs(t);return e!==t&&(ur.set(t,e),pr.set(e,t)),e}var at=t=>pr.get(t);function qn(t,e,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=G(s);return n&&s.addEventListener("upgradeneeded",u=>{n(G(s.result),u.oldVersion,u.newVersion,G(s.transaction),u)}),r&&s.addEventListener("blocked",u=>r(u.oldVersion,u.newVersion,u)),c.then(u=>{o&&u.addEventListener("close",()=>o()),i&&u.addEventListener("versionchange",d=>i(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}var Hs=["get","getKey","getAll","getAllKeys","count"],$s=["put","add","delete","clear"],fr=new Map;function Wn(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(fr.get(e))return fr.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,i=$s.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||Hs.includes(r)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),d=u.store;return n&&(d=d.index(c.shift())),(await Promise.all([d[r](...c),i&&u.done]))[0]};return fr.set(e,o),o}$n(t=>({...t,get:(e,r,n)=>Wn(e,r)||t.get(e,r,n),has:(e,r)=>!!Wn(e,r)||t.has(e,r)}));var mr=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(r=>{if(qs(r)){let n=r.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(r=>r).join(" ")}};function qs(t){return t.getComponent()?.type==="VERSION"}var gr="@firebase/app",Gn="0.14.6";var Q=new Ee("@firebase/app"),Gs="@firebase/app-compat",js="@firebase/analytics-compat",zs="@firebase/analytics",Ks="@firebase/app-check-compat",Ys="@firebase/app-check",Js="@firebase/auth",Xs="@firebase/auth-compat",Qs="@firebase/database",Zs="@firebase/data-connect",ea="@firebase/database-compat",ta="@firebase/functions",ra="@firebase/functions-compat",na="@firebase/installations",ia="@firebase/installations-compat",oa="@firebase/messaging",sa="@firebase/messaging-compat",aa="@firebase/performance",ca="@firebase/performance-compat",ua="@firebase/remote-config",la="@firebase/remote-config-compat",da="@firebase/storage",pa="@firebase/storage-compat",fa="@firebase/firestore",ha="@firebase/ai",ma="@firebase/firestore-compat",ga="firebase",va="12.6.0";var ya={[gr]:"fire-core",[Gs]:"fire-core-compat",[zs]:"fire-analytics",[js]:"fire-analytics-compat",[Ys]:"fire-app-check",[Ks]:"fire-app-check-compat",[Js]:"fire-auth",[Xs]:"fire-auth-compat",[Qs]:"fire-rtdb",[Zs]:"fire-data-connect",[ea]:"fire-rtdb-compat",[ta]:"fire-fn",[ra]:"fire-fn-compat",[na]:"fire-iid",[ia]:"fire-iid-compat",[oa]:"fire-fcm",[sa]:"fire-fcm-compat",[aa]:"fire-perf",[ca]:"fire-perf-compat",[ua]:"fire-rc",[la]:"fire-rc-compat",[da]:"fire-gcs",[pa]:"fire-gcs-compat",[fa]:"fire-fst",[ma]:"fire-fst-compat",[ha]:"fire-vertex","fire-js":"fire-js",[ga]:"fire-js-all"};var Ea=new Map,ba=new Map,jn=new Map;function zn(t,e){try{t.container.addComponent(e)}catch(r){Q.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,r)}}function Ie(t){let e=t.name;if(jn.has(e))return Q.debug(`There were multiple attempts to register component ${e}.`),!1;jn.set(e,t);for(let r of Ea.values())zn(r,t);for(let r of ba.values())zn(r,t);return!0}function ae(t){return t==null?!1:t.settings!==void 0}var Ia={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Er=new J("app","Firebase",Ia);var ct=va;function be(t,e,r){let n=ya[t]??t;r&&(n+=`-${r}`);let i=n.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${n}" with version "${e}":`];i&&s.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&o&&s.push("and"),o&&s.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Q.warn(s.join(" "));return}Ie(new X(`${n}-version`,()=>({library:n,version:e}),"VERSION"))}var Ta="firebase-heartbeat-database",Sa=1,He="firebase-heartbeat-store",hr=null;function Xn(){return hr||(hr=qn(Ta,Sa,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(He)}catch{}}}}).catch(t=>{throw Er.create("idb-open",{originalErrorMessage:t.message})})),hr}async function _a(t){try{let r=(await Xn()).transaction(He),n=await r.objectStore(He).get(Qn(t));return await r.done,n}catch(e){if(e instanceof q)Q.warn(e.message);else{let r=Er.create("idb-get",{originalErrorMessage:e?.message});Q.warn(r.message)}}}async function Kn(t,e){try{let n=(await Xn()).transaction(He,"readwrite");await n.objectStore(He).put(e,Qn(t)),await n.done}catch(r){if(r instanceof q)Q.warn(r.message);else{let n=Er.create("idb-set",{originalErrorMessage:r?.message});Q.warn(n.message)}}}function Qn(t){return`${t.name}!${t.options.appId}`}var Aa=1024,Ca=30,vr=class{constructor(e){this.container=e,this._heartbeatsCache=null;let r=this.container.getProvider("app").getImmediate();this._storage=new yr(r),this._heartbeatsCachePromise=this._storage.read().then(n=>(this._heartbeatsCache=n,n))}async triggerHeartbeat(){try{let r=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),n=Yn();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===n||this._heartbeatsCache.heartbeats.some(i=>i.date===n))return;if(this._heartbeatsCache.heartbeats.push({date:n,agent:r}),this._heartbeatsCache.heartbeats.length>Ca){let i=Pa(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){Q.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";let e=Yn(),{heartbeatsToSend:r,unsentEntries:n}=wa(this._heartbeatsCache.heartbeats),i=sr(JSON.stringify({version:2,heartbeats:r}));return this._heartbeatsCache.lastSentHeartbeatDate=e,n.length>0?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Q.warn(e),""}}};function Yn(){return new Date().toISOString().substring(0,10)}function wa(t,e=Aa){let r=[],n=t.slice();for(let i of t){let o=r.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),Jn(r)>e){o.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),Jn(r)>e){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}}var yr=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Ln()?Un().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let r=await _a(this.app);return r?.heartbeats?r:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let n=await this.read();return Kn(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let n=await this.read();return Kn(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}else return}};function Jn(t){return sr(JSON.stringify({version:2,heartbeats:t})).length}function Pa(t){if(t.length===0)return-1;let e=0,r=t[0].date;for(let n=1;n<t.length;n++)t[n].date<r&&(r=t[n].date,e=n);return e}function Ra(t){Ie(new X("platform-logger",e=>new mr(e),"PRIVATE")),Ie(new X("heartbeat",e=>new vr(e),"PRIVATE")),be(gr,Gn,t),be(gr,Gn,"esm2020"),be("fire-js","")}Ra("");function ai(){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 ci=ai,ui=new J("auth","Firebase",ai());var ft=new Ee("@firebase/auth");function ka(t,...e){ft.logLevel<=S.WARN&&ft.warn(`Auth (${ct}): ${t}`,...e)}function dt(t,...e){ft.logLevel<=S.ERROR&&ft.error(`Auth (${ct}): ${t}`,...e)}function Te(t,...e){throw Fr(t,...e)}function Mr(t,...e){return Fr(t,...e)}function li(t,e,r){let n={...ci(),[e]:r};return new J("auth","Firebase",n).create(e,{appName:t.name})}function pt(t){return li(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Fr(t,...e){if(typeof t!="string"){let r=e[0],n=[...e.slice(1)];return n[0]&&(n[0].appName=t.name),t._errorFactory.create(r,...n)}return ui.create(t,...e)}function I(t,e,...r){if(!t)throw Fr(e,...r)}function j(t){let e="INTERNAL ASSERTION FAILED: "+t;throw dt(e),new Error(e)}function ht(t,e){t||j(e)}function xa(){return Zn()==="http:"||Zn()==="https:"}function Zn(){return typeof self<"u"&&self.location?.protocol||null}function Oa(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(xa()||Dn()||"connection"in navigator)?navigator.onLine:!0}function Da(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var Sr=class{constructor(e,r){this.shortDelay=e,this.longDelay=r,ht(r>e,"Short delay should be less than long delay!"),this.isMobile=xn()||Nn()}get(){return Oa()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function Na(t,e){ht(t.emulator,"Emulator should always be set here");let{url:r}=t.emulator;return e?`${r}${e.startsWith("/")?e.slice(1):e}`:r}var Ge=class{static initialize(e,r,n){this.fetchImpl=e,r&&(this.headersImpl=r),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;j("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;j("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;j("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var La={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"};var Ua=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],Ma=new Sr(3e4,6e4);function z(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function K(t,e,r,n,i={}){return di(t,i,async()=>{let o={},s={};n&&(e==="GET"?s=n:o={body:JSON.stringify(n)});let c=st({key:t.config.apiKey,...s}).slice(1),u=await t._getAdditionalHeaders();u["Content-Type"]="application/json",t.languageCode&&(u["X-Firebase-Locale"]=t.languageCode);let d={method:e,headers:u,...o};return On()||(d.referrerPolicy="no-referrer"),t.emulatorConfig&&cr(t.emulatorConfig.host)&&(d.credentials="include"),Ge.fetch()(await pi(t,t.config.apiHost,r,c),d)})}async function di(t,e,r){t._canInitEmulator=!1;let n={...La,...e};try{let i=new _r(t),o=await Promise.race([r(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw ut(t,"account-exists-with-different-credential",s);if(o.ok&&!("errorMessage"in s))return s;{let c=o.ok?s.errorMessage:s.error.message,[u,d]=c.split(" : ");if(u==="FEDERATED_USER_ID_ALREADY_LINKED")throw ut(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw ut(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw ut(t,"user-disabled",s);let g=n[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(d)throw li(t,g,d);Te(t,g)}}catch(i){if(i instanceof q)throw i;Te(t,"network-request-failed",{message:String(i)})}}async function At(t,e,r,n,i={}){let o=await K(t,e,r,n,i);return"mfaPendingCredential"in o&&Te(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function pi(t,e,r,n){let i=`${e}${r}?${n}`,o=t,s=o.config.emulator?Na(t.config,i):`${t.config.apiScheme}://${i}`;return Ua.includes(r)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function Fa(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var _r=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((r,n)=>{this.timer=setTimeout(()=>n(Mr(this.auth,"network-request-failed")),Ma.get())})}};function ut(t,e,r){let n={appName:t.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);let i=Mr(t,e,n);return i.customData._tokenResponse=r,i}function ei(t){return t!==void 0&&t.enterprise!==void 0}var Ar=class{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(let r of this.recaptchaEnforcementState)if(r.provider&&r.provider===e)return Fa(r.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 Va(t,e){return K(t,"GET","/v2/recaptchaConfig",z(t,e))}async function Ba(t,e){return K(t,"POST","/v1/accounts:delete",e)}async function mt(t,e){return K(t,"POST","/v1/accounts:lookup",e)}function We(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function fi(t,e=!1){let r=Be(t),n=await r.getIdToken(e),i=hi(n);I(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:n,authTime:We(br(i.auth_time)),issuedAtTime:We(br(i.iat)),expirationTime:We(br(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function br(t){return Number(t)*1e3}function hi(t){let[e,r,n]=t.split(".");if(e===void 0||r===void 0||n===void 0)return dt("JWT malformed, contained fewer than 3 sections"),null;try{let i=ar(r);return i?JSON.parse(i):(dt("Failed to decode base64 JWT payload"),null)}catch(i){return dt("Caught error parsing JWT payload as JSON",i?.toString()),null}}function ti(t){let e=hi(t);return I(e,"internal-error"),I(typeof e.exp<"u","internal-error"),I(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Cr(t,e,r=!1){if(r)return e;try{return await e}catch(n){throw n instanceof q&&Ha(n)&&t.auth.currentUser===t&&await t.auth.signOut(),n}}function Ha({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var wr=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 r=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),r}else{this.errorBackoff=3e4;let n=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,n)}}schedule(e=!1){if(!this.isRunning)return;let r=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},r)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var je=class{constructor(e,r){this.createdAt=e,this.lastLoginAt=r,this._initializeTime()}_initializeTime(){this.lastSignInTime=We(this.lastLoginAt),this.creationTime=We(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function gt(t){let e=t.auth,r=await t.getIdToken(),n=await Cr(t,mt(e,{idToken:r}));I(n?.users.length,e,"internal-error");let i=n.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?gi(i.providerUserInfo):[],s=$a(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,d=c?u:!1,g={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:s,metadata:new je(i.createdAt,i.lastLoginAt),isAnonymous:d};Object.assign(t,g)}async function mi(t){let e=Be(t);await gt(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function $a(t,e){return[...t.filter(n=>!e.some(i=>i.providerId===n.providerId)),...e]}function gi(t){return t.map(({providerId:e,...r})=>({providerId:e,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}))}async function Wa(t,e){let r=await di(t,{},async()=>{let n=st({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await pi(t,i,"/v1/token",`key=${o}`),c=await t._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";let u={method:"POST",headers:c,body:n};return t.emulatorConfig&&cr(t.emulatorConfig.host)&&(u.credentials="include"),Ge.fetch()(s,u)});return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}async function qa(t,e){return K(t,"POST","/v2/accounts:revokeToken",z(t,e))}var qe=class t{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){I(e.idToken,"internal-error"),I(typeof e.idToken<"u","internal-error"),I(typeof e.refreshToken<"u","internal-error");let r="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):ti(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,r)}updateFromIdToken(e){I(e.length!==0,"internal-error");let r=ti(e);this.updateTokensAndExpiration(e,null,r)}async getToken(e,r=!1){return!r&&this.accessToken&&!this.isExpired?this.accessToken:(I(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,r){let{accessToken:n,refreshToken:i,expiresIn:o}=await Wa(e,r);this.updateTokensAndExpiration(n,i,Number(o))}updateTokensAndExpiration(e,r,n){this.refreshToken=r||null,this.accessToken=e||null,this.expirationTime=Date.now()+n*1e3}static fromJSON(e,r){let{refreshToken:n,accessToken:i,expirationTime:o}=r,s=new t;return n&&(I(typeof n=="string","internal-error",{appName:e}),s.refreshToken=n),i&&(I(typeof i=="string","internal-error",{appName:e}),s.accessToken=i),o&&(I(typeof o=="number","internal-error",{appName:e}),s.expirationTime=o),s}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 t,this.toJSON())}_performRefresh(){return j("not implemented")}};function ee(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var ce=class t{constructor({uid:e,auth:r,stsTokenManager:n,...i}){this.providerId="firebase",this.proactiveRefresh=new wr(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=r,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new je(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let r=await Cr(this,this.stsTokenManager.getToken(this.auth,e));return I(r,this.auth,"internal-error"),this.accessToken!==r&&(this.accessToken=r,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),r}getIdTokenResult(e){return fi(this,e)}reload(){return mi(this)}_assign(e){this!==e&&(I(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(r=>({...r})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let r=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return r.metadata._copy(this.metadata),r}_onReload(e){I(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,r=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),r&&await gt(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(ae(this.auth.app))return Promise.reject(pt(this.auth));let e=await this.getIdToken();return await Cr(this,Ba(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,r){let n=r.displayName??void 0,i=r.email??void 0,o=r.phoneNumber??void 0,s=r.photoURL??void 0,c=r.tenantId??void 0,u=r._redirectEventId??void 0,d=r.createdAt??void 0,g=r.lastLoginAt??void 0,{uid:T,emailVerified:O,isAnonymous:F,providerData:ne,stsTokenManager:et}=r;I(T&&et,e,"internal-error");let R=qe.fromJSON(this.name,et);I(typeof T=="string",e,"internal-error"),ee(n,e.name),ee(i,e.name),I(typeof O=="boolean",e,"internal-error"),I(typeof F=="boolean",e,"internal-error"),ee(o,e.name),ee(s,e.name),ee(c,e.name),ee(u,e.name),ee(d,e.name),ee(g,e.name);let P=new t({uid:T,auth:e,email:i,emailVerified:O,displayName:n,isAnonymous:F,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:R,createdAt:d,lastLoginAt:g});return ne&&Array.isArray(ne)&&(P.providerData=ne.map(Y=>({...Y}))),u&&(P._redirectEventId=u),P}static async _fromIdTokenResponse(e,r,n=!1){let i=new qe;i.updateFromServerResponse(r);let o=new t({uid:r.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await gt(o),o}static async _fromGetAccountInfoResponse(e,r,n){let i=r.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?gi(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new qe;c.updateFromIdToken(n);let u=new t({uid:i.localId,auth:e,stsTokenManager:c,isAnonymous:s}),d={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:o,metadata:new je(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,d),u}};var ri=new Map;function ue(t){ht(t instanceof Function,"Expected a class definition");let e=ri.get(t);return e?(ht(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,ri.set(t,e),e)}var vt=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,r){this.storage[e]=r}async _get(e){let r=this.storage[e];return r===void 0?null:r}async _remove(e){delete this.storage[e]}_addListener(e,r){}_removeListener(e,r){}};vt.type="NONE";var Pr=vt;function Ir(t,e,r){return`firebase:${t}:${e}:${r}`}var yt=class t{constructor(e,r,n){this.persistence=e,this.auth=r,this.userKey=n;let{config:i,name:o}=this.auth;this.fullUserKey=Ir(this.userKey,i.apiKey,o),this.fullPersistenceKey=Ir("persistence",i.apiKey,o),this.boundEventHandler=r._onStorageEvent.bind(r),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 r=await mt(this.auth,{idToken:e}).catch(()=>{});return r?ce._fromGetAccountInfoResponse(this.auth,r,e):null}return ce._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 r=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,r)return this.setCurrentUser(r)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,r,n="authUser"){if(!r.length)return new t(ue(Pr),e,n);let i=(await Promise.all(r.map(async d=>{if(await d._isAvailable())return d}))).filter(d=>d),o=i[0]||ue(Pr),s=Ir(n,e.config.apiKey,e.name),c=null;for(let d of r)try{let g=await d._get(s);if(g){let T;if(typeof g=="string"){let O=await mt(e,{idToken:g}).catch(()=>{});if(!O)break;T=await ce._fromGetAccountInfoResponse(e,O,g)}else T=ce._fromJSON(e,g);d!==o&&(c=T),o=d;break}}catch{}let u=i.filter(d=>d._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,n):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(r.map(async d=>{if(d!==o)try{await d._remove(s)}catch{}})),new t(o,e,n))}};function ni(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(Ka(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Ga(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(Ja(e))return"Blackberry";if(Xa(e))return"Webos";if(ja(e))return"Safari";if((e.includes("chrome/")||za(e))&&!e.includes("edge/"))return"Chrome";if(Ya(e))return"Android";{let r=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=t.match(r);if(n?.length===2)return n[1]}return"Other"}function Ga(t=B()){return/firefox\//i.test(t)}function ja(t=B()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function za(t=B()){return/crios\//i.test(t)}function Ka(t=B()){return/iemobile/i.test(t)}function Ya(t=B()){return/android/i.test(t)}function Ja(t=B()){return/blackberry/i.test(t)}function Xa(t=B()){return/webos/i.test(t)}function vi(t,e=[]){let r;switch(t){case"Browser":r=ni(B());break;case"Worker":r=`${ni(B())}-${t}`;break;default:r=t}let n=e.length?e.join(","):"FirebaseCore-web";return`${r}/JsCore/${ct}/${n}`}var Rr=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,r){let n=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});n.onAbort=r,this.queue.push(n);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let r=[];try{for(let n of this.queue)await n(e),n.onAbort&&r.push(n.onAbort)}catch(n){r.reverse();for(let i of r)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:n?.message})}}};async function Qa(t,e={}){return K(t,"GET","/v2/passwordPolicy",z(t,e))}var Za=6,kr=class{constructor(e){let r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=r.minPasswordLength??Za,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),r.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),r.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),r.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),r.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.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 r={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,r),this.validatePasswordCharacterOptions(e,r),r.isValid&&(r.isValid=r.meetsMinPasswordLength??!0),r.isValid&&(r.isValid=r.meetsMaxPasswordLength??!0),r.isValid&&(r.isValid=r.containsLowercaseLetter??!0),r.isValid&&(r.isValid=r.containsUppercaseLetter??!0),r.isValid&&(r.isValid=r.containsNumericCharacter??!0),r.isValid&&(r.isValid=r.containsNonAlphanumericCharacter??!0),r}validatePasswordLengthOptions(e,r){let n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(r.meetsMinPasswordLength=e.length>=n),i&&(r.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,r){this.updatePasswordCharacterOptionsStatuses(r,!1,!1,!1,!1);let n;for(let i=0;i<e.length;i++)n=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(r,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,r,n,i,o){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=r)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=o))}};var Et=class{constructor(e,r,n,i){this.app=e,this.heartbeatServiceProvider=r,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new bt(this),this.idTokenSubscription=new bt(this),this.beforeStateQueue=new Rr(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=ui,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=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(o=>this._resolvePersistenceManagerAvailable=o)}_initializeWithPersistence(e,r){return r&&(this._popupRedirectResolver=ue(r)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await yt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(r),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 r=await mt(this,{idToken:e}),n=await ce._fromGetAccountInfoResponse(this,r,e);await this.directlySetCurrentUser(n)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(ae(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let r=await this.assertedPersistence.getCurrentUser(),n=r,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=n?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(n=c.user,i=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(n)}catch(o){n=r,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return I(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 r=null;try{r=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return r}async reloadAndSetCurrentUserOrClear(e){try{await gt(e)}catch(r){if(r?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=Da()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(ae(this.app))return Promise.reject(pt(this));let r=e?Be(e):null;return r&&I(r.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,r=!1){if(!this._deleted)return e&&I(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),r||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return ae(this.app)?Promise.reject(pt(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return ae(this.app)?Promise.reject(pt(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(ue(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let r=this._getPasswordPolicyInternal();return r.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):r.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=await Qa(this),r=new kr(e);this.tenantId===null?this._projectPasswordPolicy=r:this._tenantPasswordPolicies[this.tenantId]=r}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new J("auth","Firebase",e())}onAuthStateChanged(e,r,n){return this.registerStateListener(this.authStateSubscription,e,r,n)}beforeAuthStateChanged(e,r){return this.beforeStateQueue.pushCallback(e,r)}onIdTokenChanged(e,r,n){return this.registerStateListener(this.idTokenSubscription,e,r,n)}authStateReady(){return new Promise((e,r)=>{if(this.currentUser)e();else{let n=this.onAuthStateChanged(()=>{n(),e()},r)}})}async revokeAccessToken(e){if(this.currentUser){let r=await this.currentUser.getIdToken(),n={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:r};this.tenantId!=null&&(n.tenantId=this.tenantId),await qa(this,n)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,r){let n=await this.getOrInitRedirectPersistenceManager(r);return e===null?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let r=e&&ue(e)||this._popupRedirectResolver;I(r,this,"argument-error"),this.redirectPersistenceManager=await yt.create(this,[ue(r._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,r,n,i){if(this._deleted)return()=>{};let o=typeof r=="function"?r:r.next.bind(r),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof r=="function"){let u=e.addObserver(r,n,i);return()=>{s=!0,u()}}else{let u=e.addObserver(r);return()=>{s=!0,u()}}}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 I(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=vi(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 r=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();r&&(e["X-Firebase-Client"]=r);let n=await this._getAppCheckToken();return n&&(e["X-Firebase-AppCheck"]=n),e}async _getAppCheckToken(){if(ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&ka(`Error while retrieving App Check token: ${e.error}`),e?.token}};function yi(t){return Be(t)}var bt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Mn(r=>this.observer=r)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var Ei={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function ec(t){return Ei.loadJS(t)}function tc(){return Ei.recaptchaEnterpriseScript}var xr=class{constructor(){this.enterprise=new Or}ready(e){e()}execute(e,r){return Promise.resolve("token")}render(e,r){return""}},Or=class{ready(e){e()}execute(e,r){return Promise.resolve("token")}render(e,r){return""}},rc="recaptcha-enterprise",bi="NO_RECAPTCHA",Dr=class{constructor(e){this.type=rc,this.auth=yi(e)}async verify(e="verify",r=!1){async function n(o){if(!r){if(o.tenantId==null&&o._agentRecaptchaConfig!=null)return o._agentRecaptchaConfig.siteKey;if(o.tenantId!=null&&o._tenantRecaptchaConfigs[o.tenantId]!==void 0)return o._tenantRecaptchaConfigs[o.tenantId].siteKey}return new Promise(async(s,c)=>{Va(o,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(u=>{if(u.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{let d=new Ar(u);return o.tenantId==null?o._agentRecaptchaConfig=d:o._tenantRecaptchaConfigs[o.tenantId]=d,s(d.siteKey)}}).catch(u=>{c(u)})})}function i(o,s,c){let u=window.grecaptcha;ei(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(d=>{s(d)}).catch(()=>{s(bi)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new xr().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{n(this.auth).then(c=>{if(!r&&ei(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=tc();u.length!==0&&(u+=c),ec(u).then(()=>{i(c,o,s)}).catch(d=>{s(d)})}}).catch(c=>{s(c)})})}};async function $e(t,e,r,n=!1,i=!1){let o=new Dr(t),s;if(i)s=bi;else try{s=await o.verify(r)}catch{s=await o.verify(r,!0)}let c={...e};if(r==="mfaSmsEnrollment"||r==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){let u=c.phoneEnrollmentInfo.phoneNumber,d=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:u,recaptchaToken:d,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){let u=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:u,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return n?Object.assign(c,{captchaResp:s}):Object.assign(c,{captchaResponse:s}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function ii(t,e,r,n,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await $e(t,e,r,r==="getOobCode");return n(t,o)}else return n(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await $e(t,e,r,r==="getOobCode");return n(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await $e(t,e,r);return n(t,o).catch(async s=>{if(t._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"&&(s.code==="auth/missing-recaptcha-token"||s.code==="auth/invalid-app-credential")){let c=await $e(t,e,r,!1,!0);return n(t,c)}return Promise.reject(s)})}else{let o=await $e(t,e,r,!1,!0);return n(t,o)}else return Promise.reject(i+" provider is not supported.")}function nc(t,e){let r=e?.persistence||[],n=(Array.isArray(r)?r:[r]).map(ue);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(n,e?.popupRedirectResolver)}var ze=class{constructor(e,r){this.providerId=e,this.signInMethod=r}toJSON(){return j("not implemented")}_getIdTokenResponse(e){return j("not implemented")}_linkToIdToken(e,r){return j("not implemented")}_getReauthenticationResolver(e){return j("not implemented")}};async function ic(t,e){return K(t,"POST","/v1/accounts:signUp",e)}async function oc(t,e){return At(t,"POST","/v1/accounts:signInWithPassword",z(t,e))}async function sc(t,e){return At(t,"POST","/v1/accounts:signInWithEmailLink",z(t,e))}async function ac(t,e){return At(t,"POST","/v1/accounts:signInWithEmailLink",z(t,e))}var Ke=class t extends ze{constructor(e,r,n,i=null){super("password",n),this._email=e,this._password=r,this._tenantId=i}static _fromEmailAndPassword(e,r){return new t(e,r,"password")}static _fromEmailAndCode(e,r,n=null){return new t(e,r,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let r=typeof e=="string"?JSON.parse(e):e;if(r?.email&&r?.password){if(r.signInMethod==="password")return this._fromEmailAndPassword(r.email,r.password);if(r.signInMethod==="emailLink")return this._fromEmailAndCode(r.email,r.password,r.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let r={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return ii(e,r,"signInWithPassword",oc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return sc(e,{email:this._email,oobCode:this._password});default:Te(e,"internal-error")}}async _linkToIdToken(e,r){switch(this.signInMethod){case"password":let n={idToken:r,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return ii(e,n,"signUpPassword",ic,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return ac(e,{idToken:r,email:this._email,oobCode:this._password});default:Te(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Tr(t,e){return At(t,"POST","/v1/accounts:signInWithIdp",z(t,e))}var cc="http://localhost",le=class t extends ze{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let r=new t(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(r.idToken=e.idToken),e.accessToken&&(r.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(r.nonce=e.nonce),e.pendingToken&&(r.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(r.accessToken=e.oauthToken,r.secret=e.oauthTokenSecret):Te("argument-error"),r}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let r=typeof e=="string"?JSON.parse(e):e,{providerId:n,signInMethod:i,...o}=r;if(!n||!i)return null;let s=new t(n,i);return s.idToken=o.idToken||void 0,s.accessToken=o.accessToken||void 0,s.secret=o.secret,s.nonce=o.nonce,s.pendingToken=o.pendingToken||null,s}_getIdTokenResponse(e){let r=this.buildRequest();return Tr(e,r)}_linkToIdToken(e,r){let n=this.buildRequest();return n.idToken=r,Tr(e,n)}_getReauthenticationResolver(e){let r=this.buildRequest();return r.autoCreate=!1,Tr(e,r)}buildRequest(){let e={requestUri:cc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let r={};this.idToken&&(r.id_token=this.idToken),this.accessToken&&(r.access_token=this.accessToken),this.secret&&(r.oauth_token_secret=this.secret),r.providerId=this.providerId,this.nonce&&!this.pendingToken&&(r.nonce=this.nonce),e.postBody=st(r)}return e}};function uc(t){switch(t){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 lc(t){let e=ve(ye(t)).link,r=e?ve(ye(e)).deep_link_id:null,n=ve(ye(t)).deep_link_id;return(n?ve(ye(n)).link:null)||n||r||e||t}var It=class t{constructor(e){let r=ve(ye(e)),n=r.apiKey??null,i=r.oobCode??null,o=uc(r.mode??null);I(n&&i&&o,"argument-error"),this.apiKey=n,this.operation=o,this.code=i,this.continueUrl=r.continueUrl??null,this.languageCode=r.lang??null,this.tenantId=r.tenantId??null}static parseLink(e){let r=lc(e);try{return new t(r)}catch{return null}}};var Se=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,r){return Ke._fromEmailAndPassword(e,r)}static credentialWithLink(e,r){let n=It.parseLink(r);return I(n,"argument-error"),Ke._fromEmailAndCode(e,n.code,n.tenantId)}};Se.PROVIDER_ID="password";Se.EMAIL_PASSWORD_SIGN_IN_METHOD="password";Se.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var Nr=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}};var _e=class extends Nr{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var Ae=class t extends _e{constructor(){super("facebook.com")}static credential(e){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Ae.FACEBOOK_SIGN_IN_METHOD="facebook.com";Ae.PROVIDER_ID="facebook.com";var Ce=class t extends _e{constructor(){super("google.com"),this.addScope("profile")}static credential(e,r){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:r})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:r,oauthAccessToken:n}=e;if(!r&&!n)return null;try{return t.credential(r,n)}catch{return null}}};Ce.GOOGLE_SIGN_IN_METHOD="google.com";Ce.PROVIDER_ID="google.com";var we=class t extends _e{constructor(){super("github.com")}static credential(e){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};we.GITHUB_SIGN_IN_METHOD="github.com";we.PROVIDER_ID="github.com";var Pe=class t extends _e{constructor(){super("twitter.com")}static credential(e,r){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:r})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:r,oauthTokenSecret:n}=e;if(!r||!n)return null;try{return t.credential(r,n)}catch{return null}}};Pe.TWITTER_SIGN_IN_METHOD="twitter.com";Pe.PROVIDER_ID="twitter.com";function dc(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:start",z(t,e))}function pc(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:finalize",z(t,e))}var oi="@firebase/auth",si="1.12.0";var Lr=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 r=this.auth.onIdTokenChanged(n=>{e(n?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,r),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let r=this.internalListeners.get(e);r&&(this.internalListeners.delete(e),r(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function fc(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function hc(t){Ie(new X("auth",(e,{options:r})=>{let n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=n.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:vi(t)},d=new Et(n,i,o,u);return nc(d,r),d},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,r,n)=>{e.getProvider("auth-internal").initialize()})),Ie(new X("auth-internal",e=>{let r=yi(e.getProvider("auth").getImmediate());return(n=>new Lr(n))(r)},"PRIVATE").setInstantiationMode("EXPLICIT")),be(oi,si,fc(t)),be(oi,si,"esm2020")}Ge.initialize(fetch,Headers,Response);hc("Node");var th=Mr("operation-not-supported-in-this-environment");Et.prototype.setPersistence=async()=>{};function mc(t,e){return K(t,"POST","/v2/accounts/mfaSignIn:finalize",z(t,e))}var Ur=class{constructor(e){this.factorId=e}_process(e,r,n){switch(r.type){case"enroll":return this._finalizeEnroll(e,r.credential,n);case"signin":return this._finalizeSignIn(e,r.credential);default:return j("unexpected MultiFactorSessionType")}}},Tt=class{static assertionForEnrollment(e,r){return St._fromSecret(e,r)}static assertionForSignIn(e,r){return St._fromEnrollmentId(e,r)}static async generateSecret(e){let r=e;I(typeof r.user?.auth<"u","internal-error");let n=await dc(r.user.auth,{idToken:r.credential,totpEnrollmentInfo:{}});return _t._fromStartTotpMfaEnrollmentResponse(n,r.user.auth)}};Tt.FACTOR_ID="totp";var St=class t extends Ur{constructor(e,r,n){super("totp"),this.otp=e,this.enrollmentId=r,this.secret=n}static _fromSecret(e,r){return new t(r,void 0,e)}static _fromEnrollmentId(e,r){return new t(r,e)}async _finalizeEnroll(e,r,n){return I(typeof this.secret<"u",e,"argument-error"),pc(e,{idToken:r,displayName:n,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,r){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let n={verificationCode:this.otp};return mc(e,{mfaPendingCredential:r,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:n})}},_t=class t{constructor(e,r,n,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=r,this.codeLength=n,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,r){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,r)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,r){let n=!1;return(lt(e)||lt(r))&&(n=!0),n&&(lt(e)&&(e=this.auth.currentUser?.email||"unknownuser"),lt(r)&&(r=this.auth.name)),`otpauth://totp/${r}:${e}?secret=${this.secretKey}&issuer=${r}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function lt(t){return typeof t>"u"||t?.length===0}import*as y from"valibot";function U(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var te=null;function Xe(){return Ti().platform}function Ti(){if(te)return te;let t=U();if(t?.platform)return te={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},te;let e=[];e.push(...vc()),e.push(...yc());let r=e.sort((n,i)=>i.confidence-n.confidence)[0];return!r||r.confidence<L.MINIMUM?(te={platform:C.UNKNOWN,mode:Ii(),context:Ec(),metadata:{detectedAt:Date.now()}},te):(te={platform:r.platform,mode:Ii(),context:r.context,version:bc(r.platform),metadata:{...r.metadata,detectedAt:Date.now()}},te)}var Ye=null,Je=null;function Si(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return Je=!0,!0;if(Je===!0)return!0;let t=U();if(t?.platform){let r=t.platform===C.NEXTJS;return r&&(Je=!0),r}let e=Xe()===C.NEXTJS;return e&&(Je=!0),e}function _i(){if(Ye!==null)return Ye;let t=U();if(t?.platform)return Ye=t.platform===C.VITE,Ye;let e=Xe()===C.VITE;return Ye=e,e}function M(){return typeof window<"u"}function Vr(){return typeof process<"u"&&!!process.versions?.node}function vc(){let t=[];if(M()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:C.VITE,confidence:L.HIGH,context:D.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=U();e?.platform===C.VITE&&t.push({platform:C.VITE,confidence:L.HIGH,context:D.CLIENT}),e?.i18n?.mapping&&t.push({platform:C.VITE,confidence:L.MEDIUM,context:D.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:C.VITE,confidence:L.LOW,context:D.CLIENT})}return Vr()&&(process.env.VITE&&t.push({platform:C.VITE,confidence:L.MEDIUM,context:D.SERVER}),process.env.npm_lifecycle_event?.includes(C.VITE)&&t.push({platform:C.VITE,confidence:L.LOW,context:D.BUILD})),t}function yc(){let t=[];return Vr()&&(process.env.NEXT_RUNTIME&&t.push({platform:C.NEXTJS,confidence:L.HIGH,context:D.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:C.NEXTJS,confidence:L.MEDIUM,context:D.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:C.NEXTJS,confidence:L.LOW,context:D.SERVER})),M()&&(U()?.platform===C.NEXTJS&&t.push({platform:C.NEXTJS,confidence:L.HIGH,context:D.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:C.NEXTJS,confidence:L.LOW,context:D.CLIENT})),t}function Ii(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===ie.PRODUCTION?ie.PRODUCTION:t===ie.TEST?ie.TEST:ie.DEVELOPMENT}function Ec(){return M()?D.CLIENT:Vr()?ie.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?D.BUILD:D.SERVER:D.CLIENT}function bc(t){if(!(typeof process>"u"))return t===C.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===C.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function Ai(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Ic(t){let e,r=U();return r?.env&&typeof r.env=="object"&&(e=r.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Ai(e)}function Tc(t){let e=U(),r;return e?.env&&typeof e.env=="object"&&(r=e.env[t]),r===void 0&&typeof process<"u"&&process.env&&(r=process.env[t]),Ai(r)}function x(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=U();if(s?.env?.MODE)return t==="DEV"?s.env.MODE==="development"?"true":"false":t==="PROD"?s.env.MODE==="production"?"true":"false":s.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let c=import.meta.env;if(t==="MODE"&&c.MODE)return c.MODE;if(t==="DEV")return c.DEV?"true":"false";if(t==="PROD")return c.PROD?"true":"false"}if(typeof process<"u"){let c="production";return t==="DEV"?c==="development"?"true":"false":t==="PROD"?c==="production"?"true":"false":c}return t==="DEV"?"true":t==="PROD"?"false":"development"}let r=U()?.platform,n=e||r||(_i()?"vite":Si()?"nextjs":Xe()),i=["MODE","DEV","PROD","SSR"],o;return n==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:n==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,n==="vite"?Ic(o):n==="nextjs"?Tc(o):void 0}function Ci(){if(typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production"))return!0;let t=x("APP_ENV"),e=x("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var wi=y.object({name:y.string(),color:y.string(),icon:y.string(),button:y.object({backgroundColor:y.string(),textColor:y.string(),borderColor:y.string(),hoverBackgroundColor:y.string(),focusOutlineColor:y.string(),fontWeight:y.optional(y.string(),"500")})}),Sc=y.object({...wi.entries,type:y.picklist(["auth","both"]),scopes:y.optional(y.array(y.string())),firebaseProviderId:y.optional(y.string())}),Ct=y.union([y.literal(""),y.pipe(y.string(),y.url())]),_c=y.object({authUrl:Ct,tokenUrl:Ct,profileUrl:Ct,revokeUrl:y.optional(Ct)}),Ac=y.object({authentication:y.optional(y.array(y.string())),"api-access":y.array(y.string())}),Hm=y.object({...wi.entries,type:y.picklist(["oauth","both"]),scopes:Ac,endpoints:_c}),Qe=null;function Cc(){let t=[];for(let[e,r]of Object.entries(he))y.safeParse(Sc,r).success?t.push(e):typeof window<"u"&&Ci();return t}function wt(){if(Qe!==null)return Qe;let t=x("AUTH_PARTNERS");if(!t)return Qe=[],Qe;let e=Cc(),r=t.split(",").map(n=>n.trim().toLowerCase()).filter(n=>e.includes(n));return Qe=r,r}var wc=12e4,Br=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,r={}){this.authInstance=e,this.refreshBuffer=r.refreshBufferMs??wc,this.maxRefreshAttempts=r.maxRefreshAttempts??3,this.autoRefresh=r.autoRefresh!==!1,this.onTokenExpired=r.onTokenExpired,this.onFatalError=r.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let r=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:r},this.autoRefresh&&e.expiresAt&&this.scheduleRefresh(e.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(e){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(e&&typeof e.getIdToken=="function"){let r=await e.getIdToken(!0),n=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:r,expiresAt:n}),r}else if(e&&typeof e.getIdTokenResult=="function"){let r=await e.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),r.token}if(this.authInstance?.currentUser){let r=await this.authInstance.currentUser.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),r.token}throw v(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(r){return this.handleError(r instanceof Error?r:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:r}=this.tokenInfo;if(e==="valid")return r;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(this.authInstance?.currentUser)return await this.forceRefresh(this.authInstance.currentUser)}catch(n){this.handleError(n instanceof Error?n:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:r}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let r={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},n=this.calculateTokenStatus(r.expiresAt);this.tokenInfo={...r,status:n},this.autoRefresh&&r.expiresAt&&this.scheduleRefresh(r.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let r=new Date;if(r>=e)return"expired";let n=new Date(e.getTime()-this.refreshBuffer);return r>=n?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let r=new Date,n=e.getTime()-r.getTime()-this.refreshBuffer;if(n<=0){this.authInstance?.currentUser&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{this.authInstance?.currentUser?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},n)}handleRefreshError(e){if(this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let r=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);setTimeout(()=>{this.authInstance?.currentUser?this.forceRefresh(this.authInstance.currentUser).catch(n=>{this.handleRefreshError(n)}):this.refreshCallback&&this.refreshCallback().catch(n=>{this.handleRefreshError(n)})},r)}else this.tokenInfo={...this.tokenInfo,status:"error",error:e instanceof Error?e:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(e instanceof Error?e:new Error("Max token refresh attempts reached"))}handleError(e){this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},og=Le(Br,null,{});var Pt=class{buildKey(e,r,n,i=!1){let o="dndev";switch(r){case"user":if(!n){if(i)return null;throw v(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:r}})}return`${o}:user:${n}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var de=null;async function Pc(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(t){throw v(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function Rc(t){try{let e=await window.crypto.subtle.exportKey("raw",t);return btoa(String.fromCharCode(...new Uint8Array(e)))}catch(e){throw v(e,{userMessage:"Failed to export encryption key"})}}async function kc(t){try{let e=Uint8Array.from(atob(t),r=>r.charCodeAt(0));return await window.crypto.subtle.importKey("raw",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(e){throw v(e,{userMessage:"Failed to import encryption key"})}}async function Pi(){if(de)return de;try{let t=localStorage.getItem("dndev:encryptionKey");if(t)return de=await kc(t),de;de=await Pc();let e=await Rc(de);return localStorage.setItem("dndev:encryptionKey",e),de}catch(t){throw v(t,{userMessage:"Failed to get or create encryption key"})}}async function Ri(t){try{let e=await Pi(),r=window.crypto.getRandomValues(new Uint8Array(12)),n=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(n),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,o),c=new Uint8Array(r.length+s.byteLength);return c.set(r,0),c.set(new Uint8Array(s),r.length),btoa(String.fromCharCode(...c))}catch(e){throw v(e,{userMessage:"Failed to encrypt data"})}}async function ki(t){try{let e=await Pi(),r=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),n=r.slice(0,12),i=r.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i),c=new TextDecoder().decode(o);try{return JSON.parse(c)}catch{return c}}catch(e){throw v(e,{userMessage:"Failed to decrypt data"})}}var re=class extends Pt{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,r={}){let{scope:n="user",encryption:i=!1}=r,o=this.buildKey(e,n,this.userId,!0);if(!o)return null;try{if(!M())return null;let s=localStorage.getItem(o);if(!s)return null;let c=JSON.parse(s);if(c.expiresAt&&new Date(c.expiresAt)<new Date)return await this.remove(e),null;let u=c.value;return i&&typeof u=="string"&&(u=await ki(u)),u}catch(s){throw v(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:r}})}}async set(e,r,n={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=n,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=r;o&&(u=await Ri(r));let d=s>0?new Date(Date.now()+s*1e3).toISOString():null,g=JSON.stringify({value:u,expiresAt:d,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,g)}catch(u){let d=u?.name==="QuotaExceededError"||u?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":u?.name==="SecurityError"||u?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw v(u,{userMessage:d,context:{key:e,options:n}})}}async remove(e){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(e,n,this.userId,!0);if(!i)continue;typeof window<"u"&&localStorage.removeItem(i)}catch{}}async clear(e){if(!e){let s=(typeof window<"u"?Object.keys(localStorage):[]).filter(c=>c.startsWith("dndev:"));for(let c of s)typeof window<"u"&&localStorage.removeItem(c);return}let r=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(r));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var Ze=class{localStrategy;userId;apiEndpoint;constructor(e,r="/api/storage"){if(!e)throw v("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=r}async get(e,r={}){try{let n=await this.localStrategy.get(e,r);return n!==null?n:await this.getFromCloud(e,r)}catch(n){try{return await this.localStrategy.get(e,r)}catch(i){throw v(n,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:r,fallbackError:i}})}}}async set(e,r,n={}){try{await this.localStrategy.set(e,r,n),this.setToCloud(e,r,n).catch(i=>{})}catch(i){throw v(i,{userMessage:"Failed to store data",context:{key:e,options:n}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(r=>{})}catch(r){throw v(r,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(r=>{})}catch(r){throw v(r,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,r,n,i=!1){let o="dndev";switch(r){case"user":if(!n){if(i)return null;throw v(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:r}})}return`${o}:user:${n}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,r){try{let{scope:n="user"}=r,i=this.buildKey(e,n,this.userId,!0);if(!i)return null;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`);if(!o.ok){if(o.status===404)return null;throw v(new Error(`Cloud storage API error: ${o.status} ${o.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:e,status:o.status}})}let s=await o.json();return s.expiresAt&&new Date(s.expiresAt)<new Date?(this.removeFromCloud(e).catch(console.warn),null):(this.localStrategy.set(e,s.value,r).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,r,n){let{scope:i="user",expiry:o=0}=n,s=this.buildKey(e,i,this.userId,!0);if(!s)return;let c=o>0?new Date(Date.now()+o*1e3).toISOString():null,u={value:r,expiresAt:c,createdAt:new Date().toISOString()},d=await fetch(`${this.apiEndpoint}/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw v(new Error(`Cloud storage API error: ${d.status} ${d.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:e,status:d.status}})}async removeFromCloud(e){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(e,n,this.userId,!0);if(!i)continue;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE"});!o.ok&&o.status}catch{}}async clearFromCloud(e){try{let r=new URLSearchParams;e&&r.append("scope",e),e==="user"&&r.append("userId",this.userId);let n=r.toString(),i=n?`${this.apiEndpoint}/clear?${n}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE"})).ok}catch{}}};var Rt=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,r){this.initialize(),r&&e?this.strategy=new Ze(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new Ze(this.userId):this.strategy=new re(this.userId)}async get(e,r={}){return this.initialize(),this.strategy.get(e,r)}async set(e,r,n={}){return this.initialize(),this.strategy.set(e,r,n)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,r,n={}){return this.initialize(),this.set(e,r,{...n,encryption:!0})}async getSecure(e,r={}){return this.initialize(),this.get(e,{...r,encryption:!0})}},xc=Le(Rt);var H={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function pe(t){return!!t&&t.trim()!==""}var Fg={[H.AUTH]:()=>wt().length>0,[H.OAUTH]:()=>["VITE_OAUTH_GOOGLE_CLIENT_ID","VITE_OAUTH_GITHUB_CLIENT_ID","VITE_OAUTH_FACEBOOK_CLIENT_ID","VITE_OAUTH_TWITTER_CLIENT_ID","VITE_OAUTH_LINKEDIN_CLIENT_ID","VITE_OAUTH_DISCORD_CLIENT_ID","VITE_OAUTH_SLACK_CLIENT_ID","VITE_OAUTH_MICROSOFT_CLIENT_ID","VITE_OAUTH_APPLE_CLIENT_ID"].some(e=>pe(x(e))),[H.I18N]:()=>!0,[H.BILLING]:()=>!!(pe(x("STRIPE_PUBLISHABLE_KEY"))||pe(x("BILLING_ENABLED"))&&x("BILLING_ENABLED")==="true"),[H.ROUTES]:()=>!0,[H.THEMES]:()=>!0,[H.COMPONENTS]:()=>!0,[H.CRUD]:()=>!0,[H.FORMS]:()=>!0,[H.REALTIME]:()=>!!(pe(x("REALTIME_ENABLED"))&&x("REALTIME_ENABLED")==="true"||pe(x("FIREBASE_CONFIG"))),[H.STORAGE]:()=>!!(pe(x("STORAGE_ENABLED"))&&x("STORAGE_ENABLED")==="true"||pe(x("FIREBASE_CONFIG")))};var Kc=Qr(Kr(),1);var Yc=Qr(Kr(),1);var Yr=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:r,once:!1,context:n};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,r)}}once(e,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:r,once:!0,context:n};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,r)}}off(e,r){let n=this.events.get(e);if(!n||n.length===0)return!1;let i=n.findIndex(o=>o.handler===r);return i===-1?!1:(n.splice(i,1),n.length===0&&this.events.delete(e),!0)}emit(e,...r){this.cacheEvent(e,r);let n=this.events.get(e);if(!n||n.length===0)return!1;let i=[...n],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,r):s.handler(...r),s.once&&o.push(s)}catch(c){v(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:r},severity:"warning"})}if(o.length>0){let s=this.events.get(e);if(s){let c=s.filter(u=>!o.includes(u));c.length===0?this.events.delete(e):this.events.set(e,c)}}return!0}hasListeners(e){let r=this.events.get(e);return!!r&&r.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let r=this.events.get(e);return r?r.map(n=>n.handler):[]}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}setMaxListeners(e){return this.maxListeners=e>0?e:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(e){let r=this.events.get(e);return r||(r=[],this.events.set(e,r)),r}checkListenerCount(e){let r=this.listenerCount(e);this.maxListeners!==1/0&&r>this.maxListeners}cacheEvent(e,r){let n=this.eventCache.get(e);n||(n=[],this.eventCache.set(e,n)),n.push({data:r,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let r=this.eventCache.get(e);return!r||r.length===0?[]:(this.cleanupCache(e),(this.eventCache.get(e)||[]).map(i=>i.data))}clearCachedEvents(e){this.eventCache.delete(e)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let e=0,r=null,n=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(r===null||c.timestamp<r)&&(r=c.timestamp),(n===null||c.timestamp>n)&&(n=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:r,newestEvent:n,memoryEstimate:i}}cleanupCache(e){let r=Date.now()-this.cacheTTL;if(e){let n=this.eventCache.get(e);if(n){let i=n.filter(o=>o.timestamp>r);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[n,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>r);o.length===0?this.eventCache.delete(n):this.eventCache.set(n,o)}}},Tv=new Yr;var Pv={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},error:null,emailVerification:{status:"pending"},getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:De.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:V.GUEST,userTier:Oe.FREE,can:{navigate:t=>t===!1||typeof t=="object"&&!t.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Rv={status:De.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1},kv={status:De.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},xv={status:De.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var Wi=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function qi(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function xt(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>{let i=`${e}[${n}]`;if(typeof r=="string"&&qi(r)){if(!Wi.test(r))throw v({userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&xt(r,i)});else if(typeof t=="object"&&t!==null)for(let[r,n]of Object.entries(t)){let i=e?`${e}.${r}`:r;if(typeof n=="string"&&qi(n)){if(!Wi.test(n))throw v({userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&xt(n,i)}}import*as ji from"valibot";var Jr={};function dy(t){Jr.uniqueConstraintValidator=t}async function Gi(t,e,r){let{uniqueFields:n=[],collection:i}=t.metadata;n.length!==0&&Jr.uniqueConstraintValidator&&await Promise.all(n.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await Jr.uniqueConstraintValidator.checkDuplicate(i,o,c,r))throw v({userMessage:s||`${o} must be unique`,code:"already-exists",context:{field:o}})}))}async function my(t,e,r,n){ji.parse(t,e),xt(e),await Gi(t,e,n),t.metadata.customValidate&&await t.metadata.customValidate(e,r)}function Jc(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function _y(t){if(!Jc(t)){let e=t,r=e&&typeof e=="object"&&"constructor"in e&&e.constructor&&e.constructor.name||"unknown";throw v(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return t.metadata.collection}function Xc(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let r=t.map(i=>({value:i.value,label:i.label})),n=new Set(t.map(i=>i.value));for(let i of e)n.has(i.value)||r.push(i);return r}function Qc(t){let{form:e,fields:r}=t,n=Object.keys(r);if(e){if(e.type==="multi-step"||e.type==="wizard"){if(!e.steps||e.steps.length===0)throw v(new Error(`Multi-step form for entity '${t.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${t.name}' must have at least one step`,context:{entityName:t.name,operation:"validateFormConfig"},severity:"error"});let i=e.steps.flatMap(u=>u.fields),o=i.filter(u=>!n.includes(u));if(o.length>0)throw v(new Error(`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:t.name,invalidFields:o,operation:"validateFormConfig"},severity:"error"});let s=new Set(i);n.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(g=>g.field):[i.condition.field]).filter(g=>!n.includes(g));if(c.length>0)throw v(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let d=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(g=>!n.includes(g));if(d.length>0)throw v(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${d.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${d.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:d,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([i,o])=>{if(o.dependsOn&&!n.includes(o.dependsOn.field))throw v(new Error(`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`,context:{entityName:t.name,fieldName:i,dependsOnField:o.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Zc(t){return t.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...t.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Ry(t){try{Qc(t);let e=Zc(t),r={...t.fields,...w,...t.fields.createdAt&&{createdAt:{...w.createdAt,...t.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...w.updatedAt,...t.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...w.createdById,...t.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...w.updatedById,...t.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...t.fields.status&&{status:{...w.status,...t.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:Xc(rr,t.fields.status.validation?.options)}}}};if(t.listFields){let o=new Set(Object.keys(r)),s=t.listFields.filter(c=>!o.has(c));if(s.length>0)throw v(new Error(`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let o=new Set(Object.keys(r)),s=t.listCardFields.filter(c=>!o.has(c));if(s.length>0)throw v(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}let n={...Vt,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:r,access:n,namespace:i}}catch(e){throw v(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}function xy(t,e,r=1,n=!1){let i=[];if(n)for(let o=e;o>=t;o-=r)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=r)i.push({value:String(o),label:String(o)});return i}export{ml as AUTH_EVENTS,he as AUTH_PARTNERS,Fu as AUTH_PARTNER_STATE,cn as AuthUserSchema,ge as BACKEND_GENERATED_FIELD_NAMES,vl as BILLING_EVENTS,Io as BREAKPOINT_RANGES,Ht as BREAKPOINT_THRESHOLDS,en as COMMON_TIER_CONFIGS,L as CONFIDENCE_LEVELS,fn as CONSENT_CATEGORY,D as CONTEXTS,an as CheckoutSessionMetadataSchema,tn as CreateCheckoutSessionRequestSchema,rn as CreateCheckoutSessionResponseSchema,un as CustomClaimsSchema,Vt as DEFAULT_ENTITY_ACCESS,oe as DEFAULT_ERROR_MESSAGES,Vl as DEFAULT_LAYOUT_PRESET,rr as DEFAULT_STATUS_OPTIONS,sf as DEFAULT_STATUS_VALUE,fu as DEFAULT_SUBSCRIPTION,yd as DENSITY,k as DoNotDevError,ie as ENVIRONMENTS,ln as EntityHookError,Ut as FEATURES,Ed as FEATURE_CONSENT_MATRIX,De as FEATURE_STATUS,Bt as FIREBASE_ERROR_MAP,rt as FIRESTORE_ID_PATTERN,dn as GITHUB_PERMISSION_LEVELS,af as HIDDEN_STATUSES,Bl as LAYOUT_PRESET,El as OAUTH_EVENTS,Wt as OAUTH_PARTNERS,cd as PARTNER_ICONS,Il as PAYLOAD_EVENTS,Mt as PERMISSIONS,C as PLATFORMS,Ku as PWA_ASSET_TYPES,zu as PWA_DISPLAY_MODES,yo as ProductDeclarationSchema,Tu as ProductDeclarationsSchema,Yu as ROUTE_SOURCES,ju as STORAGE_SCOPES,Gu as STORAGE_TYPES,Sl as STRIPE_EVENTS,tt as STRIPE_MODES,du as SUBSCRIPTION_DURATIONS,fe as SUBSCRIPTION_STATUS,Oe as SUBSCRIPTION_TIERS,In as ServerUtils,Yt as SingletonManager,bo as StripeBackConfigSchema,Eo as StripeFrontConfigSchema,go as StripePaymentSchema,vo as StripeSubscriptionSchema,on as SubscriptionClaimsSchema,nn as SubscriptionDataSchema,bs as TECHNICAL_FIELD_NAMES,V as USER_ROLES,Ft as UserSubscriptionSchema,sn as WebhookEventSchema,Ue as addMonths,Xt as addYears,w as baseFields,es as calculateSubscriptionEndDate,zt as captureErrorToSentry,Ql as checkGitHubAccessSchema,rf as clearSchemaGenerators,Ne as commonErrorCodeMappings,Dt as compactToISOString,Ko as createAsyncSingleton,pu as createDefaultSubscriptionClaims,Vu as createDefaultUserProfile,rl as createEntitySchema,$ as createErrorHandler,io as createMetadata,Yo as createMethodProxy,Is as createSchemas,Le as createSingleton,zo as createSingletonWithParams,Ry as defineEntity,ol as deleteEntitySchema,qt as detectErrorSource,td as disconnectOAuthSchema,yf as enhanceSchema,Zl as exchangeTokenSchema,Zo as filterVisibleFields,Zr as formatDate,po as formatRelativeTime,vn as generateCodeChallenge,gn as generateCodeVerifier,Bo as generatePKCEPair,To as getBreakpointFromWidth,Ml as getBreakpointUtils,_y as getCollectionName,rd as getConnectionsSchema,ao as getCurrentTimestamp,nl as getEntitySchema,tf as getRegisteredSchemaTypes,Fe as getSchemaType,Jt as getVisibleFields,lo as getWeekFromISOString,So as githubPermissionSchema,$t as githubRepoConfigSchema,Jl as grantGitHubAccessSchema,v as handleError,ef as hasCustomSchemaGenerator,Jc as hasMetadata,it as hasRoleAccess,jo as hasTierAccess,xo as isAuthPartnerId,uf as isBackendGeneratedField,Ul as isBreakpoint,Nt as isCompactDateString,bn as isFieldVisible,cf as isFrameworkField,Oo as isOAuthPartnerId,Ho as isPKCESupported,oo as isoToCompactString,Go as lazyImport,sl as listEntitiesSchema,jt as mapToDoNotDevError,Vo as maybeTranslate,so as normalizeToISOString,su as overrideFeatures,lu as overridePaymentModes,au as overridePermissions,uu as overrideSubscriptionStatus,ou as overrideSubscriptionTiers,iu as overrideUserRoles,Lt as parseDate,ho as parseDateToNoonUTC,ts as parseISODate,os as parseServerCookie,xy as rangeOptions,ed as refreshTokenSchema,b as registerSchemaGenerator,dy as registerUniqueConstraintValidator,Xl as revokeGitHubAccessSchema,Fo as showNotification,uo as timestampToISOString,mo as toDateOnly,co as toISOString,eo as translateArray,ro as translateArrayRange,no as translateArrayWithIndices,to as translateObjectArray,il as updateEntitySchema,Jo as updateMetadata,ld as validateAuthPartners,Uu as validateAuthSchemas,Du as validateAuthUser,Au as validateBillingSchemas,Iu as validateCheckoutSessionMetadata,Wo as validateCodeChallenge,$o as validateCodeVerifier,gu as validateCreateCheckoutSessionRequest,vu as validateCreateCheckoutSessionResponse,Lu as validateCustomClaims,xt as validateDates,my as validateDocument,is as validateEnvVar,ns as validateMetadata,dd as validateOAuthPartners,_u as validateStripeBackConfig,Su as validateStripeFrontConfig,Eu as validateSubscriptionClaims,yu as validateSubscriptionData,Gi as validateUniqueFields,rs as validateUrl,Nu as validateUserSubscription,bu as validateWebhookEvent,Mo as withErrorHandling,qo as withGracefulDegradation};
|
|
1
|
+
var Ji=Object.create;var Nt=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var Qi=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty;var Zr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),to=(t,e)=>{for(var r in e)Nt(t,r,{get:e[r],enumerable:!0})},ro=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zi(e))!eo.call(t,i)&&i!==r&&Nt(t,i,{get:()=>e[i],enumerable:!(n=Xi(e,i))||n.enumerable});return t};var Qr=(t,e,r)=>(r=t!=null?Ji(Qi(t)):{},ro(e||!t||!t.__esModule?Nt(r,"default",{value:t,enumerable:!0}):r,t));var qi=Zr(b=>{"use strict";var qr=Symbol.for("react.transitional.element"),Vc=Symbol.for("react.portal"),Bc=Symbol.for("react.fragment"),Hc=Symbol.for("react.strict_mode"),$c=Symbol.for("react.profiler"),Wc=Symbol.for("react.consumer"),qc=Symbol.for("react.context"),Gc=Symbol.for("react.forward_ref"),jc=Symbol.for("react.suspense"),Kc=Symbol.for("react.memo"),Fi=Symbol.for("react.lazy"),zc=Symbol.for("react.activity"),Ni=Symbol.iterator;function Yc(t){return t===null||typeof t!="object"?null:(t=Ni&&t[Ni]||t["@@iterator"],typeof t=="function"?t:null)}var Vi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Bi=Object.assign,Hi={};function ke(t,e,r){this.props=t,this.context=e,this.refs=Hi,this.updater=r||Vi}ke.prototype.isReactComponent={};ke.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};ke.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function $i(){}$i.prototype=ke.prototype;function Gr(t,e,r){this.props=t,this.context=e,this.refs=Hi,this.updater=r||Vi}var jr=Gr.prototype=new $i;jr.constructor=Gr;Bi(jr,ke.prototype);jr.isPureReactComponent=!0;var Ui=Array.isArray;function Wr(){}var C={H:null,A:null,T:null,S:null},Wi=Object.prototype.hasOwnProperty;function Kr(t,e,r){var n=r.ref;return{$$typeof:qr,type:t,key:e,ref:n!==void 0?n:null,props:r}}function Jc(t,e){return Kr(t.type,e,t.props)}function zr(t){return typeof t=="object"&&t!==null&&t.$$typeof===qr}function Xc(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var Li=/\/+/g;function $r(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Xc(""+t.key):e.toString(36)}function Zc(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Wr,Wr):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function xe(t,e,r,n,i){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(o){case"bigint":case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case qr:case Vc:s=!0;break;case Fi:return s=t._init,xe(s(t._payload),e,r,n,i)}}if(s)return i=i(t),s=n===""?"."+$r(t,0):n,Ui(i)?(r="",s!=null&&(r=s.replace(Li,"$&/")+"/"),xe(i,e,r,"",function(p){return p})):i!=null&&(zr(i)&&(i=Jc(i,r+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(Li,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=n===""?".":n+":";if(Ui(t))for(var u=0;u<t.length;u++)n=t[u],o=c+$r(n,u),s+=xe(n,e,r,o,i);else if(u=Yc(t),typeof u=="function")for(t=u.call(t),u=0;!(n=t.next()).done;)n=n.value,o=c+$r(n,u++),s+=xe(n,e,r,o,i);else if(o==="object"){if(typeof t.then=="function")return xe(Zc(t),e,r,n,i);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return s}function Ot(t,e,r){if(t==null)return t;var n=[],i=0;return xe(t,n,"","",function(o){return e.call(r,o,i++)}),n}function Qc(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Mi=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}},eu={map:Ot,forEach:function(t,e,r){Ot(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return Ot(t,function(){e++}),e},toArray:function(t){return Ot(t,function(e){return e})||[]},only:function(t){if(!zr(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};b.Activity=zc;b.Children=eu;b.Component=ke;b.Fragment=Bc;b.Profiler=$c;b.PureComponent=Gr;b.StrictMode=Hc;b.Suspense=jc;b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C;b.__COMPILER_RUNTIME={__proto__:null,c:function(t){return C.H.useMemoCache(t)}};b.cache=function(t){return function(){return t.apply(null,arguments)}};b.cacheSignal=function(){return null};b.cloneElement=function(t,e,r){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var n=Bi({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!Wi.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(n[o]=e[o]);var o=arguments.length-2;if(o===1)n.children=r;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];n.children=s}return Kr(t.type,i,n)};b.createContext=function(t){return t={$$typeof:qc,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:Wc,_context:t},t};b.createElement=function(t,e,r){var n,i={},o=null;if(e!=null)for(n in e.key!==void 0&&(o=""+e.key),e)Wi.call(e,n)&&n!=="key"&&n!=="__self"&&n!=="__source"&&(i[n]=e[n]);var s=arguments.length-2;if(s===1)i.children=r;else if(1<s){for(var c=Array(s),u=0;u<s;u++)c[u]=arguments[u+2];i.children=c}if(t&&t.defaultProps)for(n in s=t.defaultProps,s)i[n]===void 0&&(i[n]=s[n]);return Kr(t,o,i)};b.createRef=function(){return{current:null}};b.forwardRef=function(t){return{$$typeof:Gc,render:t}};b.isValidElement=zr;b.lazy=function(t){return{$$typeof:Fi,_payload:{_status:-1,_result:t},_init:Qc}};b.memo=function(t,e){return{$$typeof:Kc,type:t,compare:e===void 0?null:e}};b.startTransition=function(t){var e=C.T,r={};C.T=r;try{var n=t(),i=C.S;i!==null&&i(r,n),typeof n=="object"&&n!==null&&typeof n.then=="function"&&n.then(Wr,Mi)}catch(o){Mi(o)}finally{e!==null&&r.types!==null&&(e.types=r.types),C.T=e}};b.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()};b.use=function(t){return C.H.use(t)};b.useActionState=function(t,e,r){return C.H.useActionState(t,e,r)};b.useCallback=function(t,e){return C.H.useCallback(t,e)};b.useContext=function(t){return C.H.useContext(t)};b.useDebugValue=function(){};b.useDeferredValue=function(t,e){return C.H.useDeferredValue(t,e)};b.useEffect=function(t,e){return C.H.useEffect(t,e)};b.useEffectEvent=function(t){return C.H.useEffectEvent(t)};b.useId=function(){return C.H.useId()};b.useImperativeHandle=function(t,e,r){return C.H.useImperativeHandle(t,e,r)};b.useInsertionEffect=function(t,e){return C.H.useInsertionEffect(t,e)};b.useLayoutEffect=function(t,e){return C.H.useLayoutEffect(t,e)};b.useMemo=function(t,e){return C.H.useMemo(t,e)};b.useOptimistic=function(t,e){return C.H.useOptimistic(t,e)};b.useReducer=function(t,e,r){return C.H.useReducer(t,e,r)};b.useRef=function(t){return C.H.useRef(t)};b.useState=function(t){return C.H.useState(t)};b.useSyncExternalStore=function(t,e,r){return C.H.useSyncExternalStore(t,e,r)};b.useTransition=function(){return C.H.useTransition()};b.version="19.2.4"});var Yr=Zr((ev,Gi)=>{"use strict";Gi.exports=qi()});var Sn={};to(Sn,{CURRENCY_MAP:()=>Ut,DEFAULT_ERROR_MESSAGES:()=>oe,DoNotDevError:()=>x,SingletonManager:()=>Zt,addMonths:()=>Me,addYears:()=>er,calculateSubscriptionEndDate:()=>os,captureErrorToSentry:()=>Jt,commonErrorCodeMappings:()=>Ue,compactToISOString:()=>Lt,createAsyncSingleton:()=>Qo,createErrorHandler:()=>$,createMetadata:()=>ao,createMethodProxy:()=>es,createSingleton:()=>Le,createSingletonWithParams:()=>Zo,detectErrorSource:()=>Kt,filterVisibleFields:()=>is,formatCurrency:()=>uo,formatDate:()=>tn,formatRelativeTime:()=>vo,generateCodeChallenge:()=>En,generateCodeVerifier:()=>yn,generatePKCEPair:()=>Go,getCurrencyLocale:()=>en,getCurrencySymbol:()=>co,getCurrentTimestamp:()=>fo,getVisibleFields:()=>Qt,getWeekFromISOString:()=>go,handleError:()=>v,hasRoleAccess:()=>st,hasTierAccess:()=>Xo,isCompactDateString:()=>Mt,isFieldVisible:()=>Tn,isPKCESupported:()=>jo,isoToCompactString:()=>lo,lazyImport:()=>Jo,mapToDoNotDevError:()=>Yt,maybeTranslate:()=>qo,normalizeToISOString:()=>po,parseDate:()=>Ft,parseDateToNoonUTC:()=>Eo,parseISODate:()=>ss,parseServerCookie:()=>ls,showNotification:()=>Wo,timestampToISOString:()=>mo,toDateOnly:()=>bo,toISOString:()=>ho,translateArray:()=>no,translateArrayRange:()=>oo,translateArrayWithIndices:()=>so,translateObjectArray:()=>io,updateMetadata:()=>ts,validateCodeChallenge:()=>zo,validateCodeVerifier:()=>Ko,validateEnvVar:()=>us,validateMetadata:()=>cs,validateUrl:()=>as,withErrorHandling:()=>$o,withGracefulDegradation:()=>Yo});function no(t,e,r,n={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=n;return Array.from({length:r},(c,u)=>{let p=`${e}.${u}`;return t(p)}).filter((c,u)=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function io(t,e,r,n){return Array.from({length:r},(i,o)=>{let s=`${e}.${o}.${String(n[0])}`;if(t(s)===s)return null;let u={};for(let p of n){let g=`${e}.${o}.${String(p)}`;u[p]=t(g)}return u}).filter(i=>i!==null)}function oo(t,e,r,n,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:n-r},(u,p)=>{let g=r+p,T=`${e}.${g}`;return t(T)}).filter((u,p)=>{let g=r+p,T=`${e}.${g}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,g))})}function so(t,e,r,n={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=n;return Array.from({length:r},(c,u)=>{let p=`${e}.${u}`;return{item:t(p),originalIndex:u}}).filter(({item:c,originalIndex:u})=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function ao(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}var Ut={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function en(t){return Ut[t]?.locale??"en-US"}function co(t){return!t||typeof t!="string"?t??"":Ut[t]?.symbol??t}function uo(t,e,r={}){if(t==null||isNaN(t))return"";let n=en(e);return new Intl.NumberFormat(n,{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:0,currencyDisplay:"symbol",...r}).format(t)}function Lt(t){let e=t.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!e||e.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${t}`);let r=e[1],n=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(r,10),parseInt(n,10)-1,parseInt(i,10),parseInt(o,10),parseInt(s,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${t}`);return c.toISOString()}function lo(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0");return`${r}${n}${i}:${o}${s}`}function Mt(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function po(t){if(!t)return new Date().toISOString();if(t instanceof Date){if(isNaN(t.getTime()))throw new Error("Invalid Date object");return t.toISOString()}if(typeof t=="string"){if(Mt(t))return Lt(t);let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid date string: ${t}`);return e.toISOString()}if(typeof t=="number"){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid timestamp: ${t}`);return e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")return e.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof t}`)}function fo(){return new Date().toISOString()}function ho(t){return t.toISOString()}function mo(t){return new Date(t).toISOString()}function go(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let r=new Date(e.getFullYear(),0,1),n=Math.floor((e.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((n+r.getDay()+1)/7)}, ${e.getFullYear()}`}var N={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function vo(t,e="en",r={}){if(!t)return"";let{style:n="long",numeric:i="auto",fallbackThreshold:o=N.WEEK}=r,s;if(t instanceof Date)s=t;else if(typeof t=="string")s=new Date(t);else if(typeof t=="number")s=new Date(t);else if(typeof t=="object"&&"toDate"in t)s=t.toDate();else return"";if(isNaN(s.getTime()))return"";let c=new Date,u=s.getTime()-c.getTime(),p=Math.round(u/1e3),g=Math.abs(p);if(g>o)return tn(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:n,numeric:i});return g<N.MINUTE?T.format(p,"second"):g<N.HOUR?T.format(Math.round(p/N.MINUTE),"minute"):g<N.DAY?T.format(Math.round(p/N.HOUR),"hour"):g<N.WEEK?T.format(Math.round(p/N.DAY),"day"):g<N.MONTH?T.format(Math.round(p/N.WEEK),"week"):g<N.YEAR?T.format(Math.round(p/N.MONTH),"month"):T.format(Math.round(p/N.YEAR),"year")}function yo(t){switch(t){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function tn(t,e="en",r="long"){if(!t)return"";let n;if(t instanceof Date)n=t;else if(typeof t=="string")n=new Date(t);else if(typeof t=="number")n=new Date(t);else if(typeof t=="object"&&"toDate"in t)n=t.toDate();else return"";if(isNaN(n.getTime()))return"";let i=typeof r=="string"?yo(r):r;return new Intl.DateTimeFormat(e,i).format(n)}function Ft(t){if(t!=null){if(t instanceof Date)return isNaN(t.getTime())?void 0:t.toISOString();if(typeof t=="string"){let e=t.trim();if(!e)return;if(Mt(e))try{return Lt(e)}catch{return}let r=new Date(e);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof t=="number"){if(!Number.isFinite(t))return;let e=new Date(t);return isNaN(e.getTime())?void 0:e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")try{let r=e.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,r=e.seconds*1e3+(e.nanoseconds||0)/1e6,n=new Date(r);return isNaN(n.getTime())?void 0:n.toISOString()}}}function Eo(t){let e=Ft(t);if(!e)return;let r=new Date(e);return r.setUTCHours(12,0,0,0),r.toISOString()}function bo(t){let e=Ft(t);return e&&e.split("T")[0]||""}var V={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function hu(t){Object.assign(V,t)}var De={FREE:"free",PRO:"pro",PREMIUM:"premium"};function mu(t){Object.assign(De,t)}var Vt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function gu(t){Object.assign(Vt,t)}var Bt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function vu(t){Object.assign(Bt,t)}import*as l from"valibot";var he={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Eu(t){Object.assign(he,t)}var nt={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function bu(t){Object.assign(nt,t)}var Iu={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Tu(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var rn={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Su={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var nn=a.object({userId:a.string(),productId:a.optional(a.string()),priceId:a.string(),successUrl:a.pipe(a.string(),a.url()),cancelUrl:a.pipe(a.string(),a.url()),customerEmail:a.optional(a.pipe(a.string(),a.email())),userEmail:a.optional(a.pipe(a.string(),a.email())),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean()),mode:a.optional(a.picklist([nt.PAYMENT,nt.SUBSCRIPTION]))}),on=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),sn=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(he)),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),an=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(he)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),cn=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),un=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function Au(t){return a.safeParse(nn,t)}function wu(t){return a.safeParse(on,t)}function Pu(t){return a.safeParse(sn,t)}function Ru(t){return a.safeParse(an,t)}function xu(t){return a.safeParse(cn,t)}function ku(t){return a.safeParse(un,t)}var Io=a.object({type:a.literal("StripePayment"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.pipe(a.string(),a.minLength(1,"Duration is required")),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),To=a.object({type:a.literal("StripeSubscription"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),So=a.variant("type",[Io,To]),Ou=a.record(a.string(),So),_o=a.record(a.string(),a.object({name:a.string(),price:a.string(),currency:a.string(),description:a.optional(a.string()),features:a.optional(a.array(a.string())),priceId:a.string(),allowPromotionCodes:a.optional(a.boolean())})),Co=a.record(a.string(),a.object({type:a.picklist(["StripePayment","StripeSubscription"]),name:a.string(),price:a.number(),currency:a.string(),priceId:a.string(),tier:a.string(),duration:a.string(),description:a.optional(a.string()),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean())}));function Du(t){return a.parse(_o,t)}function Nu(t){return a.parse(Co,t)}function Uu(){let t={createCheckoutSessionRequest:a.safeParse(nn,{}),createCheckoutSessionResponse:a.safeParse(on,{}),subscriptionData:a.safeParse(sn,{}),subscriptionClaims:a.safeParse(an,{}),webhookEvent:a.safeParse(cn,{}),checkoutSessionMetadata:a.safeParse(un,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var ln=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(V))),customClaims:l.optional(l.record(l.string(),l.any()))}),Ht=l.object({userId:l.string(),tier:l.picklist(Object.values(De)),status:l.picklist(Object.values(he)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),dn=l.object({role:l.optional(l.picklist(Object.values(V))),subscription:l.optional(Ht),features:l.optional(l.array(l.picklist(Object.values(Vt)))),permissions:l.optional(l.array(l.picklist(Object.values(Bt)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function Wu(t){return l.safeParse(ln,t)}function qu(t){return l.safeParse(Ht,t)}function Gu(t){return l.safeParse(dn,t)}function ju(){let t={authUser:l.safeParse(ln,{}),userSubscription:l.safeParse(Ht,{}),customClaims:l.safeParse(dn,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(t).every(e=>e.success),results:t}}var zu={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Yu(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var A={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},ie={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},D={CLIENT:"client",SERVER:"server",BUILD:"build"},U={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ne={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},tl={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},rl={USER:"user",GLOBAL:"global",SESSION:"session"},nl={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},il={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},ol={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};import*as h from"valibot";var $t={create:"admin",read:"guest",update:"admin",delete:"admin"};var it=/^[0-9a-zA-Z]+$/,pl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),data:h.record(h.string(),h.unknown()),idempotencyKey:h.optional(h.string())}),fl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),hl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required")),data:h.record(h.string(),h.unknown()),merge:h.optional(h.boolean(),!1)}),ml=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),gl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),limit:h.optional(h.pipe(h.number(),h.minValue(1),h.maxValue(1e3)),50),offset:h.optional(h.pipe(h.number(),h.minValue(0)),0),orderBy:h.optional(h.string()),orderDirection:h.optional(h.picklist(["asc","desc"]),"desc"),where:h.optional(h.array(h.object({field:h.string(),operator:h.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:h.any()})))});var Wt={"permission-denied":{type:"PERMISSION_DENIED",message:"You do not have permission to perform this action"},"not-found":{type:"NOT_FOUND",message:"The requested resource was not found"},"already-exists":{type:"ALREADY_EXISTS",message:"The resource already exists"},"invalid-argument":{type:"VALIDATION_ERROR",message:"Invalid argument provided"}},pn=class extends Error{type;originalError;constructor(e,r,n){super(r),this.name="EntityHookError",this.type=e,this.originalError=n}},x=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,r="internal",n){super(e),Object.setPrototypeOf(this,t.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var Al={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var Pl={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var xl={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Ol={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Nl={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var qt={mobile:0,tablet:768,laptop:1024,desktop:1440},Ao={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function wo(t){return t>=qt.desktop?"desktop":t>=qt.laptop?"laptop":t>=qt.tablet?"tablet":"mobile"}function Kl(t,e){let r=Ao[e];return t>=r.min&&t<=r.max}function zl(t,e){let r=wo(t);return{current:r,width:t,height:e,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}var Jl="landing",Xl={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var fn=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var Gt=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),Po=f.picklist([...fn]),ad=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Gt,permission:f.optional(Po,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),cd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Gt}),ud=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Gt}),ld=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),dd=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),pd=f.object({provider:f.string()}),fd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var Ed={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as m from"valibot";var hn=m.object({name:m.string(),color:m.string(),icon:m.string(),customParameters:m.optional(m.record(m.string(),m.string())),button:m.object({backgroundColor:m.string(),textColor:m.string(),borderColor:m.string(),hoverBackgroundColor:m.string(),focusOutlineColor:m.string(),fontWeight:m.optional(m.string(),"500"),textKey:m.optional(m.string())})}),Ro=m.object({...hn.entries,type:m.picklist(["auth","both"]),scopes:m.optional(m.array(m.string())),firebaseProviderId:m.optional(m.string())}),ot=m.union([m.literal(""),m.pipe(m.string(),m.url())]),xo=m.object({authUrl:ot,tokenUrl:ot,profileUrl:ot,revokeUrl:m.optional(ot)}),ko=m.object({authentication:m.optional(m.array(m.string())),"api-access":m.array(m.string())}),Oo=m.optional(m.object({pkce:m.optional(m.boolean(),!1),codeChallengeMethod:m.optional(m.picklist(["S256","plain"]),"S256")})),Do=m.object({...hn.entries,type:m.picklist(["oauth","both"]),scopes:ko,endpoints:xo,capabilities:Oo}),me={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},jt={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},No=m.record(m.string(),Ro),Uo=m.record(m.string(),Do);function Id(){return m.safeParse(No,me)}function Td(){return m.safeParse(Uo,jt)}function Lo(t){return t in me}function Mo(t){return t in jt}var mn={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Rd={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},xd={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:mn.ANALYTICS},marketing:{requiresConsent:mn.MARKETING}};function Kt(t){return t instanceof Error&&"source"in t&&typeof t.source=="string"?t.source:typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("auth/")?"auth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("oauth/")?"oauth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(t.code)?"firebase":typeof t=="object"&&t!==null&&"issues"in t&&Array.isArray(t.issues)&&"name"in t&&t.name==="ValiError"?"validation":t instanceof Error&&t.name==="EntityHookError"?"entity":typeof t=="object"&&t!==null&&("response"in t||"status"in t||"statusText"in t)?"api":typeof t=="object"&&t!==null&&"componentStack"in t?"ui":"unknown"}import*as vn from"valibot";function $(t){return(e,r)=>{if(e instanceof x)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new x(r||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let n;t.extractErrorCode?n=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(n=e.code);let i=t.defaultErrorCode;n&&t.errorCodeMapping&&n in t.errorCodeMapping&&(i=t.errorCodeMapping[n]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),n&&t.friendlyMessageMapping&&n in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[n]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},n&&(s.originalCode=n)),"originalError"in s||(s.originalError=e),new x(r||o,i,{details:s,source:t.errorSource})}}var Ue={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var oe={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Fo={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},zt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Q={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",...Ue},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...Ue},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(Fo).map(([t,e])=>[t,e])),friendlyMessageMapping:{},extractErrorCode:t=>{if(typeof t!="object"||t===null)return;let e;return"response"in t&&t.response&&"status"in t.response?e=t.response.status:"status"in t&&typeof t.status=="number"&&(e=t.status),e?.toString()},processMetadata:t=>{let e={originalError:t};return typeof t!="object"||t===null||("response"in t&&t.response?("status"in t.response&&(e.statusCode=t.response.status),"data"in t.response&&(e.responseData=t.response.data)):"status"in t&&(e.statusCode=t.status)),e}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:Ue,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:oe.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:t=>{let e={originalError:t};return typeof t=="object"&&t!==null&&"componentStack"in t&&(e.componentStack=t.componentStack),e}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:oe["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:oe.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},Vo=t=>t instanceof vn.ValiError?new x(oe["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(Q.validation)(t),Bo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in zt){let e=t,r=zt[e.type]||"unknown";return new x(e.message||oe[r],r,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Wt[t.code]){let e=t,r=Wt[e.code];if(r){let n=zt[r.type]||"unknown";return new x(r.message||oe[n],n,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(Q.entity)(t)},gn={auth:$(Q.auth),oauth:$(Q.oauth),api:$(Q.api),firebase:$(Q.firebase),ui:$(Q.ui),validation:Vo,entity:Bo,unknown:$(Q.unknown)};function Yt(t,e,r){return t instanceof x?t:(gn[e]||gn.unknown)(t,r)}function Jt(t,e,r={}){let n=globalThis.Sentry;n&&n.withScope(i=>{i.setTag("errorSource",e),i.setTag("errorCode",t.code),t.details&&Object.entries(t.details).forEach(([o,s])=>{if(typeof s!="function"&&o!=="originalError")try{i.setExtra(o,s)}catch{i.setExtra(o,`[${typeof s}]`)}}),Object.entries(r).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||r.userId)&&i.setUser({id:t.details?.userId||r.userId,email:t.details?.userEmail||r.userEmail}),n.captureException(t)})}function Ho(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!0}function v(t,e){let r=typeof e=="string"?{userMessage:e}:e||{},{userMessage:n,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=r,p=Kt(t),g=t instanceof x?t:Yt(t,p,n);if(n&&!g.userMessageProvided&&(g.message.includes("Error")||g.message.includes("Failed")||g.message.length<10?g=new x(n,g.code,{details:{...g.details,originalMessage:g.message},source:p,userMessageProvided:!0}):g=new x(g.message,g.code,{details:{...g.details,userMessage:n},source:p,userMessageProvided:!0})),o){let T=Ho()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:g.code,message:g.message,source:p};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&Jt(g,p,i),g}function $o(t,e){return async(...r)=>{try{return await t(...r)}catch(n){throw v(n,e)}}}function Wo(t,e="info",r){let n=Date.now().toString();return n}function qo(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function yn(){let t=new Uint8Array(32);return crypto.getRandomValues(t),bn(t)}async function En(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return bn(new Uint8Array(n))}async function Go(){let t=yn(),e=await En(t);return{codeVerifier:t,codeChallenge:e}}function bn(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function jo(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Ko(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function zo(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function Yo(t,e,r){try{return await t()}catch{return e(),!1}}var Xt=new Map;function Jo(t,e){if(Xt.has(e))return Xt.get(e);let r=t();return Xt.set(e,r),r}var In={[V.GUEST]:0,[V.USER]:1,[V.ADMIN]:2,[V.SUPER]:3};function st(t,e){if(!t)return!1;let r=In[t]??-1,n=In[e]??1/0;return r>=n}function Xo(t,e,r){if(!t)return!1;let n=r??rn,i=n[t]?.level??-1,o=n[e]?.level??1/0;return i>=o}function Le(t,...e){let r=null,n=!1;return function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?r=new t(...e):r=t(),r}finally{n=!1}}}function Zo(t){let e=null,r=!1;return function(...i){if(e!==null)return e;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{r=!1}}}function Qo(t){let e=null,r=!1,n=null;return async function(){if(e!==null)return e;if(r&&n)return n;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return n=t(),e=await n,e}finally{r=!1,n=null}}}function es(t,e){return new Proxy({},{get(r,n){if(e.includes(n)){let o=t(),s=o[n];return typeof s=="function"?s.bind(o):s}return t()[n]}})}var Zt=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,r,n={}){if(this.instances.has(e))return this.instances.get(e);if(this.initialized.has(e))return this.instances.get(e);if(this.initializing.has(e))throw new Error(`Circular dependency detected for singleton: ${e}`);if(n.ssrSafe===!1&&typeof window>"u"){if(n.fallbackFactory){let i=n.fallbackFactory();return this.instances.set(e,i),this.initialized.add(e),i}throw new Error(`Singleton ${e} requires client-side environment`)}this.initializing.add(e);try{let i=await r();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(n.cacheFailures&&this.initialized.add(e),n.fallbackFactory){let o=n.fallbackFactory();return this.instances.set(e,o),this.initialized.add(e),o}throw i}finally{this.initializing.delete(e)}}static isInitialized(e){return this.initialized.has(e)}static clear(e){this.instances.delete(e),this.initialized.delete(e),this.initializing.delete(e)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function ts(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}import"valibot";import"valibot";function rs(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function ns(t){if(rs(t))return t.visibility}function Tn(t,e){let r=t??"guest";return r==="hidden"?!1:r==="technical"?st(e,"admin"):st(e,r)}function Qt(t,e){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let n=r.entries,i=[];for(let[o,s]of Object.entries(n)){let c=ns(s);Tn(c,e)&&i.push(o)}return i}function is(t,e,r){if(!t)return{};let n=Qt(e,r),i={};for(let o of n)Object.prototype.hasOwnProperty.call(t,o)&&(i[o]=t[o]);return i}function Me(t,e){let r=new Date(t),n=r.getDate();return r.setMonth(r.getMonth()+e),r.getDate()!==n&&r.setDate(0),r}function er(t,e){let r=new Date(t),n=r.getDate();return r.setFullYear(r.getFullYear()+e),r.getDate()!==n&&r.setDate(0),r}function os(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return t==="1month"?r=Me(e,1):t==="3months"?r=Me(e,3):t==="6months"?r=Me(e,6):t==="1year"?r=er(e,1):t==="2years"?r=er(e,2):r=Me(e,1),r.toISOString()}function ss(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function as(t,e="URL"){try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return t}catch(r){throw new Error(`Invalid ${e}: ${t}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function cs(t){let e={};for(let[r,n]of Object.entries(t)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let i=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(i.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);e[r]=i}return e}function us(t,e=!0){let r=process.env[t];if(e&&!r)throw new Error(`Required environment variable '${t}' is not set`);return r||""}function ls(t,e){if(!t)return null;let r=`${encodeURIComponent(e)}=`,n=t.split(";");for(let i=0;i<n.length;i++){let o=n[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(r)===0)return decodeURIComponent(o.substring(r.length,o.length))}}return null}import*as W from"valibot";import*as d from"valibot";var Ve=new Map;function E(t,e){Ve.set(t,e)}function ff(t){return Ve.has(t)}function hf(){return Array.from(Ve.keys())}function mf(){Ve.clear()}function _(t,e){return e?t:d.nullish(t)}var at=t=>{let e=[];t.validation?.minLength!==void 0&&e.push(d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)),t.validation?.maxLength!==void 0&&e.push(d.maxLength(t.validation.maxLength,`Must be at most ${t.validation.maxLength} characters`)),t.validation?.pattern&&e.push(d.regex(new RegExp(t.validation.pattern),"Invalid format"));let r=e.length>0?d.pipe(d.string(),...e):d.string();return _(r,t.validation?.required)},ds=t=>{let e=d.pipe(d.string(),d.email("Invalid email address"));return _(e,t.validation?.required)},ps=t=>{let e=t.validation?.minLength!==void 0?d.pipe(d.string(),d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)):d.string();return _(e,t.validation?.required)},fs=t=>{let e=d.pipe(d.string(),d.url("Invalid URL"));return _(e,t.validation?.required)},Fe=t=>{let e=[];t.validation?.min!==void 0&&e.push(d.minValue(t.validation.min,`Must be at least ${t.validation.min}`)),t.validation?.max!==void 0&&e.push(d.maxValue(t.validation.max,`Must be at most ${t.validation.max}`));let r=e.length>0?d.pipe(d.number(),...e):d.number();return _(r,t.validation?.required)},_n=t=>{let e=d.boolean();return _(e,t.validation?.required)},ge=t=>{let e=d.pipe(d.string(),d.isoTimestamp("Invalid date format"));return _(e,t.validation?.required)},Pn=d.object({url:d.string(),filename:d.string(),size:d.number(),mimeType:d.nullish(d.string()),uploadedAt:d.nullish(d.string())}),Cn=t=>{let e=d.nullable(Pn);return _(e,t.validation?.required)},An=t=>{let e=d.array(Pn);return _(e,t.validation?.required)},Rn=d.object({fullUrl:d.string(),thumbUrl:d.string()}),hs=t=>_(Rn,t.validation?.required),ms=t=>{let e=d.array(Rn);return _(e,t.validation?.required)},gs=t=>{let e=d.object({lat:d.number(),lng:d.number()});return _(e,t.validation?.required)},vs=t=>{let e=d.object({formatted_address:d.string(),latitude:d.number(),longitude:d.number(),street_number:d.nullish(d.string()),route:d.nullish(d.string()),locality:d.nullish(d.string()),administrative_area_level_1:d.nullish(d.string()),administrative_area_level_2:d.nullish(d.string()),country:d.nullish(d.string()),postal_code:d.nullish(d.string())});return _(e,t.validation?.required)},ys=t=>{let e=d.record(d.string(),d.unknown());return _(e,t.validation?.required)},Es=t=>{let e=d.array(d.unknown());return _(e,t.validation?.required)},tr=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let n=e.map(o=>o.value),i=d.picklist(n);return _(i,t.validation?.required)}let r=d.union([d.string(),d.number()]);return _(r,t.validation?.required)},bs=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let n=e.map(o=>o.value),i=d.array(d.picklist(n));return _(i,t.validation?.required)}let r=d.array(d.string());return _(r,t.validation?.required)},Is=t=>{let e=d.pipe(d.string(),d.regex(it,"Invalid ID format"));return _(e,t.validation?.required)},rr=t=>{let e=d.string();return _(e,t.validation?.required)},Ts=t=>{let e=d.string();return _(e,t.validation?.required)},wn=()=>d.never(),Ss=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let n=[e.checkedValue,e.uncheckedValue],i=d.picklist(n);return _(i,t.validation?.required)}let r=d.boolean();return _(r,t.validation?.required)},_s=t=>d.custom(r=>t.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),Cs=t=>{let e=d.object({amount:d.number(),currency:d.optional(d.string()),vatIncluded:d.optional(d.boolean()),discountPercent:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(100)))});return _(e,t.validation?.required)};function As(){E("text",at),E("textarea",at),E("richtext",at),E("color",at),E("email",ds),E("password",ps),E("url",fs),E("tel",Ts),E("number",Fe),E("currency",Fe),E("price",Cs),E("range",Fe),E("year",Fe),E("rating",Fe),E("boolean",_n),E("checkbox",_n),E("gdprConsent",_s),E("date",ge),E("datetime-local",ge),E("time",ge),E("week",ge),E("month",ge),E("timestamp",ge),E("file",Cn),E("files",An),E("document",Cn),E("documents",An),E("image",hs),E("images",ms),E("geopoint",gs),E("address",vs),E("map",ys),E("array",Es),E("select",tr),E("multiselect",bs),E("radio",tr),E("combobox",tr),E("switch",Ss),E("reference",Is),E("hidden",rr),E("avatar",rr),E("badge",rr),E("submit",wn),E("reset",wn)}As();function Be(t){if(t.validation?.schema){let n=t.validation.schema;return _(n,t.validation?.required)}let e=Ve.get(t.type);if(e){let n=e(t);if(n!==null)return n}let r=d.unknown();return _(r,t.validation?.required)}var nr=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],yf="available",Ef=["draft","deleted"],ve=["id","createdAt","updatedAt","createdById","updatedById"],ws=[...ve,"status"];function bf(t){return ws.includes(t)}function If(t){return ve.includes(t)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...nr]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:it.source}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};function He(t,e){return Object.assign(t,{visibility:e})}function se(t,e){let r=t;return r.metadata={collection:e.collection,entity:e.name,...e.uniqueKeys&&{uniqueKeys:e.uniqueKeys}},r}function xn(t){let e=Be(t);return He(e,t.visibility)}function kn(t){let e=Be({...t,validation:{...t.validation,required:!1}});return He(e,t.visibility)}function Ps(t){let e=t.fields,r={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(r[R]=xn(P));let n=se(W.object(r),t),i={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(ve.includes(R)||(i[R]=xn(P)));let o=se(W.object(i),t),s={};for(let[R,P]of Object.entries(e))if(P.visibility!=="hidden"&&!ve.includes(R))if(R==="status"){let Y=W.literal("draft");s[R]=He(Y,P.visibility)}else s[R]=kn(P);let c=se(W.object(s),t),u={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(ve.includes(R)||(u[R]=kn(P)));u.id=He(Be(w.id),"technical");let p=se(W.object(u),t),g;if(t.listFields&&t.listFields.length>0){let R=["id","status"],P=[...new Set([...R,...t.listFields])];g={};for(let Y of P){let Oe=r[Y];Oe&&(g[Y]=Oe)}}else g=r;let T=se(W.object(g),t),O,F=t.listCardFields??t.listFields;if(F&&F.length>0){let R=["id","status"],P=[...new Set([...R,...F])];O={};for(let Y of P){let Oe=r[Y];Oe&&(O[Y]=Oe)}}else O=r;let ne=se(W.object(O),t),rt=se(W.object({id:He(Be(w.id),"technical")}),t);return{create:o,draft:c,update:p,get:n,list:T,listCard:ne,delete:rt}}import"valibot";function xf(t,e){let r=t;return r.metadata=e,r}var Rs={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var On=function(t){let e=[],r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=i&63|128):(i&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=i&63|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=i&63|128)}return e},xs=function(t){let e=[],r=0,n=0;for(;r<t.length;){let i=t[r++];if(i<128)e[n++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[r++];e[n++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[r++],s=t[r++],c=t[r++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[n++]=String.fromCharCode(55296+(u>>10)),e[n++]=String.fromCharCode(56320+(u&1023))}else{let o=t[r++],s=t[r++];e[n++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},Dn={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();let r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let i=0;i<t.length;i+=3){let o=t[i],s=i+1<t.length,c=s?t[i+1]:0,u=i+2<t.length,p=u?t[i+2]:0,g=o>>2,T=(o&3)<<4|c>>4,O=(c&15)<<2|p>>6,F=p&63;u||(F=64,s||(O=64)),n.push(r[g],r[T],r[O],r[F])}return n.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(On(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):xs(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let r=e?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let i=0;i<t.length;){let o=r[t.charAt(i++)],c=i<t.length?r[t.charAt(i)]:0;++i;let p=i<t.length?r[t.charAt(i)]:64;++i;let T=i<t.length?r[t.charAt(i)]:64;if(++i,o==null||c==null||p==null||T==null)throw new or;let O=o<<2|c>>4;if(n.push(O),p!==64){let F=c<<4&240|p>>2;if(n.push(F),T!==64){let ne=p<<6&192|T;n.push(ne)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},or=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},ks=function(t){let e=On(t);return Dn.encodeByteArray(e,!0)},ar=function(t){return ks(t).replace(/\./g,"")},cr=function(t){try{return Dn.decodeString(t,!0)}catch{}return null};function ur(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function B(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Nn(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(B())}function Un(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Ln(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Mn(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Fn(){try{return typeof indexedDB=="object"}catch{return!1}}function Vn(){return new Promise((t,e)=>{try{let r=!0,n="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(n);i.onsuccess=()=>{i.result.close(),r||self.indexedDB.deleteDatabase(n),t(!0)},i.onupgradeneeded=()=>{r=!1},i.onerror=()=>{e(i.error?.message||"")}}catch(r){e(r)}})}var Os="FirebaseError",q=class t extends Error{constructor(e,r,n){super(r),this.code=e,this.customData=n,this.name=Os,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,J.prototype.create)}},J=class{constructor(e,r,n){this.service=e,this.serviceName=r,this.errors=n}create(e,...r){let n=r[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?Ds(o,n):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new q(i,c,n)}};function Ds(t,e){return t.replace(Ns,(r,n)=>{let i=e[n];return i!=null?String(i):`<${n}?>`})}var Ns=/\{\$([^}]+)}/g;function ct(t){let e=[];for(let[r,n]of Object.entries(t))Array.isArray(n)?n.forEach(i=>{e.push(encodeURIComponent(r)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return e.length?"&"+e.join("&"):""}function ye(t){let e={};return t.replace(/^\?/,"").split("&").forEach(n=>{if(n){let[i,o]=n.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function Ee(t){let e=t.indexOf("?");if(!e)return"";let r=t.indexOf("#",e);return t.substring(e,r>0?r:void 0)}function Bn(t,e){let r=new sr(t,e);return r.subscribe.bind(r)}var sr=class{constructor(e,r){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=r,this.task.then(()=>{e(this)}).catch(n=>{this.error(n)})}next(e){this.forEachObserver(r=>{r.next(e)})}error(e){this.forEachObserver(r=>{r.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,r,n){let i;if(e===void 0&&r===void 0&&n===void 0)throw new Error("Missing Observer.");Us(e,["next","error","complete"])?i=e:i={next:e,error:r,complete:n},i.next===void 0&&(i.next=ir),i.error===void 0&&(i.error=ir),i.complete===void 0&&(i.complete=ir);let o=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),o}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let r=0;r<this.observers.length;r++)this.sendOne(r,e)}sendOne(e,r){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{r(this.observers[e])}catch{}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}};function Us(t,e){if(typeof t!="object"||t===null)return!1;for(let r of e)if(r in t&&typeof t[r]=="function")return!0;return!1}function ir(){}var Uf=14400*1e3;function $e(t){return t&&t._delegate?t._delegate:t}Rs.NODE_CLIENT=!0;var X=class{constructor(e,r,n){this.name=e,this.instanceFactory=r,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var Ls=[],S;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(S||(S={}));var Ms={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},Fs=S.INFO,Vs={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},Bs=(t,e,...r)=>{if(e<t.logLevel)return;let n=new Date().toISOString(),i=Vs[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},be=class{constructor(e){this.name=e,this._logLevel=Fs,this._logHandler=Bs,this._userLogHandler=null,Ls.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in S))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?Ms[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,S.DEBUG,...e),this._logHandler(this,S.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,S.VERBOSE,...e),this._logHandler(this,S.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,S.INFO,...e),this._logHandler(this,S.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,S.WARN,...e),this._logHandler(this,S.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,S.ERROR,...e),this._logHandler(this,S.ERROR,...e)}};var Hs=(t,e)=>e.some(r=>t instanceof r),Hn,$n;function $s(){return Hn||(Hn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ws(){return $n||($n=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Wn=new WeakMap,dr=new WeakMap,qn=new WeakMap,lr=new WeakMap,fr=new WeakMap;function qs(t){let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{r(G(t.result)),i()},s=()=>{n(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(r=>{r instanceof IDBCursor&&Wn.set(r,t)}).catch(()=>{}),fr.set(e,t),e}function Gs(t){if(dr.has(t))return;let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{r(),i()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});dr.set(t,e)}var pr={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return dr.get(t);if(e==="objectStoreNames")return t.objectStoreNames||qn.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return G(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function Gn(t){pr=t(pr)}function js(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(ut(this),e,...r);return qn.set(n,e.sort?e.sort():[e]),G(n)}:Ws().includes(t)?function(...e){return t.apply(ut(this),e),G(Wn.get(this))}:function(...e){return G(t.apply(ut(this),e))}}function Ks(t){return typeof t=="function"?js(t):(t instanceof IDBTransaction&&Gs(t),Hs(t,$s())?new Proxy(t,pr):t)}function G(t){if(t instanceof IDBRequest)return qs(t);if(lr.has(t))return lr.get(t);let e=Ks(t);return e!==t&&(lr.set(t,e),fr.set(e,t)),e}var ut=t=>fr.get(t);function Kn(t,e,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=G(s);return n&&s.addEventListener("upgradeneeded",u=>{n(G(s.result),u.oldVersion,u.newVersion,G(s.transaction),u)}),r&&s.addEventListener("blocked",u=>r(u.oldVersion,u.newVersion,u)),c.then(u=>{o&&u.addEventListener("close",()=>o()),i&&u.addEventListener("versionchange",p=>i(p.oldVersion,p.newVersion,p))}).catch(()=>{}),c}var zs=["get","getKey","getAll","getAllKeys","count"],Ys=["put","add","delete","clear"],hr=new Map;function jn(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(hr.get(e))return hr.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,i=Ys.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||zs.includes(r)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),p=u.store;return n&&(p=p.index(c.shift())),(await Promise.all([p[r](...c),i&&u.done]))[0]};return hr.set(e,o),o}Gn(t=>({...t,get:(e,r,n)=>jn(e,r)||t.get(e,r,n),has:(e,r)=>!!jn(e,r)||t.has(e,r)}));var gr=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(r=>{if(Xs(r)){let n=r.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(r=>r).join(" ")}};function Xs(t){return t.getComponent()?.type==="VERSION"}var vr="@firebase/app",zn="0.14.7";var Z=new be("@firebase/app"),Zs="@firebase/app-compat",Qs="@firebase/analytics-compat",ea="@firebase/analytics",ta="@firebase/app-check-compat",ra="@firebase/app-check",na="@firebase/auth",ia="@firebase/auth-compat",oa="@firebase/database",sa="@firebase/data-connect",aa="@firebase/database-compat",ca="@firebase/functions",ua="@firebase/functions-compat",la="@firebase/installations",da="@firebase/installations-compat",pa="@firebase/messaging",fa="@firebase/messaging-compat",ha="@firebase/performance",ma="@firebase/performance-compat",ga="@firebase/remote-config",va="@firebase/remote-config-compat",ya="@firebase/storage",Ea="@firebase/storage-compat",ba="@firebase/firestore",Ia="@firebase/ai",Ta="@firebase/firestore-compat",Sa="firebase",_a="12.8.0";var Ca={[vr]:"fire-core",[Zs]:"fire-core-compat",[ea]:"fire-analytics",[Qs]:"fire-analytics-compat",[ra]:"fire-app-check",[ta]:"fire-app-check-compat",[na]:"fire-auth",[ia]:"fire-auth-compat",[oa]:"fire-rtdb",[sa]:"fire-data-connect",[aa]:"fire-rtdb-compat",[ca]:"fire-fn",[ua]:"fire-fn-compat",[la]:"fire-iid",[da]:"fire-iid-compat",[pa]:"fire-fcm",[fa]:"fire-fcm-compat",[ha]:"fire-perf",[ma]:"fire-perf-compat",[ga]:"fire-rc",[va]:"fire-rc-compat",[ya]:"fire-gcs",[Ea]:"fire-gcs-compat",[ba]:"fire-fst",[Ta]:"fire-fst-compat",[Ia]:"fire-vertex","fire-js":"fire-js",[Sa]:"fire-js-all"};var Aa=new Map,wa=new Map,Yn=new Map;function Jn(t,e){try{t.container.addComponent(e)}catch(r){Z.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,r)}}function Te(t){let e=t.name;if(Yn.has(e))return Z.debug(`There were multiple attempts to register component ${e}.`),!1;Yn.set(e,t);for(let r of Aa.values())Jn(r,t);for(let r of wa.values())Jn(r,t);return!0}function ae(t){return t==null?!1:t.settings!==void 0}var Pa={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},br=new J("app","Firebase",Pa);var lt=_a;function Ie(t,e,r){let n=Ca[t]??t;r&&(n+=`-${r}`);let i=n.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${n}" with version "${e}":`];i&&s.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&o&&s.push("and"),o&&s.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Z.warn(s.join(" "));return}Te(new X(`${n}-version`,()=>({library:n,version:e}),"VERSION"))}var Ra="firebase-heartbeat-database",xa=1,We="firebase-heartbeat-store",mr=null;function ei(){return mr||(mr=Kn(Ra,xa,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(We)}catch{}}}}).catch(t=>{throw br.create("idb-open",{originalErrorMessage:t.message})})),mr}async function ka(t){try{let r=(await ei()).transaction(We),n=await r.objectStore(We).get(ti(t));return await r.done,n}catch(e){if(e instanceof q)Z.warn(e.message);else{let r=br.create("idb-get",{originalErrorMessage:e?.message});Z.warn(r.message)}}}async function Xn(t,e){try{let n=(await ei()).transaction(We,"readwrite");await n.objectStore(We).put(e,ti(t)),await n.done}catch(r){if(r instanceof q)Z.warn(r.message);else{let n=br.create("idb-set",{originalErrorMessage:r?.message});Z.warn(n.message)}}}function ti(t){return`${t.name}!${t.options.appId}`}var Oa=1024,Da=30,yr=class{constructor(e){this.container=e,this._heartbeatsCache=null;let r=this.container.getProvider("app").getImmediate();this._storage=new Er(r),this._heartbeatsCachePromise=this._storage.read().then(n=>(this._heartbeatsCache=n,n))}async triggerHeartbeat(){try{let r=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),n=Zn();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===n||this._heartbeatsCache.heartbeats.some(i=>i.date===n))return;if(this._heartbeatsCache.heartbeats.push({date:n,agent:r}),this._heartbeatsCache.heartbeats.length>Da){let i=Ua(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){Z.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";let e=Zn(),{heartbeatsToSend:r,unsentEntries:n}=Na(this._heartbeatsCache.heartbeats),i=ar(JSON.stringify({version:2,heartbeats:r}));return this._heartbeatsCache.lastSentHeartbeatDate=e,n.length>0?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Z.warn(e),""}}};function Zn(){return new Date().toISOString().substring(0,10)}function Na(t,e=Oa){let r=[],n=t.slice();for(let i of t){let o=r.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),Qn(r)>e){o.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),Qn(r)>e){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}}var Er=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Fn()?Vn().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let r=await ka(this.app);return r?.heartbeats?r:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let n=await this.read();return Xn(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let n=await this.read();return Xn(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}else return}};function Qn(t){return ar(JSON.stringify({version:2,heartbeats:t})).length}function Ua(t){if(t.length===0)return-1;let e=0,r=t[0].date;for(let n=1;n<t.length;n++)t[n].date<r&&(r=t[n].date,e=n);return e}function La(t){Te(new X("platform-logger",e=>new gr(e),"PRIVATE")),Te(new X("heartbeat",e=>new yr(e),"PRIVATE")),Ie(vr,zn,t),Ie(vr,zn,"esm2020"),Ie("fire-js","")}La("");function li(){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 di=li,pi=new J("auth","Firebase",li());var mt=new be("@firebase/auth");function Ma(t,...e){mt.logLevel<=S.WARN&&mt.warn(`Auth (${lt}): ${t}`,...e)}function ft(t,...e){mt.logLevel<=S.ERROR&&mt.error(`Auth (${lt}): ${t}`,...e)}function Se(t,...e){throw Vr(t,...e)}function Fr(t,...e){return Vr(t,...e)}function fi(t,e,r){let n={...di(),[e]:r};return new J("auth","Firebase",n).create(e,{appName:t.name})}function ht(t){return fi(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Vr(t,...e){if(typeof t!="string"){let r=e[0],n=[...e.slice(1)];return n[0]&&(n[0].appName=t.name),t._errorFactory.create(r,...n)}return pi.create(t,...e)}function I(t,e,...r){if(!t)throw Vr(e,...r)}function j(t){let e="INTERNAL ASSERTION FAILED: "+t;throw ft(e),new Error(e)}function gt(t,e){t||j(e)}function Fa(){return ri()==="http:"||ri()==="https:"}function ri(){return typeof self<"u"&&self.location?.protocol||null}function Va(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(Fa()||Ln()||"connection"in navigator)?navigator.onLine:!0}function Ba(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var _r=class{constructor(e,r){this.shortDelay=e,this.longDelay=r,gt(r>e,"Short delay should be less than long delay!"),this.isMobile=Nn()||Mn()}get(){return Va()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function Ha(t,e){gt(t.emulator,"Emulator should always be set here");let{url:r}=t.emulator;return e?`${r}${e.startsWith("/")?e.slice(1):e}`:r}var Ke=class{static initialize(e,r,n){this.fetchImpl=e,r&&(this.headersImpl=r),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;j("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;j("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;j("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var $a={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"};var Wa=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],qa=new _r(3e4,6e4);function K(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function z(t,e,r,n,i={}){return hi(t,i,async()=>{let o={},s={};n&&(e==="GET"?s=n:o={body:JSON.stringify(n)});let c=ct({key:t.config.apiKey,...s}).slice(1),u=await t._getAdditionalHeaders();u["Content-Type"]="application/json",t.languageCode&&(u["X-Firebase-Locale"]=t.languageCode);let p={method:e,headers:u,...o};return Un()||(p.referrerPolicy="no-referrer"),t.emulatorConfig&&ur(t.emulatorConfig.host)&&(p.credentials="include"),Ke.fetch()(await mi(t,t.config.apiHost,r,c),p)})}async function hi(t,e,r){t._canInitEmulator=!1;let n={...$a,...e};try{let i=new Cr(t),o=await Promise.race([r(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw dt(t,"account-exists-with-different-credential",s);if(o.ok&&!("errorMessage"in s))return s;{let c=o.ok?s.errorMessage:s.error.message,[u,p]=c.split(" : ");if(u==="FEDERATED_USER_ID_ALREADY_LINKED")throw dt(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw dt(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw dt(t,"user-disabled",s);let g=n[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(p)throw fi(t,g,p);Se(t,g)}}catch(i){if(i instanceof q)throw i;Se(t,"network-request-failed",{message:String(i)})}}async function wt(t,e,r,n,i={}){let o=await z(t,e,r,n,i);return"mfaPendingCredential"in o&&Se(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function mi(t,e,r,n){let i=`${e}${r}?${n}`,o=t,s=o.config.emulator?Ha(t.config,i):`${t.config.apiScheme}://${i}`;return Wa.includes(r)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function Ga(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var Cr=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((r,n)=>{this.timer=setTimeout(()=>n(Fr(this.auth,"network-request-failed")),qa.get())})}};function dt(t,e,r){let n={appName:t.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);let i=Fr(t,e,n);return i.customData._tokenResponse=r,i}function ni(t){return t!==void 0&&t.enterprise!==void 0}var Ar=class{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(let r of this.recaptchaEnforcementState)if(r.provider&&r.provider===e)return Ga(r.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 ja(t,e){return z(t,"GET","/v2/recaptchaConfig",K(t,e))}async function Ka(t,e){return z(t,"POST","/v1/accounts:delete",e)}async function vt(t,e){return z(t,"POST","/v1/accounts:lookup",e)}function Ge(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function gi(t,e=!1){let r=$e(t),n=await r.getIdToken(e),i=vi(n);I(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:n,authTime:Ge(Ir(i.auth_time)),issuedAtTime:Ge(Ir(i.iat)),expirationTime:Ge(Ir(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function Ir(t){return Number(t)*1e3}function vi(t){let[e,r,n]=t.split(".");if(e===void 0||r===void 0||n===void 0)return ft("JWT malformed, contained fewer than 3 sections"),null;try{let i=cr(r);return i?JSON.parse(i):(ft("Failed to decode base64 JWT payload"),null)}catch(i){return ft("Caught error parsing JWT payload as JSON",i?.toString()),null}}function ii(t){let e=vi(t);return I(e,"internal-error"),I(typeof e.exp<"u","internal-error"),I(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function wr(t,e,r=!1){if(r)return e;try{return await e}catch(n){throw n instanceof q&&za(n)&&t.auth.currentUser===t&&await t.auth.signOut(),n}}function za({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var Pr=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 r=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),r}else{this.errorBackoff=3e4;let n=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,n)}}schedule(e=!1){if(!this.isRunning)return;let r=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},r)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var ze=class{constructor(e,r){this.createdAt=e,this.lastLoginAt=r,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ge(this.lastLoginAt),this.creationTime=Ge(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function yt(t){let e=t.auth,r=await t.getIdToken(),n=await wr(t,vt(e,{idToken:r}));I(n?.users.length,e,"internal-error");let i=n.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?Ei(i.providerUserInfo):[],s=Ya(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,p=c?u:!1,g={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:s,metadata:new ze(i.createdAt,i.lastLoginAt),isAnonymous:p};Object.assign(t,g)}async function yi(t){let e=$e(t);await yt(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function Ya(t,e){return[...t.filter(n=>!e.some(i=>i.providerId===n.providerId)),...e]}function Ei(t){return t.map(({providerId:e,...r})=>({providerId:e,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}))}async function Ja(t,e){let r=await hi(t,{},async()=>{let n=ct({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await mi(t,i,"/v1/token",`key=${o}`),c=await t._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";let u={method:"POST",headers:c,body:n};return t.emulatorConfig&&ur(t.emulatorConfig.host)&&(u.credentials="include"),Ke.fetch()(s,u)});return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}async function Xa(t,e){return z(t,"POST","/v2/accounts:revokeToken",K(t,e))}var je=class t{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){I(e.idToken,"internal-error"),I(typeof e.idToken<"u","internal-error"),I(typeof e.refreshToken<"u","internal-error");let r="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):ii(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,r)}updateFromIdToken(e){I(e.length!==0,"internal-error");let r=ii(e);this.updateTokensAndExpiration(e,null,r)}async getToken(e,r=!1){return!r&&this.accessToken&&!this.isExpired?this.accessToken:(I(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,r){let{accessToken:n,refreshToken:i,expiresIn:o}=await Ja(e,r);this.updateTokensAndExpiration(n,i,Number(o))}updateTokensAndExpiration(e,r,n){this.refreshToken=r||null,this.accessToken=e||null,this.expirationTime=Date.now()+n*1e3}static fromJSON(e,r){let{refreshToken:n,accessToken:i,expirationTime:o}=r,s=new t;return n&&(I(typeof n=="string","internal-error",{appName:e}),s.refreshToken=n),i&&(I(typeof i=="string","internal-error",{appName:e}),s.accessToken=i),o&&(I(typeof o=="number","internal-error",{appName:e}),s.expirationTime=o),s}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 t,this.toJSON())}_performRefresh(){return j("not implemented")}};function ee(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var ce=class t{constructor({uid:e,auth:r,stsTokenManager:n,...i}){this.providerId="firebase",this.proactiveRefresh=new Pr(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=r,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new ze(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let r=await wr(this,this.stsTokenManager.getToken(this.auth,e));return I(r,this.auth,"internal-error"),this.accessToken!==r&&(this.accessToken=r,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),r}getIdTokenResult(e){return gi(this,e)}reload(){return yi(this)}_assign(e){this!==e&&(I(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(r=>({...r})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let r=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return r.metadata._copy(this.metadata),r}_onReload(e){I(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,r=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),r&&await yt(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(ae(this.auth.app))return Promise.reject(ht(this.auth));let e=await this.getIdToken();return await wr(this,Ka(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,r){let n=r.displayName??void 0,i=r.email??void 0,o=r.phoneNumber??void 0,s=r.photoURL??void 0,c=r.tenantId??void 0,u=r._redirectEventId??void 0,p=r.createdAt??void 0,g=r.lastLoginAt??void 0,{uid:T,emailVerified:O,isAnonymous:F,providerData:ne,stsTokenManager:rt}=r;I(T&&rt,e,"internal-error");let R=je.fromJSON(this.name,rt);I(typeof T=="string",e,"internal-error"),ee(n,e.name),ee(i,e.name),I(typeof O=="boolean",e,"internal-error"),I(typeof F=="boolean",e,"internal-error"),ee(o,e.name),ee(s,e.name),ee(c,e.name),ee(u,e.name),ee(p,e.name),ee(g,e.name);let P=new t({uid:T,auth:e,email:i,emailVerified:O,displayName:n,isAnonymous:F,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:R,createdAt:p,lastLoginAt:g});return ne&&Array.isArray(ne)&&(P.providerData=ne.map(Y=>({...Y}))),u&&(P._redirectEventId=u),P}static async _fromIdTokenResponse(e,r,n=!1){let i=new je;i.updateFromServerResponse(r);let o=new t({uid:r.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await yt(o),o}static async _fromGetAccountInfoResponse(e,r,n){let i=r.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?Ei(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new je;c.updateFromIdToken(n);let u=new t({uid:i.localId,auth:e,stsTokenManager:c,isAnonymous:s}),p={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:o,metadata:new ze(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,p),u}};var oi=new Map;function ue(t){gt(t instanceof Function,"Expected a class definition");let e=oi.get(t);return e?(gt(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,oi.set(t,e),e)}var Et=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,r){this.storage[e]=r}async _get(e){let r=this.storage[e];return r===void 0?null:r}async _remove(e){delete this.storage[e]}_addListener(e,r){}_removeListener(e,r){}};Et.type="NONE";var Rr=Et;function Tr(t,e,r){return`firebase:${t}:${e}:${r}`}var bt=class t{constructor(e,r,n){this.persistence=e,this.auth=r,this.userKey=n;let{config:i,name:o}=this.auth;this.fullUserKey=Tr(this.userKey,i.apiKey,o),this.fullPersistenceKey=Tr("persistence",i.apiKey,o),this.boundEventHandler=r._onStorageEvent.bind(r),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 r=await vt(this.auth,{idToken:e}).catch(()=>{});return r?ce._fromGetAccountInfoResponse(this.auth,r,e):null}return ce._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 r=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,r)return this.setCurrentUser(r)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,r,n="authUser"){if(!r.length)return new t(ue(Rr),e,n);let i=(await Promise.all(r.map(async p=>{if(await p._isAvailable())return p}))).filter(p=>p),o=i[0]||ue(Rr),s=Tr(n,e.config.apiKey,e.name),c=null;for(let p of r)try{let g=await p._get(s);if(g){let T;if(typeof g=="string"){let O=await vt(e,{idToken:g}).catch(()=>{});if(!O)break;T=await ce._fromGetAccountInfoResponse(e,O,g)}else T=ce._fromJSON(e,g);p!==o&&(c=T),o=p;break}}catch{}let u=i.filter(p=>p._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,n):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(r.map(async p=>{if(p!==o)try{await p._remove(s)}catch{}})),new t(o,e,n))}};function si(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(tc(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Za(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(nc(e))return"Blackberry";if(ic(e))return"Webos";if(Qa(e))return"Safari";if((e.includes("chrome/")||ec(e))&&!e.includes("edge/"))return"Chrome";if(rc(e))return"Android";{let r=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=t.match(r);if(n?.length===2)return n[1]}return"Other"}function Za(t=B()){return/firefox\//i.test(t)}function Qa(t=B()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function ec(t=B()){return/crios\//i.test(t)}function tc(t=B()){return/iemobile/i.test(t)}function rc(t=B()){return/android/i.test(t)}function nc(t=B()){return/blackberry/i.test(t)}function ic(t=B()){return/webos/i.test(t)}function bi(t,e=[]){let r;switch(t){case"Browser":r=si(B());break;case"Worker":r=`${si(B())}-${t}`;break;default:r=t}let n=e.length?e.join(","):"FirebaseCore-web";return`${r}/JsCore/${lt}/${n}`}var xr=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,r){let n=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});n.onAbort=r,this.queue.push(n);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let r=[];try{for(let n of this.queue)await n(e),n.onAbort&&r.push(n.onAbort)}catch(n){r.reverse();for(let i of r)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:n?.message})}}};async function oc(t,e={}){return z(t,"GET","/v2/passwordPolicy",K(t,e))}var sc=6,kr=class{constructor(e){let r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=r.minPasswordLength??sc,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),r.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),r.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),r.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),r.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.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 r={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,r),this.validatePasswordCharacterOptions(e,r),r.isValid&&(r.isValid=r.meetsMinPasswordLength??!0),r.isValid&&(r.isValid=r.meetsMaxPasswordLength??!0),r.isValid&&(r.isValid=r.containsLowercaseLetter??!0),r.isValid&&(r.isValid=r.containsUppercaseLetter??!0),r.isValid&&(r.isValid=r.containsNumericCharacter??!0),r.isValid&&(r.isValid=r.containsNonAlphanumericCharacter??!0),r}validatePasswordLengthOptions(e,r){let n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(r.meetsMinPasswordLength=e.length>=n),i&&(r.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,r){this.updatePasswordCharacterOptionsStatuses(r,!1,!1,!1,!1);let n;for(let i=0;i<e.length;i++)n=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(r,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,r,n,i,o){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=r)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=o))}};var It=class{constructor(e,r,n,i){this.app=e,this.heartbeatServiceProvider=r,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Tt(this),this.idTokenSubscription=new Tt(this),this.beforeStateQueue=new xr(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=pi,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=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(o=>this._resolvePersistenceManagerAvailable=o)}_initializeWithPersistence(e,r){return r&&(this._popupRedirectResolver=ue(r)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await bt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(r),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 r=await vt(this,{idToken:e}),n=await ce._fromGetAccountInfoResponse(this,r,e);await this.directlySetCurrentUser(n)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(ae(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let r=await this.assertedPersistence.getCurrentUser(),n=r,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=n?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(n=c.user,i=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(n)}catch(o){n=r,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return I(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 r=null;try{r=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return r}async reloadAndSetCurrentUserOrClear(e){try{await yt(e)}catch(r){if(r?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=Ba()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(ae(this.app))return Promise.reject(ht(this));let r=e?$e(e):null;return r&&I(r.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,r=!1){if(!this._deleted)return e&&I(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),r||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return ae(this.app)?Promise.reject(ht(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return ae(this.app)?Promise.reject(ht(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(ue(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let r=this._getPasswordPolicyInternal();return r.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):r.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=await oc(this),r=new kr(e);this.tenantId===null?this._projectPasswordPolicy=r:this._tenantPasswordPolicies[this.tenantId]=r}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new J("auth","Firebase",e())}onAuthStateChanged(e,r,n){return this.registerStateListener(this.authStateSubscription,e,r,n)}beforeAuthStateChanged(e,r){return this.beforeStateQueue.pushCallback(e,r)}onIdTokenChanged(e,r,n){return this.registerStateListener(this.idTokenSubscription,e,r,n)}authStateReady(){return new Promise((e,r)=>{if(this.currentUser)e();else{let n=this.onAuthStateChanged(()=>{n(),e()},r)}})}async revokeAccessToken(e){if(this.currentUser){let r=await this.currentUser.getIdToken(),n={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:r};this.tenantId!=null&&(n.tenantId=this.tenantId),await Xa(this,n)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,r){let n=await this.getOrInitRedirectPersistenceManager(r);return e===null?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let r=e&&ue(e)||this._popupRedirectResolver;I(r,this,"argument-error"),this.redirectPersistenceManager=await bt.create(this,[ue(r._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,r,n,i){if(this._deleted)return()=>{};let o=typeof r=="function"?r:r.next.bind(r),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof r=="function"){let u=e.addObserver(r,n,i);return()=>{s=!0,u()}}else{let u=e.addObserver(r);return()=>{s=!0,u()}}}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 I(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=bi(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 r=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();r&&(e["X-Firebase-Client"]=r);let n=await this._getAppCheckToken();return n&&(e["X-Firebase-AppCheck"]=n),e}async _getAppCheckToken(){if(ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&Ma(`Error while retrieving App Check token: ${e.error}`),e?.token}};function Ii(t){return $e(t)}var Tt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Bn(r=>this.observer=r)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var Ti={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function ac(t){return Ti.loadJS(t)}function cc(){return Ti.recaptchaEnterpriseScript}var Or=class{constructor(){this.enterprise=new Dr}ready(e){e()}execute(e,r){return Promise.resolve("token")}render(e,r){return""}},Dr=class{ready(e){e()}execute(e,r){return Promise.resolve("token")}render(e,r){return""}},uc="recaptcha-enterprise",Si="NO_RECAPTCHA",Nr=class{constructor(e){this.type=uc,this.auth=Ii(e)}async verify(e="verify",r=!1){async function n(o){if(!r){if(o.tenantId==null&&o._agentRecaptchaConfig!=null)return o._agentRecaptchaConfig.siteKey;if(o.tenantId!=null&&o._tenantRecaptchaConfigs[o.tenantId]!==void 0)return o._tenantRecaptchaConfigs[o.tenantId].siteKey}return new Promise(async(s,c)=>{ja(o,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(u=>{if(u.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{let p=new Ar(u);return o.tenantId==null?o._agentRecaptchaConfig=p:o._tenantRecaptchaConfigs[o.tenantId]=p,s(p.siteKey)}}).catch(u=>{c(u)})})}function i(o,s,c){let u=window.grecaptcha;ni(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(p=>{s(p)}).catch(()=>{s(Si)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new Or().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{n(this.auth).then(c=>{if(!r&&ni(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=cc();u.length!==0&&(u+=c),ac(u).then(()=>{i(c,o,s)}).catch(p=>{s(p)})}}).catch(c=>{s(c)})})}};async function qe(t,e,r,n=!1,i=!1){let o=new Nr(t),s;if(i)s=Si;else try{s=await o.verify(r)}catch{s=await o.verify(r,!0)}let c={...e};if(r==="mfaSmsEnrollment"||r==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){let u=c.phoneEnrollmentInfo.phoneNumber,p=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:u,recaptchaToken:p,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){let u=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:u,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return n?Object.assign(c,{captchaResp:s}):Object.assign(c,{captchaResponse:s}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function ai(t,e,r,n,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await qe(t,e,r,r==="getOobCode");return n(t,o)}else return n(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await qe(t,e,r,r==="getOobCode");return n(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await qe(t,e,r);return n(t,o).catch(async s=>{if(t._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"&&(s.code==="auth/missing-recaptcha-token"||s.code==="auth/invalid-app-credential")){let c=await qe(t,e,r,!1,!0);return n(t,c)}return Promise.reject(s)})}else{let o=await qe(t,e,r,!1,!0);return n(t,o)}else return Promise.reject(i+" provider is not supported.")}function lc(t,e){let r=e?.persistence||[],n=(Array.isArray(r)?r:[r]).map(ue);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(n,e?.popupRedirectResolver)}var Ye=class{constructor(e,r){this.providerId=e,this.signInMethod=r}toJSON(){return j("not implemented")}_getIdTokenResponse(e){return j("not implemented")}_linkToIdToken(e,r){return j("not implemented")}_getReauthenticationResolver(e){return j("not implemented")}};async function dc(t,e){return z(t,"POST","/v1/accounts:signUp",e)}async function pc(t,e){return wt(t,"POST","/v1/accounts:signInWithPassword",K(t,e))}async function fc(t,e){return wt(t,"POST","/v1/accounts:signInWithEmailLink",K(t,e))}async function hc(t,e){return wt(t,"POST","/v1/accounts:signInWithEmailLink",K(t,e))}var Je=class t extends Ye{constructor(e,r,n,i=null){super("password",n),this._email=e,this._password=r,this._tenantId=i}static _fromEmailAndPassword(e,r){return new t(e,r,"password")}static _fromEmailAndCode(e,r,n=null){return new t(e,r,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let r=typeof e=="string"?JSON.parse(e):e;if(r?.email&&r?.password){if(r.signInMethod==="password")return this._fromEmailAndPassword(r.email,r.password);if(r.signInMethod==="emailLink")return this._fromEmailAndCode(r.email,r.password,r.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let r={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return ai(e,r,"signInWithPassword",pc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return fc(e,{email:this._email,oobCode:this._password});default:Se(e,"internal-error")}}async _linkToIdToken(e,r){switch(this.signInMethod){case"password":let n={idToken:r,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return ai(e,n,"signUpPassword",dc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return hc(e,{idToken:r,email:this._email,oobCode:this._password});default:Se(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Sr(t,e){return wt(t,"POST","/v1/accounts:signInWithIdp",K(t,e))}var mc="http://localhost",le=class t extends Ye{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let r=new t(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(r.idToken=e.idToken),e.accessToken&&(r.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(r.nonce=e.nonce),e.pendingToken&&(r.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(r.accessToken=e.oauthToken,r.secret=e.oauthTokenSecret):Se("argument-error"),r}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let r=typeof e=="string"?JSON.parse(e):e,{providerId:n,signInMethod:i,...o}=r;if(!n||!i)return null;let s=new t(n,i);return s.idToken=o.idToken||void 0,s.accessToken=o.accessToken||void 0,s.secret=o.secret,s.nonce=o.nonce,s.pendingToken=o.pendingToken||null,s}_getIdTokenResponse(e){let r=this.buildRequest();return Sr(e,r)}_linkToIdToken(e,r){let n=this.buildRequest();return n.idToken=r,Sr(e,n)}_getReauthenticationResolver(e){let r=this.buildRequest();return r.autoCreate=!1,Sr(e,r)}buildRequest(){let e={requestUri:mc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let r={};this.idToken&&(r.id_token=this.idToken),this.accessToken&&(r.access_token=this.accessToken),this.secret&&(r.oauth_token_secret=this.secret),r.providerId=this.providerId,this.nonce&&!this.pendingToken&&(r.nonce=this.nonce),e.postBody=ct(r)}return e}};function gc(t){switch(t){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 vc(t){let e=ye(Ee(t)).link,r=e?ye(Ee(e)).deep_link_id:null,n=ye(Ee(t)).deep_link_id;return(n?ye(Ee(n)).link:null)||n||r||e||t}var St=class t{constructor(e){let r=ye(Ee(e)),n=r.apiKey??null,i=r.oobCode??null,o=gc(r.mode??null);I(n&&i&&o,"argument-error"),this.apiKey=n,this.operation=o,this.code=i,this.continueUrl=r.continueUrl??null,this.languageCode=r.lang??null,this.tenantId=r.tenantId??null}static parseLink(e){let r=vc(e);try{return new t(r)}catch{return null}}};var _e=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,r){return Je._fromEmailAndPassword(e,r)}static credentialWithLink(e,r){let n=St.parseLink(r);return I(n,"argument-error"),Je._fromEmailAndCode(e,n.code,n.tenantId)}};_e.PROVIDER_ID="password";_e.EMAIL_PASSWORD_SIGN_IN_METHOD="password";_e.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var Ur=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}};var Ce=class extends Ur{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var Ae=class t extends Ce{constructor(){super("facebook.com")}static credential(e){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Ae.FACEBOOK_SIGN_IN_METHOD="facebook.com";Ae.PROVIDER_ID="facebook.com";var we=class t extends Ce{constructor(){super("google.com"),this.addScope("profile")}static credential(e,r){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:r})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:r,oauthAccessToken:n}=e;if(!r&&!n)return null;try{return t.credential(r,n)}catch{return null}}};we.GOOGLE_SIGN_IN_METHOD="google.com";we.PROVIDER_ID="google.com";var Pe=class t extends Ce{constructor(){super("github.com")}static credential(e){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Pe.GITHUB_SIGN_IN_METHOD="github.com";Pe.PROVIDER_ID="github.com";var Re=class t extends Ce{constructor(){super("twitter.com")}static credential(e,r){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:r})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:r,oauthTokenSecret:n}=e;if(!r||!n)return null;try{return t.credential(r,n)}catch{return null}}};Re.TWITTER_SIGN_IN_METHOD="twitter.com";Re.PROVIDER_ID="twitter.com";function yc(t,e){return z(t,"POST","/v2/accounts/mfaEnrollment:start",K(t,e))}function Ec(t,e){return z(t,"POST","/v2/accounts/mfaEnrollment:finalize",K(t,e))}var ci="@firebase/auth",ui="1.12.0";var Lr=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 r=this.auth.onIdTokenChanged(n=>{e(n?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,r),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let r=this.internalListeners.get(e);r&&(this.internalListeners.delete(e),r(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function bc(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function Ic(t){Te(new X("auth",(e,{options:r})=>{let n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=n.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:bi(t)},p=new It(n,i,o,u);return lc(p,r),p},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,r,n)=>{e.getProvider("auth-internal").initialize()})),Te(new X("auth-internal",e=>{let r=Ii(e.getProvider("auth").getImmediate());return(n=>new Lr(n))(r)},"PRIVATE").setInstantiationMode("EXPLICIT")),Ie(ci,ui,bc(t)),Ie(ci,ui,"esm2020")}Ke.initialize(fetch,Headers,Response);Ic("Node");var fh=Fr("operation-not-supported-in-this-environment");It.prototype.setPersistence=async()=>{};function Tc(t,e){return z(t,"POST","/v2/accounts/mfaSignIn:finalize",K(t,e))}var Mr=class{constructor(e){this.factorId=e}_process(e,r,n){switch(r.type){case"enroll":return this._finalizeEnroll(e,r.credential,n);case"signin":return this._finalizeSignIn(e,r.credential);default:return j("unexpected MultiFactorSessionType")}}},_t=class{static assertionForEnrollment(e,r){return Ct._fromSecret(e,r)}static assertionForSignIn(e,r){return Ct._fromEnrollmentId(e,r)}static async generateSecret(e){let r=e;I(typeof r.user?.auth<"u","internal-error");let n=await yc(r.user.auth,{idToken:r.credential,totpEnrollmentInfo:{}});return At._fromStartTotpMfaEnrollmentResponse(n,r.user.auth)}};_t.FACTOR_ID="totp";var Ct=class t extends Mr{constructor(e,r,n){super("totp"),this.otp=e,this.enrollmentId=r,this.secret=n}static _fromSecret(e,r){return new t(r,void 0,e)}static _fromEnrollmentId(e,r){return new t(r,e)}async _finalizeEnroll(e,r,n){return I(typeof this.secret<"u",e,"argument-error"),Ec(e,{idToken:r,displayName:n,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,r){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let n={verificationCode:this.otp};return Tc(e,{mfaPendingCredential:r,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:n})}},At=class t{constructor(e,r,n,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=r,this.codeLength=n,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,r){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,r)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,r){let n=!1;return(pt(e)||pt(r))&&(n=!0),n&&(pt(e)&&(e=this.auth.currentUser?.email||"unknownuser"),pt(r)&&(r=this.auth.name)),`otpauth://totp/${r}:${e}?secret=${this.secretKey}&issuer=${r}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function pt(t){return typeof t>"u"||t?.length===0}import*as y from"valibot";function L(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var te=null;function Qe(){return Ci().platform}function Ci(){if(te)return te;let t=L();if(t?.platform)return te={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},te;let e=[];e.push(..._c()),e.push(...Cc());let r=e.sort((n,i)=>i.confidence-n.confidence)[0];return!r||r.confidence<U.MINIMUM?(te={platform:A.UNKNOWN,mode:_i(),context:Ac(),metadata:{detectedAt:Date.now()}},te):(te={platform:r.platform,mode:_i(),context:r.context,version:wc(r.platform),metadata:{...r.metadata,detectedAt:Date.now()}},te)}var Xe=null,Ze=null;function Ai(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return Ze=!0,!0;if(Ze===!0)return!0;let t=L();if(t?.platform){let r=t.platform===A.NEXTJS;return r&&(Ze=!0),r}let e=Qe()===A.NEXTJS;return e&&(Ze=!0),e}function wi(){if(Xe!==null)return Xe;let t=L();if(t?.platform)return Xe=t.platform===A.VITE,Xe;let e=Qe()===A.VITE;return Xe=e,e}function M(){return typeof window<"u"}function Br(){return typeof process<"u"&&!!process.versions?.node}function _c(){let t=[];if(M()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:A.VITE,confidence:U.HIGH,context:D.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=L();e?.platform===A.VITE&&t.push({platform:A.VITE,confidence:U.HIGH,context:D.CLIENT}),e?.i18n?.mapping&&t.push({platform:A.VITE,confidence:U.MEDIUM,context:D.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:A.VITE,confidence:U.LOW,context:D.CLIENT})}return Br()&&(process.env.VITE&&t.push({platform:A.VITE,confidence:U.MEDIUM,context:D.SERVER}),process.env.npm_lifecycle_event?.includes(A.VITE)&&t.push({platform:A.VITE,confidence:U.LOW,context:D.BUILD})),t}function Cc(){let t=[];return Br()&&(process.env.NEXT_RUNTIME&&t.push({platform:A.NEXTJS,confidence:U.HIGH,context:D.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:A.NEXTJS,confidence:U.MEDIUM,context:D.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:A.NEXTJS,confidence:U.LOW,context:D.SERVER})),M()&&(L()?.platform===A.NEXTJS&&t.push({platform:A.NEXTJS,confidence:U.HIGH,context:D.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:A.NEXTJS,confidence:U.LOW,context:D.CLIENT})),t}function _i(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===ie.PRODUCTION?ie.PRODUCTION:t===ie.TEST?ie.TEST:ie.DEVELOPMENT}function Ac(){return M()?D.CLIENT:Br()?ie.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?D.BUILD:D.SERVER:D.CLIENT}function wc(t){if(!(typeof process>"u"))return t===A.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===A.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function Pi(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Pc(t){let e,r=L();return r?.env&&typeof r.env=="object"&&(e=r.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Pi(e)}function Rc(t){let e=L(),r;return e?.env&&typeof e.env=="object"&&(r=e.env[t]),r===void 0&&typeof process<"u"&&process.env&&(r=process.env[t]),Pi(r)}function k(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=L();if(s?.env?.MODE)return t==="DEV"?s.env.MODE==="development"?"true":"false":t==="PROD"?s.env.MODE==="production"?"true":"false":s.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let c=import.meta.env;if(t==="MODE"&&c.MODE)return c.MODE;if(t==="DEV")return c.DEV?"true":"false";if(t==="PROD")return c.PROD?"true":"false"}if(typeof process<"u"){let c="production";return t==="DEV"?c==="development"?"true":"false":t==="PROD"?c==="production"?"true":"false":c}return t==="DEV"?"true":t==="PROD"?"false":"development"}let r=L()?.platform,n=e||r||(wi()?"vite":Ai()?"nextjs":Qe()),i=["MODE","DEV","PROD","SSR"],o;return n==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:n==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,n==="vite"?Pc(o):n==="nextjs"?Rc(o):void 0}function Ri(){if(typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production"))return!0;let t=k("APP_ENV"),e=k("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var xi=y.object({name:y.string(),color:y.string(),icon:y.string(),button:y.object({backgroundColor:y.string(),textColor:y.string(),borderColor:y.string(),hoverBackgroundColor:y.string(),focusOutlineColor:y.string(),fontWeight:y.optional(y.string(),"500")})}),xc=y.object({...xi.entries,type:y.picklist(["auth","both"]),scopes:y.optional(y.array(y.string())),firebaseProviderId:y.optional(y.string())}),Pt=y.union([y.literal(""),y.pipe(y.string(),y.url())]),kc=y.object({authUrl:Pt,tokenUrl:Pt,profileUrl:Pt,revokeUrl:y.optional(Pt)}),Oc=y.object({authentication:y.optional(y.array(y.string())),"api-access":y.array(y.string())}),Qm=y.object({...xi.entries,type:y.picklist(["oauth","both"]),scopes:Oc,endpoints:kc}),et=null;function Dc(){let t=[];for(let[e,r]of Object.entries(me))y.safeParse(xc,r).success?t.push(e):typeof window<"u"&&Ri();return t}function Rt(){if(et!==null)return et;let t=k("AUTH_PARTNERS");if(!t)return et=[],et;let e=Dc(),r=t.split(",").map(n=>n.trim().toLowerCase()).filter(n=>e.includes(n));return et=r,r}var Nc=12e4,Hr=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,r={}){this.authInstance=e,this.refreshBuffer=r.refreshBufferMs??Nc,this.maxRefreshAttempts=r.maxRefreshAttempts??3,this.autoRefresh=r.autoRefresh!==!1,this.onTokenExpired=r.onTokenExpired,this.onFatalError=r.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let r=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:r},this.autoRefresh&&e.expiresAt&&this.scheduleRefresh(e.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(e){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(e&&typeof e.getIdToken=="function"){let r=await e.getIdToken(!0),n=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:r,expiresAt:n}),r}else if(e&&typeof e.getIdTokenResult=="function"){let r=await e.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),r.token}if(this.authInstance?.currentUser){let r=await this.authInstance.currentUser.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),r.token}throw v(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(r){return this.handleError(r instanceof Error?r:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:r}=this.tokenInfo;if(e==="valid")return r;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(this.authInstance?.currentUser)return await this.forceRefresh(this.authInstance.currentUser)}catch(n){this.handleError(n instanceof Error?n:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:r}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let r={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},n=this.calculateTokenStatus(r.expiresAt);this.tokenInfo={...r,status:n},this.autoRefresh&&r.expiresAt&&this.scheduleRefresh(r.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let r=new Date;if(r>=e)return"expired";let n=new Date(e.getTime()-this.refreshBuffer);return r>=n?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let r=new Date,n=e.getTime()-r.getTime()-this.refreshBuffer;if(n<=0){this.authInstance?.currentUser&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{this.authInstance?.currentUser?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},n)}handleRefreshError(e){if(this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let r=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);setTimeout(()=>{this.authInstance?.currentUser?this.forceRefresh(this.authInstance.currentUser).catch(n=>{this.handleRefreshError(n)}):this.refreshCallback&&this.refreshCallback().catch(n=>{this.handleRefreshError(n)})},r)}else this.tokenInfo={...this.tokenInfo,status:"error",error:e instanceof Error?e:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(e instanceof Error?e:new Error("Max token refresh attempts reached"))}handleError(e){this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},vg=Le(Hr,null,{});var xt=class{buildKey(e,r,n,i=!1){let o="dndev";switch(r){case"user":if(!n){if(i)return null;throw v(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:r}})}return`${o}:user:${n}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var de=null;async function Uc(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(t){throw v(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function Lc(t){try{let e=await window.crypto.subtle.exportKey("raw",t);return btoa(String.fromCharCode(...new Uint8Array(e)))}catch(e){throw v(e,{userMessage:"Failed to export encryption key"})}}async function Mc(t){try{let e=Uint8Array.from(atob(t),r=>r.charCodeAt(0));return await window.crypto.subtle.importKey("raw",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(e){throw v(e,{userMessage:"Failed to import encryption key"})}}async function ki(){if(de)return de;try{let t=localStorage.getItem("dndev:encryptionKey");if(t)return de=await Mc(t),de;de=await Uc();let e=await Lc(de);return localStorage.setItem("dndev:encryptionKey",e),de}catch(t){throw v(t,{userMessage:"Failed to get or create encryption key"})}}async function Oi(t){try{let e=await ki(),r=window.crypto.getRandomValues(new Uint8Array(12)),n=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(n),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,o),c=new Uint8Array(r.length+s.byteLength);return c.set(r,0),c.set(new Uint8Array(s),r.length),btoa(String.fromCharCode(...c))}catch(e){throw v(e,{userMessage:"Failed to encrypt data"})}}async function Di(t){try{let e=await ki(),r=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),n=r.slice(0,12),i=r.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i),c=new TextDecoder().decode(o);try{return JSON.parse(c)}catch{return c}}catch(e){throw v(e,{userMessage:"Failed to decrypt data"})}}var re=class extends xt{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,r={}){let{scope:n="user",encryption:i=!1}=r,o=this.buildKey(e,n,this.userId,!0);if(!o)return null;try{if(!M())return null;let s=localStorage.getItem(o);if(!s)return null;let c=JSON.parse(s);if(c.expiresAt&&new Date(c.expiresAt)<new Date)return await this.remove(e),null;let u=c.value;return i&&typeof u=="string"&&(u=await Di(u)),u}catch(s){throw v(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:r}})}}async set(e,r,n={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=n,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=r;o&&(u=await Oi(r));let p=s>0?new Date(Date.now()+s*1e3).toISOString():null,g=JSON.stringify({value:u,expiresAt:p,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,g)}catch(u){let p=u?.name==="QuotaExceededError"||u?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":u?.name==="SecurityError"||u?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw v(u,{userMessage:p,context:{key:e,options:n}})}}async remove(e){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(e,n,this.userId,!0);if(!i)continue;typeof window<"u"&&localStorage.removeItem(i)}catch{}}async clear(e){if(!e){let s=(typeof window<"u"?Object.keys(localStorage):[]).filter(c=>c.startsWith("dndev:"));for(let c of s)typeof window<"u"&&localStorage.removeItem(c);return}let r=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(r));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var tt=class{localStrategy;userId;apiEndpoint;constructor(e,r="/api/storage"){if(!e)throw v("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=r}async get(e,r={}){try{let n=await this.localStrategy.get(e,r);return n!==null?n:await this.getFromCloud(e,r)}catch(n){try{return await this.localStrategy.get(e,r)}catch(i){throw v(n,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:r,fallbackError:i}})}}}async set(e,r,n={}){try{await this.localStrategy.set(e,r,n),this.setToCloud(e,r,n).catch(i=>{})}catch(i){throw v(i,{userMessage:"Failed to store data",context:{key:e,options:n}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(r=>{})}catch(r){throw v(r,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(r=>{})}catch(r){throw v(r,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,r,n,i=!1){let o="dndev";switch(r){case"user":if(!n){if(i)return null;throw v(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:r}})}return`${o}:user:${n}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,r){try{let{scope:n="user"}=r,i=this.buildKey(e,n,this.userId,!0);if(!i)return null;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`);if(!o.ok){if(o.status===404)return null;throw v(new Error(`Cloud storage API error: ${o.status} ${o.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:e,status:o.status}})}let s=await o.json();return s.expiresAt&&new Date(s.expiresAt)<new Date?(this.removeFromCloud(e).catch(console.warn),null):(this.localStrategy.set(e,s.value,r).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,r,n){let{scope:i="user",expiry:o=0}=n,s=this.buildKey(e,i,this.userId,!0);if(!s)return;let c=o>0?new Date(Date.now()+o*1e3).toISOString():null,u={value:r,expiresAt:c,createdAt:new Date().toISOString()},p=await fetch(`${this.apiEndpoint}/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw v(new Error(`Cloud storage API error: ${p.status} ${p.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:e,status:p.status}})}async removeFromCloud(e){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(e,n,this.userId,!0);if(!i)continue;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE"});!o.ok&&o.status}catch{}}async clearFromCloud(e){try{let r=new URLSearchParams;e&&r.append("scope",e),e==="user"&&r.append("userId",this.userId);let n=r.toString(),i=n?`${this.apiEndpoint}/clear?${n}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE"})).ok}catch{}}};var kt=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,r){this.initialize(),r&&e?this.strategy=new tt(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new tt(this.userId):this.strategy=new re(this.userId)}async get(e,r={}){return this.initialize(),this.strategy.get(e,r)}async set(e,r,n={}){return this.initialize(),this.strategy.set(e,r,n)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,r,n={}){return this.initialize(),this.set(e,r,{...n,encryption:!0})}async getSecure(e,r={}){return this.initialize(),this.get(e,{...r,encryption:!0})}},Fc=Le(kt);var H={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function pe(t){return!!t&&t.trim()!==""}var Jg={[H.AUTH]:()=>Rt().length>0,[H.OAUTH]:()=>["VITE_OAUTH_GOOGLE_CLIENT_ID","VITE_OAUTH_GITHUB_CLIENT_ID","VITE_OAUTH_FACEBOOK_CLIENT_ID","VITE_OAUTH_TWITTER_CLIENT_ID","VITE_OAUTH_LINKEDIN_CLIENT_ID","VITE_OAUTH_DISCORD_CLIENT_ID","VITE_OAUTH_SLACK_CLIENT_ID","VITE_OAUTH_MICROSOFT_CLIENT_ID","VITE_OAUTH_APPLE_CLIENT_ID"].some(e=>pe(k(e))),[H.I18N]:()=>!0,[H.BILLING]:()=>!!(pe(k("STRIPE_PUBLISHABLE_KEY"))||pe(k("BILLING_ENABLED"))&&k("BILLING_ENABLED")==="true"),[H.ROUTES]:()=>!0,[H.THEMES]:()=>!0,[H.COMPONENTS]:()=>!0,[H.CRUD]:()=>!0,[H.FORMS]:()=>!0,[H.REALTIME]:()=>!!(pe(k("REALTIME_ENABLED"))&&k("REALTIME_ENABLED")==="true"||pe(k("FIREBASE_CONFIG"))),[H.STORAGE]:()=>!!(pe(k("STORAGE_ENABLED"))&&k("STORAGE_ENABLED")==="true"||pe(k("FIREBASE_CONFIG")))};var tu=Qr(Yr(),1);var ru=Qr(Yr(),1);var Jr=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:r,once:!1,context:n};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,r)}}once(e,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:r,once:!0,context:n};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,r)}}off(e,r){let n=this.events.get(e);if(!n||n.length===0)return!1;let i=n.findIndex(o=>o.handler===r);return i===-1?!1:(n.splice(i,1),n.length===0&&this.events.delete(e),!0)}emit(e,...r){this.cacheEvent(e,r);let n=this.events.get(e);if(!n||n.length===0)return!1;let i=[...n],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,r):s.handler(...r),s.once&&o.push(s)}catch(c){v(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:r},severity:"warning"})}if(o.length>0){let s=this.events.get(e);if(s){let c=s.filter(u=>!o.includes(u));c.length===0?this.events.delete(e):this.events.set(e,c)}}return!0}hasListeners(e){let r=this.events.get(e);return!!r&&r.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let r=this.events.get(e);return r?r.map(n=>n.handler):[]}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}setMaxListeners(e){return this.maxListeners=e>0?e:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(e){let r=this.events.get(e);return r||(r=[],this.events.set(e,r)),r}checkListenerCount(e){let r=this.listenerCount(e);this.maxListeners!==1/0&&r>this.maxListeners}cacheEvent(e,r){let n=this.eventCache.get(e);n||(n=[],this.eventCache.set(e,n)),n.push({data:r,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let r=this.eventCache.get(e);return!r||r.length===0?[]:(this.cleanupCache(e),(this.eventCache.get(e)||[]).map(i=>i.data))}clearCachedEvents(e){this.eventCache.delete(e)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let e=0,r=null,n=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(r===null||c.timestamp<r)&&(r=c.timestamp),(n===null||c.timestamp>n)&&(n=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:r,newestEvent:n,memoryEstimate:i}}cleanupCache(e){let r=Date.now()-this.cacheTTL;if(e){let n=this.eventCache.get(e);if(n){let i=n.filter(o=>o.timestamp>r);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[n,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>r);o.length===0?this.eventCache.delete(n):this.eventCache.set(n,o)}}},Nv=new Jr;var Bv={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},error:null,emailVerification:{status:"pending"},getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:Ne.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:V.GUEST,userTier:De.FREE,can:{navigate:t=>t===!1||typeof t=="object"&&!t.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Hv={status:Ne.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1},$v={status:Ne.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},Wv={status:Ne.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var ji=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function Ki(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function Dt(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>{let i=`${e}[${n}]`;if(typeof r=="string"&&Ki(r)){if(!ji.test(r))throw v({userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&Dt(r,i)});else if(typeof t=="object"&&t!==null)for(let[r,n]of Object.entries(t)){let i=e?`${e}.${r}`:r;if(typeof n=="string"&&Ki(n)){if(!ji.test(n))throw v({userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&Dt(n,i)}}import*as Yi from"valibot";var Xr={};function Sy(t){Xr.uniqueConstraintValidator=t}async function zi(t,e,r){let{uniqueFields:n=[],collection:i}=t.metadata;n.length!==0&&Xr.uniqueConstraintValidator&&await Promise.all(n.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await Xr.uniqueConstraintValidator.checkDuplicate(i,o,c,r))throw v({userMessage:s||`${o} must be unique`,code:"already-exists",context:{field:o}})}))}async function wy(t,e,r,n){Yi.parse(t,e),Dt(e),await zi(t,e,n),t.metadata.customValidate&&await t.metadata.customValidate(e,r)}function nu(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function Ly(t){if(!nu(t)){let e=t,r=e&&typeof e=="object"&&"constructor"in e&&e.constructor&&e.constructor.name||"unknown";throw v(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return t.metadata.collection}function iu(t){let e=t.collection||(t.field.endsWith("Id")?t.field.slice(0,-2)+"ies":t.field+"s");return{name:t.field,label:`crud:fields.${t.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:e}}}function ou(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let r=t.map(i=>({value:i.value,label:i.label})),n=new Set(t.map(i=>i.value));for(let i of e)n.has(i.value)||r.push(i);return r}function su(t,e){if(!(!t.uniqueKeys||t.uniqueKeys.length===0))for(let r=0;r<t.uniqueKeys.length;r++){let n=t.uniqueKeys[r];if(!n)continue;if(!n.fields||n.fields.length===0)throw v(new Error(`uniqueKeys[${r}] for entity '${t.name}' must have at least one field`),{userMessage:`uniqueKeys[${r}] for entity '${t.name}' must have at least one field`,context:{entityName:t.name,uniqueKeyIndex:r},severity:"error"});let i=n.fields.filter(o=>!e.has(o));if(i.length>0)throw v(new Error(`uniqueKeys[${r}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${r}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:t.name,uniqueKeyIndex:r,invalidFields:i},severity:"error"})}}function au(t){let{form:e,fields:r}=t,n=Object.keys(r);if(e){if(e.type==="multi-step"||e.type==="wizard"){if(!e.steps||e.steps.length===0)throw v(new Error(`Multi-step form for entity '${t.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${t.name}' must have at least one step`,context:{entityName:t.name,operation:"validateFormConfig"},severity:"error"});let i=e.steps.flatMap(u=>u.fields),o=i.filter(u=>!n.includes(u));if(o.length>0)throw v(new Error(`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:t.name,invalidFields:o,operation:"validateFormConfig"},severity:"error"});let s=new Set(i);n.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(g=>g.field):[i.condition.field]).filter(g=>!n.includes(g));if(c.length>0)throw v(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let p=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(g=>!n.includes(g));if(p.length>0)throw v(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:p,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([i,o])=>{if(o.dependsOn&&!n.includes(o.dependsOn.field))throw v(new Error(`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`,context:{entityName:t.name,fieldName:i,dependsOnField:o.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function cu(t){return t.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...t.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Hy(t){try{au(t);let e=cu(t),r={...t.fields,...w,...t.fields.createdAt&&{createdAt:{...w.createdAt,...t.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...w.updatedAt,...t.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...w.createdById,...t.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...w.updatedById,...t.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...t.fields.status&&{status:{...w.status,...t.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:ou(nr,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:iu(t.scope)}};if(t.listFields){let o=new Set(Object.keys(r)),s=t.listFields.filter(c=>!o.has(c));if(s.length>0)throw v(new Error(`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let o=new Set(Object.keys(r)),s=t.listCardFields.filter(c=>!o.has(c));if(s.length>0)throw v(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let o=new Set(Object.keys(r));su(t,o)}let n={...$t,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:r,access:n,namespace:i}}catch(e){throw v(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}function Wy(t,e,r=1,n=!1){let i=[];if(n)for(let o=e;o>=t;o-=r)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=r)i.push({value:String(o),label:String(o)});return i}var fe=new Map;function Gy(t,e){fe.has(t),fe.set(t,e)}function jy(t){fe.delete(t)}function Ky(t){let e=fe.get(t);return e?e():null}function zy(t){return fe.has(t)}function Yy(){return Array.from(fe.keys())}function Jy(){fe.clear()}export{Al as AUTH_EVENTS,me as AUTH_PARTNERS,zu as AUTH_PARTNER_STATE,ln as AuthUserSchema,ve as BACKEND_GENERATED_FIELD_NAMES,Pl as BILLING_EVENTS,Ao as BREAKPOINT_RANGES,qt as BREAKPOINT_THRESHOLDS,rn as COMMON_TIER_CONFIGS,U as CONFIDENCE_LEVELS,mn as CONSENT_CATEGORY,D as CONTEXTS,Ut as CURRENCY_MAP,un as CheckoutSessionMetadataSchema,nn as CreateCheckoutSessionRequestSchema,on as CreateCheckoutSessionResponseSchema,dn as CustomClaimsSchema,$t as DEFAULT_ENTITY_ACCESS,oe as DEFAULT_ERROR_MESSAGES,Jl as DEFAULT_LAYOUT_PRESET,nr as DEFAULT_STATUS_OPTIONS,yf as DEFAULT_STATUS_VALUE,Su as DEFAULT_SUBSCRIPTION,Rd as DENSITY,x as DoNotDevError,ie as ENVIRONMENTS,pn as EntityHookError,Vt as FEATURES,xd as FEATURE_CONSENT_MATRIX,Ne as FEATURE_STATUS,Wt as FIREBASE_ERROR_MAP,it as FIRESTORE_ID_PATTERN,fn as GITHUB_PERMISSION_LEVELS,Ef as HIDDEN_STATUSES,Xl as LAYOUT_PRESET,xl as OAUTH_EVENTS,jt as OAUTH_PARTNERS,Ed as PARTNER_ICONS,Ol as PAYLOAD_EVENTS,Bt as PERMISSIONS,A as PLATFORMS,il as PWA_ASSET_TYPES,nl as PWA_DISPLAY_MODES,So as ProductDeclarationSchema,Ou as ProductDeclarationsSchema,ol as ROUTE_SOURCES,rl as STORAGE_SCOPES,tl as STORAGE_TYPES,Nl as STRIPE_EVENTS,nt as STRIPE_MODES,Iu as SUBSCRIPTION_DURATIONS,he as SUBSCRIPTION_STATUS,De as SUBSCRIPTION_TIERS,Sn as ServerUtils,Zt as SingletonManager,Co as StripeBackConfigSchema,_o as StripeFrontConfigSchema,Io as StripePaymentSchema,To as StripeSubscriptionSchema,an as SubscriptionClaimsSchema,sn as SubscriptionDataSchema,ws as TECHNICAL_FIELD_NAMES,V as USER_ROLES,Ht as UserSubscriptionSchema,cn as WebhookEventSchema,Me as addMonths,er as addYears,vs as addressSchema,Es as arraySchema,w as baseFields,_n as booleanSchema,os as calculateSubscriptionEndDate,Jt as captureErrorToSentry,ud as checkGitHubAccessSchema,mf as clearSchemaGenerators,Jy as clearScopeProviders,Ue as commonErrorCodeMappings,Lt as compactToISOString,Qo as createAsyncSingleton,Tu as createDefaultSubscriptionClaims,Yu as createDefaultUserProfile,pl as createEntitySchema,$ as createErrorHandler,ao as createMetadata,es as createMethodProxy,Ps as createSchemas,Le as createSingleton,Zo as createSingletonWithParams,ge as dateSchema,Hy as defineEntity,ml as deleteEntitySchema,Kt as detectErrorSource,pd as disconnectOAuthSchema,ds as emailSchema,xf as enhanceSchema,ld as exchangeTokenSchema,Cn as fileSchema,An as filesSchema,is as filterVisibleFields,uo as formatCurrency,tn as formatDate,vo as formatRelativeTime,_s as gdprConsentSchema,En as generateCodeChallenge,yn as generateCodeVerifier,Go as generatePKCEPair,gs as geopointSchema,wo as getBreakpointFromWidth,zl as getBreakpointUtils,Ly as getCollectionName,fd as getConnectionsSchema,en as getCurrencyLocale,co as getCurrencySymbol,fo as getCurrentTimestamp,fl as getEntitySchema,hf as getRegisteredSchemaTypes,Yy as getRegisteredScopeProviders,Be as getSchemaType,Ky as getScopeValue,Qt as getVisibleFields,go as getWeekFromISOString,Po as githubPermissionSchema,Gt as githubRepoConfigSchema,ad as grantGitHubAccessSchema,v as handleError,ff as hasCustomSchemaGenerator,nu as hasMetadata,st as hasRoleAccess,zy as hasScopeProvider,Xo as hasTierAccess,Lo as isAuthPartnerId,If as isBackendGeneratedField,Kl as isBreakpoint,Mt as isCompactDateString,Tn as isFieldVisible,bf as isFrameworkField,Mo as isOAuthPartnerId,jo as isPKCESupported,lo as isoToCompactString,Jo as lazyImport,gl as listEntitiesSchema,ys as mapSchema,Yt as mapToDoNotDevError,qo as maybeTranslate,bs as multiselectSchema,wn as neverSchema,po as normalizeToISOString,Fe as numberSchema,gu as overrideFeatures,bu as overridePaymentModes,vu as overridePermissions,Eu as overrideSubscriptionStatus,mu as overrideSubscriptionTiers,hu as overrideUserRoles,Ft as parseDate,Eo as parseDateToNoonUTC,ss as parseISODate,ls as parseServerCookie,ps as passwordSchema,hs as pictureSchema,ms as picturesSchema,Cs as priceSchema,Wy as rangeOptions,Is as referenceSchema,dd as refreshTokenSchema,E as registerSchemaGenerator,Gy as registerScopeProvider,Sy as registerUniqueConstraintValidator,cd as revokeGitHubAccessSchema,tr as selectSchema,Wo as showNotification,rr as stringSchema,Ss as switchSchema,Ts as telSchema,at as textSchema,mo as timestampToISOString,bo as toDateOnly,ho as toISOString,no as translateArray,oo as translateArrayRange,so as translateArrayWithIndices,io as translateObjectArray,jy as unregisterScopeProvider,hl as updateEntitySchema,ts as updateMetadata,fs as urlSchema,Id as validateAuthPartners,ju as validateAuthSchemas,Wu as validateAuthUser,Uu as validateBillingSchemas,ku as validateCheckoutSessionMetadata,zo as validateCodeChallenge,Ko as validateCodeVerifier,Au as validateCreateCheckoutSessionRequest,wu as validateCreateCheckoutSessionResponse,Gu as validateCustomClaims,Dt as validateDates,wy as validateDocument,us as validateEnvVar,cs as validateMetadata,Td as validateOAuthPartners,Nu as validateStripeBackConfig,Du as validateStripeFrontConfig,Ru as validateSubscriptionClaims,Pu as validateSubscriptionData,zi as validateUniqueFields,as as validateUrl,qu as validateUserSubscription,xu as validateWebhookEvent,$o as withErrorHandling,Yo as withGracefulDegradation};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
react/cjs/react.production.js:
|