@donotdev/core 0.0.36 → 0.0.38
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.js +7 -7
- package/index.d.ts +36 -5
- package/index.js +41 -39
- package/next/index.js +12 -12
- package/package.json +2 -2
- package/server.d.ts +10 -0
- package/server.js +1 -1
- package/vite/index.js +20 -20
package/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var lo=Object.create;var Kt=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var fo=Object.getOwnPropertyNames;var ho=Object.getPrototypeOf,mo=Object.prototype.hasOwnProperty;var pr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),go=(t,e)=>{for(var n in e)Kt(t,n,{get:e[n],enumerable:!0})},vo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fo(e))!mo.call(t,i)&&i!==n&&Kt(t,i,{get:()=>e[i],enumerable:!(r=po(e,i))||r.enumerable});return t};var fr=(t,e,n)=>(n=t!=null?lo(ho(t)):{},vo(e||!t||!t.__esModule?Kt(n,"default",{value:t,enumerable:!0}):n,t));var no=pr(b=>{"use strict";var rr=Symbol.for("react.transitional.element"),Su=Symbol.for("react.portal"),Au=Symbol.for("react.fragment"),Cu=Symbol.for("react.strict_mode"),wu=Symbol.for("react.profiler"),_u=Symbol.for("react.consumer"),Ru=Symbol.for("react.context"),Pu=Symbol.for("react.forward_ref"),xu=Symbol.for("react.suspense"),ku=Symbol.for("react.memo"),Ji=Symbol.for("react.lazy"),Ou=Symbol.for("react.activity"),ji=Symbol.iterator;function Du(t){return t===null||typeof t!="object"?null:(t=ji&&t[ji]||t["@@iterator"],typeof t=="function"?t:null)}var Xi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Qi=Object.assign,Zi={};function Me(t,e,n){this.props=t,this.context=e,this.refs=Zi,this.updater=n||Xi}Me.prototype.isReactComponent={};Me.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")};Me.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function eo(){}eo.prototype=Me.prototype;function ir(t,e,n){this.props=t,this.context=e,this.refs=Zi,this.updater=n||Xi}var or=ir.prototype=new eo;or.constructor=ir;Qi(or,Me.prototype);or.isPureReactComponent=!0;var Ki=Array.isArray;function nr(){}var w={H:null,A:null,T:null,S:null},to=Object.prototype.hasOwnProperty;function sr(t,e,n){var r=n.ref;return{$$typeof:rr,type:t,key:e,ref:r!==void 0?r:null,props:n}}function Nu(t,e){return sr(t.type,e,t.props)}function ar(t){return typeof t=="object"&&t!==null&&t.$$typeof===rr}function Lu(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var zi=/\/+/g;function tr(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Lu(""+t.key):e.toString(36)}function Uu(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(nr,nr):(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 Ue(t,e,n,r,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 rr:case Su:s=!0;break;case Ji:return s=t._init,Ue(s(t._payload),e,n,r,i)}}if(s)return i=i(t),s=r===""?"."+tr(t,0):r,Ki(i)?(n="",s!=null&&(n=s.replace(zi,"$&/")+"/"),Ue(i,e,n,"",function(p){return p})):i!=null&&(ar(i)&&(i=Nu(i,n+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(zi,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=r===""?".":r+":";if(Ki(t))for(var u=0;u<t.length;u++)r=t[u],o=c+tr(r,u),s+=Ue(r,e,n,o,i);else if(u=Du(t),typeof u=="function")for(t=u.call(t),u=0;!(r=t.next()).done;)r=r.value,o=c+tr(r,u++),s+=Ue(r,e,n,o,i);else if(o==="object"){if(typeof t.then=="function")return Ue(Uu(t),e,n,r,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 Gt(t,e,n){if(t==null)return t;var r=[],i=0;return Ue(t,r,"","",function(o){return e.call(n,o,i++)}),r}function Mu(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Yi=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}},Fu={map:Gt,forEach:function(t,e,n){Gt(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Gt(t,function(){e++}),e},toArray:function(t){return Gt(t,function(e){return e})||[]},only:function(t){if(!ar(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};b.Activity=Ou;b.Children=Fu;b.Component=Me;b.Fragment=Au;b.Profiler=wu;b.PureComponent=ir;b.StrictMode=Cu;b.Suspense=xu;b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w;b.__COMPILER_RUNTIME={__proto__:null,c:function(t){return w.H.useMemoCache(t)}};b.cache=function(t){return function(){return t.apply(null,arguments)}};b.cacheSignal=function(){return null};b.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var r=Qi({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!to.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(r[o]=e[o]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];r.children=s}return sr(t.type,i,r)};b.createContext=function(t){return t={$$typeof:Ru,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:_u,_context:t},t};b.createElement=function(t,e,n){var r,i={},o=null;if(e!=null)for(r in e.key!==void 0&&(o=""+e.key),e)to.call(e,r)&&r!=="key"&&r!=="__self"&&r!=="__source"&&(i[r]=e[r]);var s=arguments.length-2;if(s===1)i.children=n;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(r in s=t.defaultProps,s)i[r]===void 0&&(i[r]=s[r]);return sr(t,o,i)};b.createRef=function(){return{current:null}};b.forwardRef=function(t){return{$$typeof:Pu,render:t}};b.isValidElement=ar;b.lazy=function(t){return{$$typeof:Ji,_payload:{_status:-1,_result:t},_init:Mu}};b.memo=function(t,e){return{$$typeof:ku,type:t,compare:e===void 0?null:e}};b.startTransition=function(t){var e=w.T,n={};w.T=n;try{var r=t(),i=w.S;i!==null&&i(n,r),typeof r=="object"&&r!==null&&typeof r.then=="function"&&r.then(nr,Yi)}catch(o){Yi(o)}finally{e!==null&&n.types!==null&&(e.types=n.types),w.T=e}};b.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()};b.use=function(t){return w.H.use(t)};b.useActionState=function(t,e,n){return w.H.useActionState(t,e,n)};b.useCallback=function(t,e){return w.H.useCallback(t,e)};b.useContext=function(t){return w.H.useContext(t)};b.useDebugValue=function(){};b.useDeferredValue=function(t,e){return w.H.useDeferredValue(t,e)};b.useEffect=function(t,e){return w.H.useEffect(t,e)};b.useEffectEvent=function(t){return w.H.useEffectEvent(t)};b.useId=function(){return w.H.useId()};b.useImperativeHandle=function(t,e,n){return w.H.useImperativeHandle(t,e,n)};b.useInsertionEffect=function(t,e){return w.H.useInsertionEffect(t,e)};b.useLayoutEffect=function(t,e){return w.H.useLayoutEffect(t,e)};b.useMemo=function(t,e){return w.H.useMemo(t,e)};b.useOptimistic=function(t,e){return w.H.useOptimistic(t,e)};b.useReducer=function(t,e,n){return w.H.useReducer(t,e,n)};b.useRef=function(t){return w.H.useRef(t)};b.useState=function(t){return w.H.useState(t)};b.useSyncExternalStore=function(t,e,n){return w.H.useSyncExternalStore(t,e,n)};b.useTransition=function(){return w.H.useTransition()};b.version="19.2.4"});var cr=pr((yy,ro)=>{"use strict";ro.exports=no()});var Ur={};go(Ur,{AuthHardening:()=>Et,CURRENCY_MAP:()=>an,ConditionBuilder:()=>Ie,DEFAULT_ERROR_MESSAGES:()=>ae,DoNotDevError:()=>_,SingletonManager:()=>pn,addMonths:()=>Ke,addYears:()=>hn,calculateSubscriptionEndDate:()=>$s,captureErrorToSentry:()=>on,commonErrorCodeMappings:()=>qe,compactToISOString:()=>cn,configureProviders:()=>Ss,createAsyncSingleton:()=>Rs,createErrorHandler:()=>$,createMetadata:()=>Qo,createMethodProxy:()=>Ps,createSingleton:()=>Ge,createSingletonWithParams:()=>_s,detectErrorSource:()=>nn,ensureSpreadable:()=>jo,evaluateCondition:()=>ue,evaluateFieldConditions:()=>Vs,filterVisibleFields:()=>Ns,formatCurrency:()=>es,formatDate:()=>xr,formatRelativeTime:()=>as,generateCodeChallenge:()=>Or,generateCodeVerifier:()=>kr,generateFirestoreRuleCondition:()=>fs,generatePKCEPair:()=>ms,getConditionDependencies:()=>Hs,getCurrencyLocale:()=>Pr,getCurrencySymbol:()=>Zo,getCurrentTimestamp:()=>rs,getListCardFieldNames:()=>je,getProvider:()=>As,getRoleFromClaims:()=>Is,getVisibleFields:()=>fn,getWeekFromISOString:()=>ss,handleError:()=>v,hasProvider:()=>Cs,hasRestrictedVisibility:()=>Ls,hasRoleAccess:()=>vt,hasTierAccess:()=>Ts,isCompactDateString:()=>un,isFieldVisible:()=>Lr,isPKCESupported:()=>gs,isoToCompactString:()=>ts,lazyImport:()=>bs,mapToDoNotDevError:()=>ce,maybeTranslate:()=>hs,normalizeToISOString:()=>ns,parseDate:()=>ln,parseDateToNoonUTC:()=>us,parseISODate:()=>qs,parseServerCookie:()=>Ks,resetProviders:()=>ws,safeValidate:()=>Go,showNotification:()=>Bo,timestampToISOString:()=>os,toDateOnly:()=>ls,toISOString:()=>is,translateArray:()=>zo,translateArrayRange:()=>Jo,translateArrayWithIndices:()=>Xo,translateObjectArray:()=>Yo,updateMetadata:()=>xs,validateCodeChallenge:()=>ys,validateCodeVerifier:()=>vs,validateEnvVar:()=>js,validateMetadata:()=>Gs,validateUrl:()=>Ws,validateWithSchema:()=>Wo,when:()=>Bs,withErrorHandling:()=>Vo,withGracefulDegradation:()=>Es,wrapAuthError:()=>qo,wrapCrudError:()=>Ho,wrapStorageError:()=>$o});var O={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function Xu(t){Object.assign(O,t)}var Be={FREE:"free",PRO:"pro",PREMIUM:"premium"};function Qu(t){Object.assign(Be,t)}var zt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Zu(t){Object.assign(zt,t)}var Yt={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 el(t){Object.assign(Yt,t)}import*as l from"valibot";var ye={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function nl(t){Object.assign(ye,t)}var ht={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function rl(t){Object.assign(ht,t)}var il={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function ol(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var hr={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}},sl={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var mr=a.object({userId:a.optional(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([ht.PAYMENT,ht.SUBSCRIPTION]))}),gr=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),vr=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(ye)),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())}),yr=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(ye)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),Er=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),br=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function ul(t){return a.safeParse(mr,t)}function ll(t){return a.safeParse(gr,t)}function dl(t){return a.safeParse(vr,t)}function pl(t){return a.safeParse(yr,t)}function fl(t){return a.safeParse(Er,t)}function hl(t){return a.safeParse(br,t)}var yo=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()))}),Eo=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()))}),bo=a.variant("type",[yo,Eo]),ml=a.record(a.string(),bo),Io=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())})),To=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 gl(t){return a.parse(Io,t)}function vl(t){return a.parse(To,t)}function yl(){let t={createCheckoutSessionRequest:a.safeParse(mr,{}),createCheckoutSessionResponse:a.safeParse(gr,{}),subscriptionData:a.safeParse(vr,{}),subscriptionClaims:a.safeParse(yr,{}),webhookEvent:a.safeParse(Er,{}),checkoutSessionMetadata:a.safeParse(br,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var Ir=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(O))),customClaims:l.optional(l.record(l.string(),l.any()))}),Jt=l.object({userId:l.string(),tier:l.picklist(Object.values(Be)),status:l.picklist(Object.values(ye)),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())}),Tr=l.object({role:l.optional(l.picklist(Object.values(O))),subscription:l.optional(Jt),features:l.optional(l.array(l.picklist(Object.values(zt)))),permissions:l.optional(l.array(l.picklist(Object.values(Yt)))),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 wl(t){return l.safeParse(Ir,t)}function _l(t){return l.safeParse(Jt,t)}function Rl(t){return l.safeParse(Tr,t)}function Pl(){let t={authUser:l.safeParse(Ir,{}),userSubscription:l.safeParse(Jt,{}),customClaims:l.safeParse(Tr,{}),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 kl={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},Ol={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Dl(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var S={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},oe={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},x={CLIENT:"client",SERVER:"server",BUILD:"build"},N={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},He={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Bl={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},Hl={USER:"user",GLOBAL:"global",SESSION:"session"},$l={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},ql={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Wl={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var jl={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},Kl={TRUE:!0,FALSE:!1,ADMIN:"admin",CREATE_ONLY:"create-only"},Xt={create:"admin",read:"guest",update:"admin",delete:"admin"},se={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},zl={ASC:"asc",DESC:"desc"},Yl={LIST:"list",LIST_CARD:"listCard"},Jl=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Zl={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},ed={EQ:se.EQ,NEQ:se.NEQ,LT:se.LT,LTE:se.LTE,GT:se.GT,GTE:se.GTE};import*as h from"valibot";var sd=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())}),ad=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"))}),cd=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)}),ud=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"))}),ld=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)),1e3),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.unknown()})))});var $e={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},bd={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},mt={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Qt={[$e.PERMISSION_DENIED]:{type:mt.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[$e.NOT_FOUND]:{type:mt.NOT_FOUND,message:"The requested resource was not found"},[$e.ALREADY_EXISTS]:{type:mt.ALREADY_EXISTS,message:"The resource already exists"},[$e.INVALID_ARGUMENT]:{type:mt.VALIDATION_ERROR,message:"Invalid argument provided"}},Sr=class extends Error{type;originalError;constructor(e,n,r){super(n),this.name="EntityHookError",this.type=e,this.originalError=r}},Id={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},_=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,n=$e.INTERNAL,r){super(e),Object.setPrototypeOf(this,t.prototype),this.code=n,this.details=r?.details,this.source=r?.source,this.originalError=r?.originalError,this.context=r?.context,this.displayable=r?.displayable??!0,this.userMessageProvided=r?.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 Cd={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 _d={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 Pd={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 kd={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 Dd={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 Zt={mobile:0,tablet:768,laptop:1024,desktop:1440},So={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function Ao(t){return t>=Zt.desktop?"desktop":t>=Zt.laptop?"laptop":t>=Zt.tablet?"tablet":"mobile"}function jd(t,e){let n=So[e];return t>=n.min&&t<=n.max}function Kd(t,e){let n=Ao(t);return{current:n,width:t,height:e,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var Yd="landing",Jd={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Ar=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var en=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"))}),Co=f.picklist([...Ar]),sp=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:en,permission:f.optional(Co,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),ap=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:en}),cp=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:en}),up=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()))}),lp=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"))}),dp=f.object({provider:f.string()}),pp=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var yp={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 g from"valibot";var Cr=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),wo=g.object({...Cr.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),gt=g.union([g.literal(""),g.pipe(g.string(),g.url())]),_o=g.object({authUrl:gt,tokenUrl:gt,profileUrl:gt,revokeUrl:g.optional(gt)}),Ro=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),Po=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),xo=g.object({...Cr.entries,type:g.picklist(["oauth","both"]),scopes:Ro,endpoints:_o,capabilities:Po}),Ee={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"}}},tn={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"}}},ko=g.record(g.string(),wo),Oo=g.record(g.string(),xo);function bp(){return g.safeParse(ko,Ee)}function Ip(){return g.safeParse(Oo,tn)}function Do(t){return t in Ee}function No(t){return t in tn}var wr={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},kp={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Op={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:wr.ANALYTICS},marketing:{requiresConsent:wr.MARKETING}};function nn(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 Rr from"valibot";function $(t){return(e,n)=>{if(e instanceof _)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new _(n||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let r;t.extractErrorCode?r=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(r=e.code);let i=t.defaultErrorCode;r&&t.errorCodeMapping&&r in t.errorCodeMapping&&(i=t.errorCodeMapping[r]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),r&&t.friendlyMessageMapping&&r in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[r]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},r&&(s.originalCode=r)),"originalError"in s||(s.originalError=e),new _(n||o,i,{details:s,source:t.errorSource})}}var qe={"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 ae={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",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."},Lo={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"},rn={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},ee={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",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...qe},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",...qe},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(Lo).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:qe,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ae.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:ae["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ae.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},Uo=t=>t instanceof Rr.ValiError?new _(ae["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(ee.validation)(t),Mo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in rn){let e=t,n=rn[e.type]||"unknown";return new _(e.message||ae[n],n,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Qt[t.code]){let e=t,n=Qt[e.code];if(n){let r=rn[n.type]||"unknown";return new _(n.message||ae[r],r,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(ee.entity)(t)},_r={auth:$(ee.auth),oauth:$(ee.oauth),api:$(ee.api),firebase:$(ee.firebase),ui:$(ee.ui),validation:Uo,entity:Mo,unknown:$(ee.unknown)};function ce(t,e,n){return t instanceof _?t:(_r[e]||_r.unknown)(t,n)}function on(t,e,n={}){let r=globalThis.Sentry;r&&r.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(n).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||n.userId)&&i.setUser({id:t.details?.userId||n.userId,email:t.details?.userEmail||n.userEmail}),r.captureException(t)})}function Fo(){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 n=typeof e=="string"?{userMessage:e}:e||{},{userMessage:r,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=n,p=nn(t),m=t instanceof _?t:ce(t,p,r);if(r&&!m.userMessageProvided&&(m.message.includes("Error")||m.message.includes("Failed")||m.message.length<10?m=new _(r,m.code,{details:{...m.details,originalMessage:m.message},source:p,userMessageProvided:!0}):m=new _(m.message,m.code,{details:{...m.details,userMessage:r},source:p,userMessageProvided:!0})),o){let T=Fo()||typeof window<"u"&&window.__DNDEV_DEBUG,k={code:m.code,message:m.message,source:p};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&on(m,p,i),m}function Vo(t,e){return async(...n)=>{try{return await t(...n)}catch(r){throw v(r,e)}}}function Bo(t,e="info",n){let r=Date.now().toString();return r}function Ho(t,e,n,r,i){let o=`${e}.${n}(${r}${i?`, ${i}`:""})`;return ce(t,"api",`${o}: ${sn(t)}`)}function $o(t,e,n,r){let i=`${e}.${n}(${r})`;return ce(t,"api",`${i}: ${sn(t)}`)}function qo(t,e,n,r){let i=r?` ${JSON.stringify(r)}`:"",o=`${e}.${n}(${i})`,s=ce(t,"auth",`${o}: ${sn(t)}`);return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&s.code==="unknown"&&t.code!=="unknown"?new _(s.message,s.code,{details:{...s.details,originalCode:t.code},source:s.source}):s}function sn(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}import*as We from"valibot";function Wo(t,e,n){try{return We.parse(t,e)}catch(r){throw r instanceof We.ValiError?new _(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:e},source:"validation"}):new _(`Unexpected validation error in ${n}: ${Ko(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function Go(t,e){try{return We.parse(t,e)}catch{return null}}function jo(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{value:t}}function Ko(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}function zo(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(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 Yo(t,e,n,r){return Array.from({length:n},(i,o)=>{let s=`${e}.${o}.${String(r[0])}`;if(t(s)===s)return null;let u={};for(let p of r){let m=`${e}.${o}.${String(p)}`;u[p]=t(m)}return u}).filter(i=>i!==null)}function Jo(t,e,n,r,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:r-n},(u,p)=>{let m=n+p,T=`${e}.${m}`;return t(T)}).filter((u,p)=>{let m=n+p,T=`${e}.${m}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,m))})}function Xo(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(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 Qo(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}var an={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 Pr(t){return an[t]?.locale??"en-US"}function Zo(t){return!t||typeof t!="string"?t??"":an[t]?.symbol??t}function es(t,e,n={}){if(t==null||isNaN(t))return"";let r=Pr(e);return new Intl.NumberFormat(r,{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:0,currencyDisplay:"symbol",...n}).format(t)}function cn(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 n=e[1],r=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(n,10),parseInt(r,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 ts(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=e.getUTCFullYear(),r=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`${n}${r}${i}:${o}${s}`}function un(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function ns(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(un(t))return cn(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 rs(){return new Date().toISOString()}function is(t){return t.toISOString()}function os(t){return new Date(t).toISOString()}function ss(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=new Date(e.getFullYear(),0,1),r=Math.floor((e.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${e.getFullYear()}`}var U={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function as(t,e="en",n={}){if(!t)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:o=U.WEEK}=n,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),m=Math.abs(p);if(m>o)return xr(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:r,numeric:i});return m<U.MINUTE?T.format(p,"second"):m<U.HOUR?T.format(Math.round(p/U.MINUTE),"minute"):m<U.DAY?T.format(Math.round(p/U.HOUR),"hour"):m<U.WEEK?T.format(Math.round(p/U.DAY),"day"):m<U.MONTH?T.format(Math.round(p/U.WEEK),"week"):m<U.YEAR?T.format(Math.round(p/U.MONTH),"month"):T.format(Math.round(p/U.YEAR),"year")}function cs(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 xr(t,e="en",n="long"){if(!t)return"";let r;if(t instanceof Date)r=t;else if(typeof t=="string")r=new Date(t);else if(typeof t=="number")r=new Date(t);else if(typeof t=="object"&&"toDate"in t)r=t.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?cs(n):n;return new Intl.DateTimeFormat(e,i).format(r)}function ln(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(un(e))try{return cn(e)}catch{return}let n=new Date(e);return isNaN(n.getTime())?void 0:n.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 n=e.toDate();return isNaN(n.getTime())?void 0:n.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,n=e.seconds*1e3+(e.nanoseconds||0)/1e6,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function us(t){let e=ln(t);if(!e)return;let n=new Date(e);return n.setUTCHours(12,0,0,0),n.toISOString()}function ls(t){let e=ln(t);return e&&e.split("T")[0]||""}function ds(t){return typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:typeof t=="boolean"?t?"true":"false":String(t)}function ps(t){let e=`resource.data.${t.field}`,n=ds(t.value);return`${e} ${t.op} ${n}`}function fs(t){let e=[];if(t.publicCondition&&t.publicCondition.length>0){let n=t.publicCondition.map(ps).join(" && ");e.push(`(${n})`)}for(let n of t.ownerFields)e.push(`request.auth.uid == resource.data.${n}`);return e.length===0?"false":e.join(" || ")}function hs(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function kr(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Dr(t)}async function Or(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Dr(new Uint8Array(r))}async function ms(){let t=kr(),e=await Or(t);return{codeVerifier:t,codeChallenge:e}}function Dr(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gs(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function vs(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function ys(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function Es(t,e,n){try{return await t()}catch{return e(),!1}}var dn=new Map;function bs(t,e){if(dn.has(e))return dn.get(e);let n=t();return dn.set(e,n),n}var Nr={[O.GUEST]:0,[O.USER]:1,[O.ADMIN]:2,[O.SUPER]:3};function vt(t,e){if(!t)return!1;let n=Nr[t]??-1,r=Nr[e]??1/0;return n>=r}function Is(t){return t?t.role===O.SUPER||t.isSuper===!0?O.SUPER:t.role===O.ADMIN||t.isAdmin===!0?O.ADMIN:t.role===O.USER?O.USER:t.role||O.USER:O.USER}function Ts(t,e,n){if(!t)return!1;let r=n??hr,i=r[t]?.level??-1,o=r[e]?.level??1/0;return i>=o}var be=null;function Ss(t){be=t}function As(t){if(!be)throw new Error(`[dndev] Provider "${t}" not available. Call configureProviders() at app startup.`);let e=be[t];if(!e)throw new Error(`[dndev] Provider "${t}" not configured. Pass it to configureProviders().`);return e}function Cs(t){return!!be?.[t]}function ws(){be=null}function Ge(t,...e){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?n=new t(...e):n=t(),n}finally{r=!1}}}function _s(t){let e=null,n=!1;return function(...i){if(e!==null)return e;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{n=!1}}}function Rs(t){let e=null,n=!1,r=null;return async function(){if(e!==null)return e;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=t(),e=await r,e}finally{n=!1,r=null}}}function Ps(t,e){return new Proxy({},{get(n,r){if(e.includes(r)){let o=t(),s=o[r];return typeof s=="function"?s.bind(o):s}return t()[r]}})}var pn=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,n,r={}){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(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",r.fallbackFactory){let i=r.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 n();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(typeof process<"u",r.cacheFailures&&this.initialized.add(e),r.fallbackFactory){let o=r.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 xs(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}function ks(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function Os(t){if(ks(t))return t.visibility}function Lr(t,e){let n=t??"guest";return n==="hidden"?!1:n==="technical"?vt(e,"admin"):n==="owner"?!1:vt(e,n)}function Ds(t,e,n){for(let r of n.ownerFields)if(t[r]===e)return!0;return!1}function fn(t,e,n){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let i=r.entries,o=[],{documentData:s,uid:c,ownership:u}=n??{},p=u&&c!=null&&s&&Ds(s,c,u);for(let[m,T]of Object.entries(i)){let k=Os(T);if(k==="owner"){p&&o.push(m);continue}Lr(k,e)&&o.push(m)}return o}function Ns(t,e,n,r){if(!t)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??t,uid:r.uid,ownership:r.ownership}:void 0,o=fn(e,n,i),s={};for(let c of o)Object.prototype.hasOwnProperty.call(t,c)&&(s[c]=t[c]);return s}function je(t){let e=t.listCardFields;if(e){if(Array.isArray(e))return e;let n=e,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return t.listFields&&t.listFields.length>0?t.listFields:t.fields?Object.keys(t.fields):[]}function yt(t){if(!(!t||typeof t!="object")){if(t.entries&&typeof t.entries=="object")return t.entries;if(Array.isArray(t.pipe))for(let e of t.pipe){let n=yt(e);if(n)return n}if(t.wrapped)return yt(t.wrapped);if(Array.isArray(t.options))for(let e of t.options){let n=yt(e);if(n)return n}}}function Ls(t){let e=yt(t);if(!e)return!1;for(let n of Object.values(e)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}var Et=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(e={}){this.maxAttempts=e.maxAttempts??5,this.lockoutMs=e.lockoutMs??900*1e3,this.sessionTimeoutMs=e.sessionTimeoutMs??480*60*1e3}checkLockout(e){let n=this.store.get(e);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(e)}}recordFailure(e){let n=Date.now();!this.store.has(e)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(e)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(e,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(e){for(let[n,r]of this.store)r.lockedUntil!==null&&e>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&e-r.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(e){this.store.delete(e)}isSessionExpired(e){return Date.now()-e>this.sessionTimeoutMs}getEntry(e){return this.store.get(e)}};function Us(t,e){if(e.includes(".")){let n=e.split("."),r=t;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}return r}return t[e]}function Ms(t,e){let n=Us(e,t.field);switch(t.operator){case"equals":return n===t.value;case"notEquals":return n!==t.value;case"in":return Array.isArray(t.value)&&t.value.includes(n);case"notIn":return Array.isArray(t.value)&&!t.value.includes(n);case"greaterThan":return typeof n=="number"&&typeof t.value=="number"&&n>t.value;case"lessThan":return typeof n=="number"&&typeof t.value=="number"&&n<t.value;case"greaterThanOrEqual":return typeof n=="number"&&typeof t.value=="number"&&n>=t.value;case"lessThanOrEqual":return typeof n=="number"&&typeof t.value=="number"&&n<=t.value;case"exists":return n!=null&&n!==""&&n!==!1;case"notExists":return n==null||n===""||n===!1;case"contains":return typeof n=="string"&&typeof t.value=="string"||Array.isArray(n)?n.includes(t.value):!1;default:return!1}}function Fs(t){return t instanceof Ie||"expression"in t?t.expression:t}function ue(t,e){let n=Fs(t);if(n.type==="condition")return Ms(n,e);let{logic:r,conditions:i}=n;return r==="and"?i.every(o=>ue(o,e)):i.some(o=>ue(o,e))}function Vs(t,e){return t?{visible:t.visible?ue(t.visible,e):!0,disabled:t.disabled?ue(t.disabled,e):!1,required:t.required?ue(t.required,e):!1,readonly:t.readonly?ue(t.readonly,e):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var Ie=class t{expression;constructor(e){this.expression=e}get type(){return this.expression.type}or(e){let n=e instanceof t?e.expression:e,r=this.expression;return r.type==="group"&&r.logic==="or"?new t({type:"group",logic:"or",conditions:[...r.conditions,n]}):new t({type:"group",logic:"or",conditions:[r,n]})}and(e){let n=e instanceof t?e.expression:e,r=this.expression;return r.type==="group"&&r.logic==="and"?new t({type:"group",logic:"and",conditions:[...r.conditions,n]}):new t({type:"group",logic:"and",conditions:[r,n]})}};function Bs(t){function e(n,r){return new Ie({type:"condition",field:t,operator:n,value:r})}return{equals:n=>e("equals",n),notEquals:n=>e("notEquals",n),in:n=>e("in",n),notIn:n=>e("notIn",n),greaterThan:n=>e("greaterThan",n),lessThan:n=>e("lessThan",n),greaterThanOrEqual:n=>e("greaterThanOrEqual",n),lessThanOrEqual:n=>e("lessThanOrEqual",n),exists:()=>e("exists"),notExists:()=>e("notExists"),contains:n=>e("contains",n)}}function Hs(t){let e=t instanceof Ie?t.expression:t,n=new Set;function r(i){if(i.type==="condition")n.add(i.field);else for(let o of i.conditions)r(o)}return r(e),n}function Ke(t,e){let n=new Date(t),r=n.getDate();return n.setMonth(n.getMonth()+e),n.getDate()!==r&&n.setDate(0),n}function hn(t,e){let n=new Date(t),r=n.getDate();return n.setFullYear(n.getFullYear()+e),n.getDate()!==r&&n.setDate(0),n}function $s(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return t==="1month"?n=Ke(e,1):t==="3months"?n=Ke(e,3):t==="6months"?n=Ke(e,6):t==="1year"?n=hn(e,1):t==="2years"?n=hn(e,2):n=Ke(e,1),n.toISOString()}function qs(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function Ws(t,e="URL"){try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol))throw new Error(`Invalid protocol: ${n.protocol}`);return t}catch(n){throw new Error(`Invalid ${e}: ${t}. ${n instanceof Error?n.message:"Invalid URL format"}`)}}function Gs(t){let e={};for(let[n,r]of Object.entries(t)){if(typeof r!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof r}`);let i=r.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 '${n}' is too long (max 1000 characters)`);if(n.length>100)throw new Error(`Metadata key '${n}' is too long (max 100 characters)`);e[n]=i}return e}function js(t,e=!0){let n=process.env[t];if(e&&!n)throw new Error(`Required environment variable '${t}' is not set`);return n||""}function Ks(t,e){if(!t)return null;let n=`${encodeURIComponent(e)}=`,r=t.split(";");for(let i=0;i<r.length;i++){let o=r[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(n)===0)return decodeURIComponent(o.substring(n.length,o.length))}}return null}function Vh(t,e){let n=t;return n.metadata=e,n}import*as d from"valibot";var ze=new Map;function y(t,e){ze.set(t,e)}function Hh(t){return ze.has(t)}function $h(){return Array.from(ze.keys())}function qh(){ze.clear()}function A(t,e){return e?t:d.nullish(t)}var bt=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 n=e.length>0?d.pipe(d.string(),...e):d.string();return A(n,t.validation?.required)},zs=t=>{let e=d.pipe(d.string(),d.email("Invalid email address"));return A(e,t.validation?.required)},Ys=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 A(e,t.validation?.required)},Js=t=>{let e=d.pipe(d.string(),d.url("Invalid URL"));return A(e,t.validation?.required)},Te=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 n=e.length>0?d.pipe(d.number(),...e):d.number();return A(n,t.validation?.required)},Mr=t=>{let e=d.boolean();return A(e,t.validation?.required)},Se=t=>{let e=d.pipe(d.string(),d.isoTimestamp("Invalid date format"));return A(e,t.validation?.required)},Hr=d.object({url:d.string(),filename:d.string(),size:d.number(),mimeType:d.nullish(d.string()),uploadedAt:d.nullish(d.string())}),Fr=t=>{let e=d.nullable(Hr);return A(e,t.validation?.required)},Vr=t=>{let e=d.array(Hr);return A(e,t.validation?.required)},$r=d.object({fullUrl:d.string(),thumbUrl:d.string()}),Xs=t=>A($r,t.validation?.required),Qs=t=>{let e=d.array($r);return A(e,t.validation?.required)},Zs=t=>{let e=d.object({lat:d.number(),lng:d.number()});return A(e,t.validation?.required)},ea=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 A(e,t.validation?.required)},ta=t=>{let e=d.record(d.string(),d.unknown());return A(e,t.validation?.required)},na=t=>{let e=d.array(d.unknown());return A(e,t.validation?.required)},mn=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.picklist(r);return A(i,t.validation?.required)}let n=d.union([d.string(),d.number()]);return A(n,t.validation?.required)},ra=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.array(d.picklist(r));return A(i,t.validation?.required)}let n=d.array(d.string());return A(n,t.validation?.required)},ia=t=>{let e=d.pipe(d.string(),d.minLength(1,"Invalid ID format"));return A(e,t.validation?.required)},gn=t=>{let e=d.string();return A(e,t.validation?.required)},oa=t=>{let e=d.string();return A(e,t.validation?.required)},sa=t=>{let e=t.validation?.minLength??15,n=t.validation?.maxLength??34,r=t.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(e!==void 0&&i.push(d.minLength(e,`IBAN must be at least ${e} characters`)),n!==void 0&&i.push(d.maxLength(n,`IBAN must not exceed ${n} characters`)),r){let s=typeof r=="string"?new RegExp(r):r;i.push(d.regex(s,"Invalid IBAN format"))}let o=i.length>0?d.pipe(d.string(),...i):d.string();return A(o,t.validation?.required)},Br=()=>d.never(),aa=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let r=[e.checkedValue,e.uncheckedValue],i=d.picklist(r);return A(i,t.validation?.required)}let n=d.boolean();return A(n,t.validation?.required)},ca=t=>d.custom(n=>t.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),ua=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 A(e,t.validation?.required)};function la(){y("text",bt),y("textarea",bt),y("richtext",bt),y("color",bt),y("email",zs),y("password",Ys),y("url",Js),y("tel",oa),y("iban",sa),y("number",Te),y("currency",Te),y("price",ua),y("range",Te),y("year",Te),y("rating",Te),y("duration",Te),y("boolean",Mr),y("checkbox",Mr),y("gdprConsent",ca),y("date",Se),y("datetime-local",Se),y("time",Se),y("week",Se),y("month",Se),y("timestamp",Se),y("file",Fr),y("files",Vr),y("document",Fr),y("documents",Vr),y("image",Xs),y("images",Qs),y("geopoint",Zs),y("address",ea),y("map",ta),y("array",na),y("select",mn),y("multiselect",ra),y("radio",mn),y("combobox",mn),y("switch",aa),y("reference",ia),y("hidden",gn),y("avatar",gn),y("badge",gn),y("submit",Br),y("reset",Br)}la();function Ye(t){if(t.validation?.schema){let r=t.validation.schema;return A(r,t.validation?.required)}let e=ze.get(t.type);if(e){let r=e(t);if(r!==null)return r}let n=d.unknown();return A(n,t.validation?.required)}var da={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var qr=function(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},pa=function(t){let e=[],n=0,r=0;for(;n<t.length;){let i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[n++];e[r++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[n++],s=t[n++],c=t[n++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[r++]=String.fromCharCode(55296+(u>>10)),e[r++]=String.fromCharCode(56320+(u&1023))}else{let o=t[n++],s=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},Wr={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 n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];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,m=o>>2,T=(o&3)<<4|c>>4,k=(c&15)<<2|p>>6,H=p&63;u||(H=64,s||(k=64)),r.push(n[m],n[T],n[k],n[H])}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(qr(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):pa(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<t.length;){let o=n[t.charAt(i++)],c=i<t.length?n[t.charAt(i)]:0;++i;let p=i<t.length?n[t.charAt(i)]:64;++i;let T=i<t.length?n[t.charAt(i)]:64;if(++i,o==null||c==null||p==null||T==null)throw new yn;let k=o<<2|c>>4;if(r.push(k),p!==64){let H=c<<4&240|p>>2;if(r.push(H),T!==64){let ie=p<<6&192|T;r.push(ie)}}}return r},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)}}},yn=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},fa=function(t){let e=qr(t);return Wr.encodeByteArray(e,!0)},bn=function(t){return fa(t).replace(/\./g,"")},In=function(t){try{return Wr.decodeString(t,!0)}catch{}return null};function Tn(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function V(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Gr(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(V())}function jr(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Kr(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function zr(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Yr(){try{return typeof indexedDB=="object"}catch{return!1}}function Jr(){return new Promise((t,e)=>{try{let n=!0,r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{e(i.error?.message||"")}}catch(n){e(n)}})}var ha="FirebaseError",q=class t extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=ha,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,J.prototype.create)}},J=class{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r}create(e,...n){let r=n[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?ma(o,r):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new q(i,c,r)}};function ma(t,e){return t.replace(ga,(n,r)=>{let i=e[r];return i!=null?String(i):`<${r}?>`})}var ga=/\{\$([^}]+)}/g;function It(t){let e=[];for(let[n,r]of Object.entries(t))Array.isArray(r)?r.forEach(i=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return e.length?"&"+e.join("&"):""}function Ae(t){let e={};return t.replace(/^\?/,"").split("&").forEach(r=>{if(r){let[i,o]=r.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function Ce(t){let e=t.indexOf("?");if(!e)return"";let n=t.indexOf("#",e);return t.substring(e,n>0?n:void 0)}function Xr(t,e){let n=new En(t,e);return n.subscribe.bind(n)}var En=class{constructor(e,n){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=n,this.task.then(()=>{e(this)}).catch(r=>{this.error(r)})}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(e===void 0&&n===void 0&&r===void 0)throw new Error("Missing Observer.");va(e,["next","error","complete"])?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=vn),i.error===void 0&&(i.error=vn),i.complete===void 0&&(i.complete=vn);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 n=0;n<this.observers.length;n++)this.sendOne(n,e)}sendOne(e,n){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{n(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 va(t,e){if(typeof t!="object"||t===null)return!1;for(let n of e)if(n in t&&typeof t[n]=="function")return!0;return!1}function vn(){}var zh=14400*1e3;function Je(t){return t&&t._delegate?t._delegate:t}da.NODE_CLIENT=!0;var X=class{constructor(e,n,r){this.name=e,this.instanceFactory=n,this.type=r,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 ya=[],C;(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"})(C||(C={}));var Ea={debug:C.DEBUG,verbose:C.VERBOSE,info:C.INFO,warn:C.WARN,error:C.ERROR,silent:C.SILENT},ba=C.INFO,Ia={[C.DEBUG]:"log",[C.VERBOSE]:"log",[C.INFO]:"info",[C.WARN]:"warn",[C.ERROR]:"error"},Ta=(t,e,...n)=>{if(e<t.logLevel)return;let r=new Date().toISOString(),i=Ia[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},we=class{constructor(e){this.name=e,this._logLevel=ba,this._logHandler=Ta,this._userLogHandler=null,ya.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in C))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?Ea[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,C.DEBUG,...e),this._logHandler(this,C.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,C.VERBOSE,...e),this._logHandler(this,C.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,C.INFO,...e),this._logHandler(this,C.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,C.WARN,...e),this._logHandler(this,C.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,C.ERROR,...e),this._logHandler(this,C.ERROR,...e)}};var Sa=(t,e)=>e.some(n=>t instanceof n),Qr,Zr;function Aa(){return Qr||(Qr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ca(){return Zr||(Zr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var ei=new WeakMap,An=new WeakMap,ti=new WeakMap,Sn=new WeakMap,wn=new WeakMap;function wa(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{n(W(t.result)),i()},s=()=>{r(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(n=>{n instanceof IDBCursor&&ei.set(n,t)}).catch(()=>{}),wn.set(e,t),e}function _a(t){if(An.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{n(),i()},s=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});An.set(t,e)}var Cn={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return An.get(t);if(e==="objectStoreNames")return t.objectStoreNames||ti.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return W(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function ni(t){Cn=t(Cn)}function Ra(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(Tt(this),e,...n);return ti.set(r,e.sort?e.sort():[e]),W(r)}:Ca().includes(t)?function(...e){return t.apply(Tt(this),e),W(ei.get(this))}:function(...e){return W(t.apply(Tt(this),e))}}function Pa(t){return typeof t=="function"?Ra(t):(t instanceof IDBTransaction&&_a(t),Sa(t,Aa())?new Proxy(t,Cn):t)}function W(t){if(t instanceof IDBRequest)return wa(t);if(Sn.has(t))return Sn.get(t);let e=Pa(t);return e!==t&&(Sn.set(t,e),wn.set(e,t)),e}var Tt=t=>wn.get(t);function ii(t,e,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=W(s);return r&&s.addEventListener("upgradeneeded",u=>{r(W(s.result),u.oldVersion,u.newVersion,W(s.transaction),u)}),n&&s.addEventListener("blocked",u=>n(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 xa=["get","getKey","getAll","getAllKeys","count"],ka=["put","add","delete","clear"],_n=new Map;function ri(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(_n.get(e))return _n.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=ka.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||xa.includes(n)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),p=u.store;return r&&(p=p.index(c.shift())),(await Promise.all([p[n](...c),i&&u.done]))[0]};return _n.set(e,o),o}ni(t=>({...t,get:(e,n,r)=>ri(e,n)||t.get(e,n,r),has:(e,n)=>!!ri(e,n)||t.has(e,n)}));var Pn=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(Da(n)){let r=n.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}};function Da(t){return t.getComponent()?.type==="VERSION"}var xn="@firebase/app",oi="0.14.9";var Q=new we("@firebase/app"),Na="@firebase/app-compat",La="@firebase/analytics-compat",Ua="@firebase/analytics",Ma="@firebase/app-check-compat",Fa="@firebase/app-check",Va="@firebase/auth",Ba="@firebase/auth-compat",Ha="@firebase/database",$a="@firebase/data-connect",qa="@firebase/database-compat",Wa="@firebase/functions",Ga="@firebase/functions-compat",ja="@firebase/installations",Ka="@firebase/installations-compat",za="@firebase/messaging",Ya="@firebase/messaging-compat",Ja="@firebase/performance",Xa="@firebase/performance-compat",Qa="@firebase/remote-config",Za="@firebase/remote-config-compat",ec="@firebase/storage",tc="@firebase/storage-compat",nc="@firebase/firestore",rc="@firebase/ai",ic="@firebase/firestore-compat",oc="firebase",sc="12.10.0";var ac={[xn]:"fire-core",[Na]:"fire-core-compat",[Ua]:"fire-analytics",[La]:"fire-analytics-compat",[Fa]:"fire-app-check",[Ma]:"fire-app-check-compat",[Va]:"fire-auth",[Ba]:"fire-auth-compat",[Ha]:"fire-rtdb",[$a]:"fire-data-connect",[qa]:"fire-rtdb-compat",[Wa]:"fire-fn",[Ga]:"fire-fn-compat",[ja]:"fire-iid",[Ka]:"fire-iid-compat",[za]:"fire-fcm",[Ya]:"fire-fcm-compat",[Ja]:"fire-perf",[Xa]:"fire-perf-compat",[Qa]:"fire-rc",[Za]:"fire-rc-compat",[ec]:"fire-gcs",[tc]:"fire-gcs-compat",[nc]:"fire-fst",[ic]:"fire-fst-compat",[rc]:"fire-vertex","fire-js":"fire-js",[oc]:"fire-js-all"};var cc=new Map,uc=new Map,si=new Map;function ai(t,e){try{t.container.addComponent(e)}catch(n){Q.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function Re(t){let e=t.name;if(si.has(e))return Q.debug(`There were multiple attempts to register component ${e}.`),!1;si.set(e,t);for(let n of cc.values())ai(n,t);for(let n of uc.values())ai(n,t);return!0}function le(t){return t==null?!1:t.settings!==void 0}var lc={"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."},Dn=new J("app","Firebase",lc);var St=sc;function _e(t,e,n){let r=ac[t]??t;n&&(r+=`-${n}`);let i=r.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${r}" with version "${e}":`];i&&s.push(`library name "${r}" 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}Re(new X(`${r}-version`,()=>({library:r,version:e}),"VERSION"))}var dc="firebase-heartbeat-database",pc=1,Xe="firebase-heartbeat-store",Rn=null;function di(){return Rn||(Rn=ii(dc,pc,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(Xe)}catch{}}}}).catch(t=>{throw Dn.create("idb-open",{originalErrorMessage:t.message})})),Rn}async function fc(t){try{let n=(await di()).transaction(Xe),r=await n.objectStore(Xe).get(pi(t));return await n.done,r}catch(e){if(e instanceof q)Q.warn(e.message);else{let n=Dn.create("idb-get",{originalErrorMessage:e?.message});Q.warn(n.message)}}}async function ci(t,e){try{let r=(await di()).transaction(Xe,"readwrite");await r.objectStore(Xe).put(e,pi(t)),await r.done}catch(n){if(n instanceof q)Q.warn(n.message);else{let r=Dn.create("idb-set",{originalErrorMessage:n?.message});Q.warn(r.message)}}}function pi(t){return`${t.name}!${t.options.appId}`}var hc=1024,mc=30,kn=class{constructor(e){this.container=e,this._heartbeatsCache=null;let n=this.container.getProvider("app").getImmediate();this._storage=new On(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=ui();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(i=>i.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats.length>mc){let i=vc(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=ui(),{heartbeatsToSend:n,unsentEntries:r}=gc(this._heartbeatsCache.heartbeats),i=bn(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Q.warn(e),""}}};function ui(){return new Date().toISOString().substring(0,10)}function gc(t,e=hc){let n=[],r=t.slice();for(let i of t){let o=n.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),li(n)>e){o.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),li(n)>e){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}var On=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Yr()?Jr().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let n=await fc(this.app);return n?.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ci(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ci(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}};function li(t){return bn(JSON.stringify({version:2,heartbeats:t})).length}function vc(t){if(t.length===0)return-1;let e=0,n=t[0].date;for(let r=1;r<t.length;r++)t[r].date<n&&(n=t[r].date,e=r);return e}function yc(t){Re(new X("platform-logger",e=>new Pn(e),"PRIVATE")),Re(new X("heartbeat",e=>new kn(e),"PRIVATE")),_e(xn,oi,t),_e(xn,oi,"esm2020"),_e("fire-js","")}yc("");function Ii(){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 Ti=Ii,Si=new J("auth","Firebase",Ii());var Rt=new we("@firebase/auth");function Ec(t,...e){Rt.logLevel<=C.WARN&&Rt.warn(`Auth (${St}): ${t}`,...e)}function wt(t,...e){Rt.logLevel<=C.ERROR&&Rt.error(`Auth (${St}): ${t}`,...e)}function Pe(t,...e){throw Qn(t,...e)}function Xn(t,...e){return Qn(t,...e)}function Ai(t,e,n){let r={...Ti(),[e]:n};return new J("auth","Firebase",r).create(e,{appName:t.name})}function _t(t){return Ai(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Qn(t,...e){if(typeof t!="string"){let n=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=t.name),t._errorFactory.create(n,...r)}return Si.create(t,...e)}function I(t,e,...n){if(!t)throw Qn(e,...n)}function G(t){let e="INTERNAL ASSERTION FAILED: "+t;throw wt(e),new Error(e)}function Pt(t,e){t||G(e)}function bc(){return fi()==="http:"||fi()==="https:"}function fi(){return typeof self<"u"&&self.location?.protocol||null}function Ic(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(bc()||Kr()||"connection"in navigator)?navigator.onLine:!0}function Tc(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var Mn=class{constructor(e,n){this.shortDelay=e,this.longDelay=n,Pt(n>e,"Short delay should be less than long delay!"),this.isMobile=Gr()||zr()}get(){return Ic()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function Sc(t,e){Pt(t.emulator,"Emulator should always be set here");let{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}var tt=class{static initialize(e,n,r){this.fetchImpl=e,n&&(this.headersImpl=n),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;G("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;G("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;G("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var Ac={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 Cc=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],wc=new Mn(3e4,6e4);function j(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function K(t,e,n,r,i={}){return Ci(t,i,async()=>{let o={},s={};r&&(e==="GET"?s=r:o={body:JSON.stringify(r)});let c=It({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 jr()||(p.referrerPolicy="no-referrer"),t.emulatorConfig&&Tn(t.emulatorConfig.host)&&(p.credentials="include"),tt.fetch()(await wi(t,t.config.apiHost,n,c),p)})}async function Ci(t,e,n){t._canInitEmulator=!1;let r={...Ac,...e};try{let i=new Fn(t),o=await Promise.race([n(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw At(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 At(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw At(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw At(t,"user-disabled",s);let m=r[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(p)throw Ai(t,m,p);Pe(t,m)}}catch(i){if(i instanceof q)throw i;Pe(t,"network-request-failed",{message:String(i)})}}async function Bt(t,e,n,r,i={}){let o=await K(t,e,n,r,i);return"mfaPendingCredential"in o&&Pe(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function wi(t,e,n,r){let i=`${e}${n}?${r}`,o=t,s=o.config.emulator?Sc(t.config,i):`${t.config.apiScheme}://${i}`;return Cc.includes(n)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function _c(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var Fn=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((n,r)=>{this.timer=setTimeout(()=>r(Xn(this.auth,"network-request-failed")),wc.get())})}};function At(t,e,n){let r={appName:t.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);let i=Xn(t,e,r);return i.customData._tokenResponse=n,i}function hi(t){return t!==void 0&&t.enterprise!==void 0}var Vn=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 n of this.recaptchaEnforcementState)if(n.provider&&n.provider===e)return _c(n.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 Rc(t,e){return K(t,"GET","/v2/recaptchaConfig",j(t,e))}async function Pc(t,e){return K(t,"POST","/v1/accounts:delete",e)}async function xt(t,e){return K(t,"POST","/v1/accounts:lookup",e)}function Ze(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function _i(t,e=!1){let n=Je(t),r=await n.getIdToken(e),i=Ri(r);I(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:r,authTime:Ze(Nn(i.auth_time)),issuedAtTime:Ze(Nn(i.iat)),expirationTime:Ze(Nn(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function Nn(t){return Number(t)*1e3}function Ri(t){let[e,n,r]=t.split(".");if(e===void 0||n===void 0||r===void 0)return wt("JWT malformed, contained fewer than 3 sections"),null;try{let i=In(n);return i?JSON.parse(i):(wt("Failed to decode base64 JWT payload"),null)}catch(i){return wt("Caught error parsing JWT payload as JSON",i?.toString()),null}}function mi(t){let e=Ri(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 Bn(t,e,n=!1){if(n)return e;try{return await e}catch(r){throw r instanceof q&&xc(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function xc({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var Hn=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 n=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),n}else{this.errorBackoff=3e4;let r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;let n=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},n)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var nt=class{constructor(e,n){this.createdAt=e,this.lastLoginAt=n,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ze(this.lastLoginAt),this.creationTime=Ze(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function kt(t){let e=t.auth,n=await t.getIdToken(),r=await Bn(t,xt(e,{idToken:n}));I(r?.users.length,e,"internal-error");let i=r.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?xi(i.providerUserInfo):[],s=kc(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,p=c?u:!1,m={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 nt(i.createdAt,i.lastLoginAt),isAnonymous:p};Object.assign(t,m)}async function Pi(t){let e=Je(t);await kt(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function kc(t,e){return[...t.filter(r=>!e.some(i=>i.providerId===r.providerId)),...e]}function xi(t){return t.map(({providerId:e,...n})=>({providerId:e,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}))}async function Oc(t,e){let n=await Ci(t,{},async()=>{let r=It({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await wi(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:r};return t.emulatorConfig&&Tn(t.emulatorConfig.host)&&(u.credentials="include"),tt.fetch()(s,u)});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function Dc(t,e){return K(t,"POST","/v2/accounts:revokeToken",j(t,e))}var et=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 n="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):mi(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}updateFromIdToken(e){I(e.length!==0,"internal-error");let n=mi(e);this.updateTokensAndExpiration(e,null,n)}async getToken(e,n=!1){return!n&&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,n){let{accessToken:r,refreshToken:i,expiresIn:o}=await Oc(e,n);this.updateTokensAndExpiration(r,i,Number(o))}updateTokensAndExpiration(e,n,r){this.refreshToken=n||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,n){let{refreshToken:r,accessToken:i,expirationTime:o}=n,s=new t;return r&&(I(typeof r=="string","internal-error",{appName:e}),s.refreshToken=r),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 G("not implemented")}};function te(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var de=class t{constructor({uid:e,auth:n,stsTokenManager:r,...i}){this.providerId="firebase",this.proactiveRefresh=new Hn(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=n,this.stsTokenManager=r,this.accessToken=r.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 nt(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let n=await Bn(this,this.stsTokenManager.getToken(this.auth,e));return I(n,this.auth,"internal-error"),this.accessToken!==n&&(this.accessToken=n,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),n}getIdTokenResult(e){return _i(this,e)}reload(){return Pi(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(n=>({...n})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let n=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return n.metadata._copy(this.metadata),n}_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,n=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),n&&await kt(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(le(this.auth.app))return Promise.reject(_t(this.auth));let e=await this.getIdToken();return await Bn(this,Pc(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,n){let r=n.displayName??void 0,i=n.email??void 0,o=n.phoneNumber??void 0,s=n.photoURL??void 0,c=n.tenantId??void 0,u=n._redirectEventId??void 0,p=n.createdAt??void 0,m=n.lastLoginAt??void 0,{uid:T,emailVerified:k,isAnonymous:H,providerData:ie,stsTokenManager:ft}=n;I(T&&ft,e,"internal-error");let D=et.fromJSON(this.name,ft);I(typeof T=="string",e,"internal-error"),te(r,e.name),te(i,e.name),I(typeof k=="boolean",e,"internal-error"),I(typeof H=="boolean",e,"internal-error"),te(o,e.name),te(s,e.name),te(c,e.name),te(u,e.name),te(p,e.name),te(m,e.name);let P=new t({uid:T,auth:e,email:i,emailVerified:k,displayName:r,isAnonymous:H,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:D,createdAt:p,lastLoginAt:m});return ie&&Array.isArray(ie)&&(P.providerData=ie.map(Y=>({...Y}))),u&&(P._redirectEventId=u),P}static async _fromIdTokenResponse(e,n,r=!1){let i=new et;i.updateFromServerResponse(n);let o=new t({uid:n.localId,auth:e,stsTokenManager:i,isAnonymous:r});return await kt(o),o}static async _fromGetAccountInfoResponse(e,n,r){let i=n.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?xi(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new et;c.updateFromIdToken(r);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 nt(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,p),u}};var gi=new Map;function pe(t){Pt(t instanceof Function,"Expected a class definition");let e=gi.get(t);return e?(Pt(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,gi.set(t,e),e)}var Ot=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,n){this.storage[e]=n}async _get(e){let n=this.storage[e];return n===void 0?null:n}async _remove(e){delete this.storage[e]}_addListener(e,n){}_removeListener(e,n){}};Ot.type="NONE";var $n=Ot;function Ln(t,e,n){return`firebase:${t}:${e}:${n}`}var Dt=class t{constructor(e,n,r){this.persistence=e,this.auth=n,this.userKey=r;let{config:i,name:o}=this.auth;this.fullUserKey=Ln(this.userKey,i.apiKey,o),this.fullPersistenceKey=Ln("persistence",i.apiKey,o),this.boundEventHandler=n._onStorageEvent.bind(n),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 n=await xt(this.auth,{idToken:e}).catch(()=>{});return n?de._fromGetAccountInfoResponse(this.auth,n,e):null}return de._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 n=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,n)return this.setCurrentUser(n)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,n,r="authUser"){if(!n.length)return new t(pe($n),e,r);let i=(await Promise.all(n.map(async p=>{if(await p._isAvailable())return p}))).filter(p=>p),o=i[0]||pe($n),s=Ln(r,e.config.apiKey,e.name),c=null;for(let p of n)try{let m=await p._get(s);if(m){let T;if(typeof m=="string"){let k=await xt(e,{idToken:m}).catch(()=>{});if(!k)break;T=await de._fromGetAccountInfoResponse(e,k,m)}else T=de._fromJSON(e,m);p!==o&&(c=T),o=p;break}}catch{}let u=i.filter(p=>p._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,r):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(n.map(async p=>{if(p!==o)try{await p._remove(s)}catch{}})),new t(o,e,r))}};function vi(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(Mc(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Nc(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(Vc(e))return"Blackberry";if(Bc(e))return"Webos";if(Lc(e))return"Safari";if((e.includes("chrome/")||Uc(e))&&!e.includes("edge/"))return"Chrome";if(Fc(e))return"Android";{let n=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=t.match(n);if(r?.length===2)return r[1]}return"Other"}function Nc(t=V()){return/firefox\//i.test(t)}function Lc(t=V()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Uc(t=V()){return/crios\//i.test(t)}function Mc(t=V()){return/iemobile/i.test(t)}function Fc(t=V()){return/android/i.test(t)}function Vc(t=V()){return/blackberry/i.test(t)}function Bc(t=V()){return/webos/i.test(t)}function ki(t,e=[]){let n;switch(t){case"Browser":n=vi(V());break;case"Worker":n=`${vi(V())}-${t}`;break;default:n=t}let r=e.length?e.join(","):"FirebaseCore-web";return`${n}/JsCore/${St}/${r}`}var qn=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,n){let r=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});r.onAbort=n,this.queue.push(r);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let n=[];try{for(let r of this.queue)await r(e),r.onAbort&&n.push(r.onAbort)}catch(r){n.reverse();for(let i of n)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}};async function Hc(t,e={}){return K(t,"GET","/v2/passwordPolicy",j(t,e))}var $c=6,Wn=class{constructor(e){let n=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=n.minPasswordLength??$c,n.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=n.maxPasswordLength),n.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=n.containsLowercaseCharacter),n.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=n.containsUppercaseCharacter),n.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=n.containsNumericCharacter),n.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=n.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 n={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,n),this.validatePasswordCharacterOptions(e,n),n.isValid&&(n.isValid=n.meetsMinPasswordLength??!0),n.isValid&&(n.isValid=n.meetsMaxPasswordLength??!0),n.isValid&&(n.isValid=n.containsLowercaseLetter??!0),n.isValid&&(n.isValid=n.containsUppercaseLetter??!0),n.isValid&&(n.isValid=n.containsNumericCharacter??!0),n.isValid&&(n.isValid=n.containsNonAlphanumericCharacter??!0),n}validatePasswordLengthOptions(e,n){let r=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;r&&(n.meetsMinPasswordLength=e.length>=r),i&&(n.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,n){this.updatePasswordCharacterOptionsStatuses(n,!1,!1,!1,!1);let r;for(let i=0;i<e.length;i++)r=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(n,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,n,r,i,o){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=n)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=o))}};var Nt=class{constructor(e,n,r,i){this.app=e,this.heartbeatServiceProvider=n,this.appCheckServiceProvider=r,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Lt(this),this.idTokenSubscription=new Lt(this),this.beforeStateQueue=new qn(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=Si,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,n){return n&&(this._popupRedirectResolver=pe(n)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Dt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(n),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 n=await xt(this,{idToken:e}),r=await de._fromGetAccountInfoResponse(this,n,e);await this.directlySetCurrentUser(r)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(le(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let n=await this.assertedPersistence.getCurrentUser(),r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(r=c.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(o){r=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return I(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let n=null;try{n=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return n}async reloadAndSetCurrentUserOrClear(e){try{await kt(e)}catch(n){if(n?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=Tc()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(le(this.app))return Promise.reject(_t(this));let n=e?Je(e):null;return n&&I(n.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(n&&n._clone(this))}async _updateCurrentUser(e,n=!1){if(!this._deleted)return e&&I(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),n||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return le(this.app)?Promise.reject(_t(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return le(this.app)?Promise.reject(_t(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(pe(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let n=this._getPasswordPolicyInternal();return n.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):n.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=await Hc(this),n=new Wn(e);this.tenantId===null?this._projectPasswordPolicy=n:this._tenantPasswordPolicies[this.tenantId]=n}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new J("auth","Firebase",e())}onAuthStateChanged(e,n,r){return this.registerStateListener(this.authStateSubscription,e,n,r)}beforeAuthStateChanged(e,n){return this.beforeStateQueue.pushCallback(e,n)}onIdTokenChanged(e,n,r){return this.registerStateListener(this.idTokenSubscription,e,n,r)}authStateReady(){return new Promise((e,n)=>{if(this.currentUser)e();else{let r=this.onAuthStateChanged(()=>{r(),e()},n)}})}async revokeAccessToken(e){if(this.currentUser){let n=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:n};this.tenantId!=null&&(r.tenantId=this.tenantId),await Dc(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,n){let r=await this.getOrInitRedirectPersistenceManager(n);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let n=e&&pe(e)||this._popupRedirectResolver;I(n,this,"argument-error"),this.redirectPersistenceManager=await Dt.create(this,[pe(n._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,n,r,i){if(this._deleted)return()=>{};let o=typeof n=="function"?n:n.next.bind(n),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof n=="function"){let u=e.addObserver(n,r,i);return()=>{s=!0,u()}}else{let u=e.addObserver(n);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=ki(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 n=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();n&&(e["X-Firebase-Client"]=n);let r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(le(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&Ec(`Error while retrieving App Check token: ${e.error}`),e?.token}};function Oi(t){return Je(t)}var Lt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Xr(n=>this.observer=n)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var Di={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function qc(t){return Di.loadJS(t)}function Wc(){return Di.recaptchaEnterpriseScript}var Gn=class{constructor(){this.enterprise=new jn}ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},jn=class{ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},Gc="recaptcha-enterprise",Ni="NO_RECAPTCHA",Kn=class{constructor(e){this.type=Gc,this.auth=Oi(e)}async verify(e="verify",n=!1){async function r(o){if(!n){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)=>{Rc(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 Vn(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;hi(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(p=>{s(p)}).catch(()=>{s(Ni)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new Gn().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{r(this.auth).then(c=>{if(!n&&hi(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=Wc();u.length!==0&&(u+=c),qc(u).then(()=>{i(c,o,s)}).catch(p=>{s(p)})}}).catch(c=>{s(c)})})}};async function Qe(t,e,n,r=!1,i=!1){let o=new Kn(t),s;if(i)s=Ni;else try{s=await o.verify(n)}catch{s=await o.verify(n,!0)}let c={...e};if(n==="mfaSmsEnrollment"||n==="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 r?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 yi(t,e,n,r,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await Qe(t,e,n,n==="getOobCode");return r(t,o)}else return r(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await Qe(t,e,n,n==="getOobCode");return r(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await Qe(t,e,n);return r(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,n,!1,!0);return r(t,c)}return Promise.reject(s)})}else{let o=await Qe(t,e,n,!1,!0);return r(t,o)}else return Promise.reject(i+" provider is not supported.")}function jc(t,e){let n=e?.persistence||[],r=(Array.isArray(n)?n:[n]).map(pe);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,e?.popupRedirectResolver)}var rt=class{constructor(e,n){this.providerId=e,this.signInMethod=n}toJSON(){return G("not implemented")}_getIdTokenResponse(e){return G("not implemented")}_linkToIdToken(e,n){return G("not implemented")}_getReauthenticationResolver(e){return G("not implemented")}};async function Kc(t,e){return K(t,"POST","/v1/accounts:signUp",e)}async function zc(t,e){return Bt(t,"POST","/v1/accounts:signInWithPassword",j(t,e))}async function Yc(t,e){return Bt(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}async function Jc(t,e){return Bt(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}var it=class t extends rt{constructor(e,n,r,i=null){super("password",r),this._email=e,this._password=n,this._tenantId=i}static _fromEmailAndPassword(e,n){return new t(e,n,"password")}static _fromEmailAndCode(e,n,r=null){return new t(e,n,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e;if(n?.email&&n?.password){if(n.signInMethod==="password")return this._fromEmailAndPassword(n.email,n.password);if(n.signInMethod==="emailLink")return this._fromEmailAndCode(n.email,n.password,n.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let n={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return yi(e,n,"signInWithPassword",zc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return Yc(e,{email:this._email,oobCode:this._password});default:Pe(e,"internal-error")}}async _linkToIdToken(e,n){switch(this.signInMethod){case"password":let r={idToken:n,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return yi(e,r,"signUpPassword",Kc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return Jc(e,{idToken:n,email:this._email,oobCode:this._password});default:Pe(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Un(t,e){return Bt(t,"POST","/v1/accounts:signInWithIdp",j(t,e))}var Xc="http://localhost",fe=class t extends rt{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let n=new t(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(n.idToken=e.idToken),e.accessToken&&(n.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(n.nonce=e.nonce),e.pendingToken&&(n.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(n.accessToken=e.oauthToken,n.secret=e.oauthTokenSecret):Pe("argument-error"),n}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:i,...o}=n;if(!r||!i)return null;let s=new t(r,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 n=this.buildRequest();return Un(e,n)}_linkToIdToken(e,n){let r=this.buildRequest();return r.idToken=n,Un(e,r)}_getReauthenticationResolver(e){let n=this.buildRequest();return n.autoCreate=!1,Un(e,n)}buildRequest(){let e={requestUri:Xc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let n={};this.idToken&&(n.id_token=this.idToken),this.accessToken&&(n.access_token=this.accessToken),this.secret&&(n.oauth_token_secret=this.secret),n.providerId=this.providerId,this.nonce&&!this.pendingToken&&(n.nonce=this.nonce),e.postBody=It(n)}return e}};function Qc(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 Zc(t){let e=Ae(Ce(t)).link,n=e?Ae(Ce(e)).deep_link_id:null,r=Ae(Ce(t)).deep_link_id;return(r?Ae(Ce(r)).link:null)||r||n||e||t}var Ut=class t{constructor(e){let n=Ae(Ce(e)),r=n.apiKey??null,i=n.oobCode??null,o=Qc(n.mode??null);I(r&&i&&o,"argument-error"),this.apiKey=r,this.operation=o,this.code=i,this.continueUrl=n.continueUrl??null,this.languageCode=n.lang??null,this.tenantId=n.tenantId??null}static parseLink(e){let n=Zc(e);try{return new t(n)}catch{return null}}};var xe=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,n){return it._fromEmailAndPassword(e,n)}static credentialWithLink(e,n){let r=Ut.parseLink(n);return I(r,"argument-error"),it._fromEmailAndCode(e,r.code,r.tenantId)}};xe.PROVIDER_ID="password";xe.EMAIL_PASSWORD_SIGN_IN_METHOD="password";xe.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var zn=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 ke=class extends zn{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var Oe=class t extends ke{constructor(){super("facebook.com")}static credential(e){return fe._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}}};Oe.FACEBOOK_SIGN_IN_METHOD="facebook.com";Oe.PROVIDER_ID="facebook.com";var De=class t extends ke{constructor(){super("google.com"),this.addScope("profile")}static credential(e,n){return fe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:n})}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:n,oauthAccessToken:r}=e;if(!n&&!r)return null;try{return t.credential(n,r)}catch{return null}}};De.GOOGLE_SIGN_IN_METHOD="google.com";De.PROVIDER_ID="google.com";var Ne=class t extends ke{constructor(){super("github.com")}static credential(e){return fe._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}}};Ne.GITHUB_SIGN_IN_METHOD="github.com";Ne.PROVIDER_ID="github.com";var Le=class t extends ke{constructor(){super("twitter.com")}static credential(e,n){return fe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:n})}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:n,oauthTokenSecret:r}=e;if(!n||!r)return null;try{return t.credential(n,r)}catch{return null}}};Le.TWITTER_SIGN_IN_METHOD="twitter.com";Le.PROVIDER_ID="twitter.com";function eu(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:start",j(t,e))}function tu(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:finalize",j(t,e))}var Ei="@firebase/auth",bi="1.12.1";var Yn=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 n=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,n),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let n=this.internalListeners.get(e);n&&(this.internalListeners.delete(e),n(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function nu(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 ru(t){Re(new X("auth",(e,{options:n})=>{let r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=r.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:r.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:ki(t)},p=new Nt(r,i,o,u);return jc(p,n),p},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,n,r)=>{e.getProvider("auth-internal").initialize()})),Re(new X("auth-internal",e=>{let n=Oi(e.getProvider("auth").getImmediate());return(r=>new Yn(r))(n)},"PRIVATE").setInstantiationMode("EXPLICIT")),_e(Ei,bi,nu(t)),_e(Ei,bi,"esm2020")}tt.initialize(fetch,Headers,Response);ru("Node");var wm=Xn("operation-not-supported-in-this-environment");Nt.prototype.setPersistence=async()=>{};function iu(t,e){return K(t,"POST","/v2/accounts/mfaSignIn:finalize",j(t,e))}var Jn=class{constructor(e){this.factorId=e}_process(e,n,r){switch(n.type){case"enroll":return this._finalizeEnroll(e,n.credential,r);case"signin":return this._finalizeSignIn(e,n.credential);default:return G("unexpected MultiFactorSessionType")}}},Mt=class{static assertionForEnrollment(e,n){return Ft._fromSecret(e,n)}static assertionForSignIn(e,n){return Ft._fromEnrollmentId(e,n)}static async generateSecret(e){let n=e;I(typeof n.user?.auth<"u","internal-error");let r=await eu(n.user.auth,{idToken:n.credential,totpEnrollmentInfo:{}});return Vt._fromStartTotpMfaEnrollmentResponse(r,n.user.auth)}};Mt.FACTOR_ID="totp";var Ft=class t extends Jn{constructor(e,n,r){super("totp"),this.otp=e,this.enrollmentId=n,this.secret=r}static _fromSecret(e,n){return new t(n,void 0,e)}static _fromEnrollmentId(e,n){return new t(n,e)}async _finalizeEnroll(e,n,r){return I(typeof this.secret<"u",e,"argument-error"),tu(e,{idToken:n,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,n){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let r={verificationCode:this.otp};return iu(e,{mfaPendingCredential:n,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}},Vt=class t{constructor(e,n,r,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=n,this.codeLength=r,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,n){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,n)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,n){let r=!1;return(Ct(e)||Ct(n))&&(r=!0),r&&(Ct(e)&&(e=this.auth.currentUser?.email||"unknownuser"),Ct(n)&&(n=this.auth.name)),`otpauth://totp/${n}:${e}?secret=${this.secretKey}&issuer=${n}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function Ct(t){return typeof t>"u"||t?.length===0}import*as E from"valibot";function M(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var ne=null;function at(){return Ui().platform}function Ui(){if(ne)return ne;let t=M();if(t?.platform)return ne={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},ne;let e=[];e.push(...su()),e.push(...au()),e.push(...cu());let n=e.sort((r,i)=>i.confidence-r.confidence)[0];return!n||n.confidence<N.MINIMUM?(ne={platform:S.UNKNOWN,mode:Li(),context:uu(),metadata:{detectedAt:Date.now()}},ne):(ne={platform:n.platform,mode:Li(),context:n.context,version:lu(n.platform),metadata:{...n.metadata,detectedAt:Date.now()}},ne)}var ot=null,st=null;function Mi(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return st=!0,!0;if(st===!0)return!0;let t=M();if(t?.platform){let n=t.platform===S.NEXTJS;return n&&(st=!0),n}let e=at()===S.NEXTJS;return e&&(st=!0),e}function Fi(){if(ot!==null)return ot;let t=M();if(t?.platform)return ot=t.platform===S.VITE,ot;let e=at()===S.VITE;return ot=e,e}function F(){return typeof window<"u"&&typeof document<"u"}function Zn(){return typeof process<"u"&&!!process.versions?.node}function su(){let t=[];if(F()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:S.VITE,confidence:N.HIGH,context:x.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=M();e?.platform===S.VITE&&t.push({platform:S.VITE,confidence:N.HIGH,context:x.CLIENT}),e?.i18n?.mapping&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:x.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:S.VITE,confidence:N.LOW,context:x.CLIENT})}return Zn()&&(process.env.VITE&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:x.SERVER}),process.env.npm_lifecycle_event?.includes(S.VITE)&&t.push({platform:S.VITE,confidence:N.LOW,context:x.BUILD})),t}function au(){let t=[];return Zn()&&(process.env.NEXT_RUNTIME&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:x.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:S.NEXTJS,confidence:N.MEDIUM,context:x.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:x.SERVER})),F()&&(M()?.platform===S.NEXTJS&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:x.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:x.CLIENT})),t}function cu(){let t=[];try{typeof globalThis<"u"&&globalThis.expo?.Constants?.expoConfig&&t.push({platform:S.EXPO,confidence:N.HIGH,context:x.CLIENT})}catch{}try{typeof globalThis<"u"&&globalThis.Platform?.OS&&!F()&&t.push({platform:S.REACT_NATIVE,confidence:N.MEDIUM,context:x.CLIENT})}catch{}let e=M();return e?.platform===S.EXPO?t.push({platform:S.EXPO,confidence:N.HIGH,context:x.CLIENT}):e?.platform===S.REACT_NATIVE&&t.push({platform:S.REACT_NATIVE,confidence:N.HIGH,context:x.CLIENT}),t}function Li(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===oe.PRODUCTION?oe.PRODUCTION:t===oe.TEST?oe.TEST:oe.DEVELOPMENT}function uu(){return F()?x.CLIENT:Zn()?oe.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?x.BUILD:x.SERVER:x.CLIENT}function lu(t){if(!(typeof process>"u"))return t===S.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===S.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 Vi(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function du(t){let e,n=M();return n?.env&&typeof n.env=="object"&&(e=n.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Vi(e)}function pu(t){let e=M(),n;return e?.env&&typeof e.env=="object"&&(n=e.env[t]),n===void 0&&typeof process<"u"&&process.env&&(n=process.env[t]),Vi(n)}function L(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=M();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 n=M()?.platform,r=e||n||(Fi()?"vite":Mi()?"nextjs":at()),i=["MODE","DEV","PROD","SSR"],o;return r==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:r==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,r==="vite"?du(o):r==="nextjs"?pu(o):void 0}function Z(){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=L("APP_ENV"),e=L("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var Bi=E.object({name:E.string(),color:E.string(),icon:E.string(),button:E.object({backgroundColor:E.string(),textColor:E.string(),borderColor:E.string(),hoverBackgroundColor:E.string(),focusOutlineColor:E.string(),fontWeight:E.optional(E.string(),"500")})}),fu=E.object({...Bi.entries,type:E.picklist(["auth","both"]),scopes:E.optional(E.array(E.string())),firebaseProviderId:E.optional(E.string())}),Ht=E.union([E.literal(""),E.pipe(E.string(),E.url())]),hu=E.object({authUrl:Ht,tokenUrl:Ht,profileUrl:Ht,revokeUrl:E.optional(Ht)}),mu=E.object({authentication:E.optional(E.array(E.string())),"api-access":E.array(E.string())}),pv=E.object({...Bi.entries,type:E.picklist(["oauth","both"]),scopes:mu,endpoints:hu}),ct=null;function gu(){let t=[];for(let[e,n]of Object.entries(Ee))E.safeParse(fu,n).success?t.push(e):typeof window<"u"&&Z();return t}function $t(){if(ct!==null)return ct;let t=L("AUTH_PARTNERS");if(!t)return ct=[],ct;let e=gu(),n=t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>e.includes(r));return ct=n,n}function ut(t){return typeof t=="object"&&t!==null&&"currentUser"in t&&typeof t.currentUser=="object"&&t.currentUser!==null}var vu=12e4,er=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,n={}){this.authInstance=e,this.refreshBuffer=n.refreshBufferMs??vu,this.maxRefreshAttempts=n.maxRefreshAttempts??3,this.autoRefresh=n.autoRefresh!==!1,this.onTokenExpired=n.onTokenExpired,this.onFatalError=n.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let n=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:n},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 n=await e.getIdToken(!0),r=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:n,expiresAt:r}),this.refreshAttempts=0,n}else if(e&&typeof e.getIdTokenResult=="function"){let n=await e.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}if(ut(this.authInstance)){let n=await this.authInstance.currentUser.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}throw v(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(n){return this.handleError(n instanceof Error?n:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:n}=this.tokenInfo;if(e==="valid")return n;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(ut(this.authInstance))return await this.forceRefresh(this.authInstance.currentUser)}catch(r){this.handleError(r instanceof Error?r:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:n}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let n={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},r=this.calculateTokenStatus(n.expiresAt);this.tokenInfo={...n,status:r},this.autoRefresh&&n.expiresAt&&this.scheduleRefresh(n.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let n=new Date;if(n>=e)return"expired";let r=new Date(e.getTime()-this.refreshBuffer);return n>=r?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let n=new Date,r=e.getTime()-n.getTime()-this.refreshBuffer;if(r<=0){ut(this.authInstance)&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{ut(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},r)}handleRefreshError(e){if(Z(),this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let n=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);Z(),setTimeout(()=>{ut(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(r=>{this.handleRefreshError(r)}):this.refreshCallback&&this.refreshCallback().catch(r=>{this.handleRefreshError(r)})},n)}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){Z(),this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},Dv=Ge(er,null,{});var qt=class{buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){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:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var he=null,yu="dndev-keys",lt="encryption-keys",Hi="main";async function $i(){return new Promise((t,e)=>{let n=indexedDB.open(yu,1);n.onupgradeneeded=()=>{n.result.createObjectStore(lt)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Eu(t){let e=await $i();return new Promise((n,r)=>{let i=e.transaction(lt,"readwrite");i.objectStore(lt).put(t,Hi),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async function bu(){try{let t=await $i();return new Promise((e,n)=>{let i=t.transaction(lt,"readonly").objectStore(lt).get(Hi);i.onsuccess=()=>e(i.result??null),i.onerror=()=>n(i.error)})}catch{return null}}async function Iu(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw v(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function qi(){if(he)return he;try{let t=await bu();return t?(he=t,he):(he=await Iu(),await Eu(he),he)}catch(t){throw v(t,{userMessage:"Failed to get or create encryption key"})}}async function Wi(t){try{let e=await qi(),n=window.crypto.getRandomValues(new Uint8Array(12)),r=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(r),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,o),c=new Uint8Array(n.length+s.byteLength);return c.set(n,0),c.set(new Uint8Array(s),n.length),btoa(String.fromCharCode(...c))}catch(e){throw v(e,{userMessage:"Failed to encrypt data"})}}async function Gi(t){try{let e=await qi(),n=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),r=n.slice(0,12),i=n.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r},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 qt{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,n={}){let{scope:r="user",encryption:i=!1}=n,o=this.buildKey(e,r,this.userId,!0);if(!o)return null;try{if(!F())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 Gi(u)),u}catch(s){throw v(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:n}})}}async set(e,n,r={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=r,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=n;o&&(u=await Wi(n));let p=s>0?new Date(Date.now()+s*1e3).toISOString():null,m=JSON.stringify({value:u,expiresAt:p,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,m)}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:r}})}}async remove(e){let n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,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 n=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(n));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var dt=class{localStrategy;userId;apiEndpoint;constructor(e,n="/api/storage"){if(!e)throw v("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=n}async get(e,n={}){try{let r=await this.localStrategy.get(e,n);return r!==null?r:await this.getFromCloud(e,n)}catch(r){try{return await this.localStrategy.get(e,n)}catch(i){throw v(r,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:n,fallbackError:i}})}}}async set(e,n,r={}){try{await this.localStrategy.set(e,n,r),this.setToCloud(e,n,r).catch(i=>{})}catch(i){throw v(i,{userMessage:"Failed to store data",context:{key:e,options:r}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(n=>{})}catch(n){throw v(n,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(n=>{})}catch(n){throw v(n,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){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:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,n){try{let{scope:r="user"}=n,i=this.buildKey(e,r,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,n).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,n,r){let{scope:i="user",expiry:o=0}=r,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:n,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 n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,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 n=new URLSearchParams;e&&n.append("scope",e),e==="user"&&n.append("userId",this.userId);let r=n.toString(),i=r?`${this.apiEndpoint}/clear?${r}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE"})).ok}catch{}}};var Wt=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{Z()}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,n){this.initialize(),n&&e?this.strategy=new dt(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new dt(this.userId):this.strategy=new re(this.userId)}async get(e,n={}){return this.initialize(),this.strategy.get(e,n)}async set(e,n,r={}){return this.initialize(),this.strategy.set(e,n,r)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,n,r={}){return this.initialize(),this.set(e,n,{...r,encryption:!0})}async getSecure(e,n={}){return this.initialize(),this.get(e,{...n,encryption:!0})}},Tu=Ge(Wt);var B={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function me(t){return!!t&&t.trim()!==""}var hy={[B.AUTH]:()=>$t().length>0,[B.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=>me(L(e))),[B.I18N]:()=>!0,[B.BILLING]:()=>!!(me(L("STRIPE_PUBLISHABLE_KEY"))||me(L("BILLING_ENABLED"))&&L("BILLING_ENABLED")==="true"),[B.ROUTES]:()=>!0,[B.THEMES]:()=>!0,[B.COMPONENTS]:()=>!0,[B.CRUD]:()=>!0,[B.FORMS]:()=>!0,[B.REALTIME]:()=>!!(me(L("REALTIME_ENABLED"))&&L("REALTIME_ENABLED")==="true"||me(L("FIREBASE_CONFIG"))),[B.STORAGE]:()=>!!(me(L("STORAGE_ENABLED"))&&L("STORAGE_ENABLED")==="true"||me(L("FIREBASE_CONFIG")))};var Vu=fr(cr(),1);var Bu=fr(cr(),1);var ur=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!1,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}once(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!0,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}off(e,n){let r=this.events.get(e);if(!r||r.length===0)return!1;let i=r.findIndex(o=>o.handler===n);return i===-1?!1:(r.splice(i,1),r.length===0&&this.events.delete(e),!0)}emit(e,...n){this.cacheEvent(e,n);let r=this.events.get(e);if(!r||r.length===0)return!1;let i=[...r],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,n):s.handler(...n),s.once&&o.push(s)}catch(c){v(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:n},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 n=this.events.get(e);return!!n&&n.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let n=this.events.get(e);return n?n.map(r=>r.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 n=this.events.get(e);return n||(n=[],this.events.set(e,n)),n}checkListenerCount(e){let n=this.listenerCount(e);this.maxListeners!==1/0&&n>this.maxListeners}cacheEvent(e,n){let r=this.eventCache.get(e);r||(r=[],this.eventCache.set(e,r)),r.push({data:n,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let n=this.eventCache.get(e);return!n||n.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,n=null,r=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(n===null||c.timestamp<n)&&(n=c.timestamp),(r===null||c.timestamp>r)&&(r=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:n,newestEvent:r,memoryEstimate:i}}cleanupCache(e){let n=Date.now()-this.cacheTTL;if(e){let r=this.eventCache.get(e);if(r){let i=r.filter(o=>o.timestamp>n);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[r,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>n);o.length===0?this.eventCache.delete(r):this.eventCache.set(r,o)}}},Qy=new ur;var iE={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:He.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:O.GUEST,userTier:Be.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},oE={status:He.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},sE={status:He.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},aE={status:He.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var io=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function oo(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function jt(t,e=""){if(Array.isArray(t))t.forEach((n,r)=>{let i=`${e}[${r}]`;if(typeof n=="string"&&oo(n)){if(!io.test(n))throw v(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${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&&jt(n,i)});else if(typeof t=="object"&&t!==null)for(let[n,r]of Object.entries(t)){let i=e?`${e}.${n}`:n;if(typeof r=="string"&&oo(r)){if(!io.test(r))throw v(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${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&&jt(r,i)}}import*as ao from"valibot";var lr={};function HE(t){lr.uniqueConstraintValidator=t}async function so(t,e,n){let{uniqueFields:r=[],collection:i}=t.metadata;r.length!==0&&lr.uniqueConstraintValidator&&await Promise.all(r.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await lr.uniqueConstraintValidator.checkDuplicate(i,o,c,n))throw v(new Error(s||`${o} must be unique`),{userMessage:s||`${o} must be unique`,context:{field:o}})}))}async function GE(t,e,n,r){ao.parse(t,e),jt(e),await so(t,e,r),t.metadata.customValidate&&await t.metadata.customValidate(e,n)}function Hu(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function eb(t){if(!Hu(t)){let e=t,n=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:n}})}return t.metadata.collection}var dr=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],rb="available",ib=["draft","deleted"],Fe=["id","createdAt","updatedAt","createdById","updatedById"],$u=[...Fe,"status"];function ob(t){return $u.includes(t)}function sb(t){return Fe.includes(t)}var R={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...dr]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},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}}};var qu=new Set(["__proto__","constructor","prototype"]);function Wu(t){for(let e of Object.keys(t.fields))if(qu.has(e))throw v(new Error(`Field name '${e}' in entity '${t.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${e}' in entity '${t.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:t.name,fieldName:e,operation:"defineEntity"},severity:"error"})}function Gu(t){let e=t.field.endsWith("Id")?t.field.slice(0,-2):t.field,n=t.collection||(e.endsWith("y")?e.slice(0,-1)+"ies":e+"s");return{name:t.field,label:`crud:fields.${t.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:n}}}function ju(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let n=t.map(i=>({value:i.value,label:i.label})),r=new Set(t.map(i=>i.value));for(let i of e)r.has(i.value)||n.push(i);return n}function Ku(t,e){if(!(!t.uniqueKeys||t.uniqueKeys.length===0))for(let n=0;n<t.uniqueKeys.length;n++){let r=t.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw v(new Error(`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`,context:{entityName:t.name,uniqueKeyIndex:n},severity:"error"});let i=r.fields.filter(o=>!e.has(o));if(i.length>0)throw v(new Error(`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:t.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function zu(t){let{form:e,fields:n}=t,r=Object.keys(n);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=>!r.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);r.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(m=>m.field):[i.condition.field]).filter(m=>!r.includes(m));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(m=>!r.includes(m));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(n).forEach(([i,o])=>{if(o.dependsOn&&!r.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 Yu(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 db(t){try{Wu(t),zu(t);let e=Yu(t),n={...t.fields,...R,...t.fields.createdAt&&{createdAt:{...R.createdAt,...t.fields.createdAt,type:R.createdAt.type,visibility:R.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...R.updatedAt,...t.fields.updatedAt,type:R.updatedAt.type,visibility:R.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...R.createdById,...t.fields.createdById,type:R.createdById.type,visibility:R.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...R.updatedById,...t.fields.updatedById,type:R.updatedById.type,visibility:R.updatedById.visibility}},...t.fields.status&&{status:{...R.status,...t.fields.status,type:R.status.type,visibility:R.status.visibility,editable:R.status.editable,validation:{...R.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:ju(dr,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:Gu(t.scope)}};if(t.listFields){let o=new Set(Object.keys(n)),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(n)),c=je(t).filter(u=>!o.has(u));if(c.length>0)throw v(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`,context:{entityName:t.name,invalidFields:c,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let o=new Set(Object.keys(n));Ku(t,o)}let r={...Xt,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:n,access:r,namespace:i,...t.search&&{search:t.search},...t.defaultSort&&{defaultSort:t.defaultSort}}}catch(e){throw v(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}import*as z from"valibot";function pt(t,e){return Object.assign(t,{visibility:e})}function ge(t,e){let n=t;return n.metadata={collection:e.collection,entity:e.name,...e.uniqueKeys&&{uniqueKeys:e.uniqueKeys}},n}function co(t){let e=Ye(t);return pt(e,t.visibility)}function uo(t){let e=Ye({...t,validation:{...t.validation,required:!1}});return pt(e,t.visibility)}function vb(t){let e=t.fields,n={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(n[D]=co(P));let r=ge(z.object(n),t),i={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(Fe.includes(D)||(i[D]=co(P)));let o=ge(z.object(i),t),s={};for(let[D,P]of Object.entries(e))if(P.visibility!=="hidden"&&!Fe.includes(D))if(D==="status"){let Y=z.literal("draft");s[D]=pt(Y,P.visibility)}else s[D]=uo(P);let c=ge(z.object(s),t),u={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(Fe.includes(D)||(u[D]=uo(P)));u.id=pt(Ye(R.id),"technical");let p=ge(z.object(u),t),m;if(t.listFields&&t.listFields.length>0){let D=["id","status"],P=[...new Set([...D,...t.listFields])];m={};for(let Y of P){let Ve=n[Y];Ve&&(m[Y]=Ve)}}else m=n;let T=ge(z.object(m),t),k,H=je(t);if(H.length>0){let D=["id","status"],P=[...new Set([...D,...H])];k={};for(let Y of P){let Ve=n[Y];Ve&&(k[Y]=Ve)}}else k=n;let ie=ge(z.object(k),t),ft=ge(z.object({id:pt(Ye(R.id),"technical")}),t);return{create:o,draft:c,update:p,get:r,list:T,listCard:ie,delete:ft}}function Eb(t,e,n=1,r=!1){let i=[];if(r)for(let o=e;o>=t;o-=n)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=n)i.push({value:String(o),label:String(o)});return i}var ve=new Map;function Ib(t,e){ve.has(t),ve.set(t,e)}function Tb(t){ve.delete(t)}function Sb(t){let e=ve.get(t);return e?e():null}function Ab(t){return ve.has(t)}function Cb(){return Array.from(ve.keys())}function wb(){ve.clear()}export{ed as AGGREGATE_FILTER_OPERATORS,Zl as AGGREGATE_OPERATIONS,Cd as AUTH_EVENTS,Ee as AUTH_PARTNERS,Ol as AUTH_PARTNER_STATE,Et as AuthHardening,Ir as AuthUserSchema,Fe as BACKEND_GENERATED_FIELD_NAMES,_d as BILLING_EVENTS,So as BREAKPOINT_RANGES,Zt as BREAKPOINT_THRESHOLDS,hr as COMMON_TIER_CONFIGS,N as CONFIDENCE_LEVELS,wr as CONSENT_CATEGORY,x as CONTEXTS,se as CRUD_OPERATORS,an as CURRENCY_MAP,br as CheckoutSessionMetadataSchema,Ie as ConditionBuilder,mr as CreateCheckoutSessionRequestSchema,gr as CreateCheckoutSessionResponseSchema,Tr as CustomClaimsSchema,Xt as DEFAULT_ENTITY_ACCESS,ae as DEFAULT_ERROR_MESSAGES,Yd as DEFAULT_LAYOUT_PRESET,dr as DEFAULT_STATUS_OPTIONS,rb as DEFAULT_STATUS_VALUE,sl as DEFAULT_SUBSCRIPTION,kp as DENSITY,_ as DoNotDevError,Kl as EDITABLE,kl as EMAIL_VERIFICATION_STATUS,mt as ENTITY_HOOK_ERRORS,oe as ENVIRONMENTS,$e as ERROR_CODES,bd as ERROR_SEVERITY,Id as ERROR_SOURCE,Sr as EntityHookError,zt as FEATURES,Op as FEATURE_CONSENT_MATRIX,He as FEATURE_STATUS,Jl as FIELD_TYPES,Qt as FIREBASE_ERROR_MAP,Ar as GITHUB_PERMISSION_LEVELS,ib as HIDDEN_STATUSES,Jd as LAYOUT_PRESET,Yl as LIST_SCHEMA_TYPE,Pd as OAUTH_EVENTS,tn as OAUTH_PARTNERS,zl as ORDER_DIRECTION,yp as PARTNER_ICONS,kd as PAYLOAD_EVENTS,Yt as PERMISSIONS,S as PLATFORMS,ql as PWA_ASSET_TYPES,$l as PWA_DISPLAY_MODES,bo as ProductDeclarationSchema,ml as ProductDeclarationsSchema,Wl as ROUTE_SOURCES,Hl as STORAGE_SCOPES,Bl as STORAGE_TYPES,Dd as STRIPE_EVENTS,ht as STRIPE_MODES,il as SUBSCRIPTION_DURATIONS,ye as SUBSCRIPTION_STATUS,Be as SUBSCRIPTION_TIERS,Ur as ServerUtils,pn as SingletonManager,To as StripeBackConfigSchema,Io as StripeFrontConfigSchema,yo as StripePaymentSchema,Eo as StripeSubscriptionSchema,yr as SubscriptionClaimsSchema,vr as SubscriptionDataSchema,$u as TECHNICAL_FIELD_NAMES,O as USER_ROLES,Jt as UserSubscriptionSchema,jl as VISIBILITY,Er as WebhookEventSchema,Ke as addMonths,hn as addYears,ea as addressSchema,na as arraySchema,R as baseFields,Mr as booleanSchema,$s as calculateSubscriptionEndDate,on as captureErrorToSentry,cp as checkGitHubAccessSchema,qh as clearSchemaGenerators,wb as clearScopeProviders,qe as commonErrorCodeMappings,cn as compactToISOString,Ss as configureProviders,Rs as createAsyncSingleton,ol as createDefaultSubscriptionClaims,Dl as createDefaultUserProfile,sd as createEntitySchema,$ as createErrorHandler,Qo as createMetadata,Ps as createMethodProxy,vb as createSchemas,Ge as createSingleton,_s as createSingletonWithParams,Se as dateSchema,db as defineEntity,ud as deleteEntitySchema,nn as detectErrorSource,dp as disconnectOAuthSchema,zs as emailSchema,Vh as enhanceSchema,jo as ensureSpreadable,ue as evaluateCondition,Vs as evaluateFieldConditions,up as exchangeTokenSchema,Fr as fileSchema,Vr as filesSchema,Ns as filterVisibleFields,es as formatCurrency,xr as formatDate,as as formatRelativeTime,ca as gdprConsentSchema,Or as generateCodeChallenge,kr as generateCodeVerifier,fs as generateFirestoreRuleCondition,ms as generatePKCEPair,Zs as geopointSchema,Ao as getBreakpointFromWidth,Kd as getBreakpointUtils,eb as getCollectionName,Hs as getConditionDependencies,pp as getConnectionsSchema,Pr as getCurrencyLocale,Zo as getCurrencySymbol,rs as getCurrentTimestamp,ad as getEntitySchema,je as getListCardFieldNames,As as getProvider,$h as getRegisteredSchemaTypes,Cb as getRegisteredScopeProviders,Is as getRoleFromClaims,Ye as getSchemaType,Sb as getScopeValue,fn as getVisibleFields,ss as getWeekFromISOString,Co as githubPermissionSchema,en as githubRepoConfigSchema,sp as grantGitHubAccessSchema,v as handleError,Hh as hasCustomSchemaGenerator,Hu as hasMetadata,Cs as hasProvider,Ls as hasRestrictedVisibility,vt as hasRoleAccess,Ab as hasScopeProvider,Ts as hasTierAccess,sa as ibanSchema,Do as isAuthPartnerId,sb as isBackendGeneratedField,jd as isBreakpoint,un as isCompactDateString,Lr as isFieldVisible,ob as isFrameworkField,No as isOAuthPartnerId,gs as isPKCESupported,ts as isoToCompactString,bs as lazyImport,ld as listEntitiesSchema,ta as mapSchema,ce as mapToDoNotDevError,hs as maybeTranslate,ra as multiselectSchema,Br as neverSchema,ns as normalizeToISOString,Te as numberSchema,Zu as overrideFeatures,rl as overridePaymentModes,el as overridePermissions,nl as overrideSubscriptionStatus,Qu as overrideSubscriptionTiers,Xu as overrideUserRoles,ln as parseDate,us as parseDateToNoonUTC,qs as parseISODate,Ks as parseServerCookie,Ys as passwordSchema,Xs as pictureSchema,Qs as picturesSchema,ua as priceSchema,Eb as rangeOptions,ia as referenceSchema,lp as refreshTokenSchema,y as registerSchemaGenerator,Ib as registerScopeProvider,HE as registerUniqueConstraintValidator,ws as resetProviders,ap as revokeGitHubAccessSchema,Go as safeValidate,mn as selectSchema,Bo as showNotification,gn as stringSchema,aa as switchSchema,oa as telSchema,bt as textSchema,os as timestampToISOString,ls as toDateOnly,is as toISOString,zo as translateArray,Jo as translateArrayRange,Xo as translateArrayWithIndices,Yo as translateObjectArray,Tb as unregisterScopeProvider,cd as updateEntitySchema,xs as updateMetadata,Js as urlSchema,bp as validateAuthPartners,Pl as validateAuthSchemas,wl as validateAuthUser,yl as validateBillingSchemas,hl as validateCheckoutSessionMetadata,ys as validateCodeChallenge,vs as validateCodeVerifier,ul as validateCreateCheckoutSessionRequest,ll as validateCreateCheckoutSessionResponse,Rl as validateCustomClaims,jt as validateDates,GE as validateDocument,js as validateEnvVar,Gs as validateMetadata,Ip as validateOAuthPartners,vl as validateStripeBackConfig,gl as validateStripeFrontConfig,pl as validateSubscriptionClaims,dl as validateSubscriptionData,so as validateUniqueFields,Ws as validateUrl,_l as validateUserSubscription,fl as validateWebhookEvent,Wo as validateWithSchema,Bs as when,Vo as withErrorHandling,Es as withGracefulDegradation,qo as wrapAuthError,Ho as wrapCrudError,$o as wrapStorageError};
|
|
1
|
+
var lo=Object.create;var zt=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var fo=Object.getOwnPropertyNames;var ho=Object.getPrototypeOf,mo=Object.prototype.hasOwnProperty;var pr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),go=(t,e)=>{for(var n in e)zt(t,n,{get:e[n],enumerable:!0})},vo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fo(e))!mo.call(t,i)&&i!==n&&zt(t,i,{get:()=>e[i],enumerable:!(r=po(e,i))||r.enumerable});return t};var fr=(t,e,n)=>(n=t!=null?lo(ho(t)):{},vo(e||!t||!t.__esModule?zt(n,"default",{value:t,enumerable:!0}):n,t));var no=pr(b=>{"use strict";var rr=Symbol.for("react.transitional.element"),Su=Symbol.for("react.portal"),Au=Symbol.for("react.fragment"),Cu=Symbol.for("react.strict_mode"),wu=Symbol.for("react.profiler"),_u=Symbol.for("react.consumer"),Ru=Symbol.for("react.context"),Pu=Symbol.for("react.forward_ref"),ku=Symbol.for("react.suspense"),xu=Symbol.for("react.memo"),Ji=Symbol.for("react.lazy"),Ou=Symbol.for("react.activity"),ji=Symbol.iterator;function Du(t){return t===null||typeof t!="object"?null:(t=ji&&t[ji]||t["@@iterator"],typeof t=="function"?t:null)}var Xi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Qi=Object.assign,Zi={};function Me(t,e,n){this.props=t,this.context=e,this.refs=Zi,this.updater=n||Xi}Me.prototype.isReactComponent={};Me.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")};Me.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function eo(){}eo.prototype=Me.prototype;function ir(t,e,n){this.props=t,this.context=e,this.refs=Zi,this.updater=n||Xi}var or=ir.prototype=new eo;or.constructor=ir;Qi(or,Me.prototype);or.isPureReactComponent=!0;var Ki=Array.isArray;function nr(){}var w={H:null,A:null,T:null,S:null},to=Object.prototype.hasOwnProperty;function sr(t,e,n){var r=n.ref;return{$$typeof:rr,type:t,key:e,ref:r!==void 0?r:null,props:n}}function Nu(t,e){return sr(t.type,e,t.props)}function ar(t){return typeof t=="object"&&t!==null&&t.$$typeof===rr}function Lu(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var zi=/\/+/g;function tr(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Lu(""+t.key):e.toString(36)}function Uu(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(nr,nr):(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 Ue(t,e,n,r,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 rr:case Su:s=!0;break;case Ji:return s=t._init,Ue(s(t._payload),e,n,r,i)}}if(s)return i=i(t),s=r===""?"."+tr(t,0):r,Ki(i)?(n="",s!=null&&(n=s.replace(zi,"$&/")+"/"),Ue(i,e,n,"",function(p){return p})):i!=null&&(ar(i)&&(i=Nu(i,n+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(zi,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=r===""?".":r+":";if(Ki(t))for(var u=0;u<t.length;u++)r=t[u],o=c+tr(r,u),s+=Ue(r,e,n,o,i);else if(u=Du(t),typeof u=="function")for(t=u.call(t),u=0;!(r=t.next()).done;)r=r.value,o=c+tr(r,u++),s+=Ue(r,e,n,o,i);else if(o==="object"){if(typeof t.then=="function")return Ue(Uu(t),e,n,r,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 jt(t,e,n){if(t==null)return t;var r=[],i=0;return Ue(t,r,"","",function(o){return e.call(n,o,i++)}),r}function Mu(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Yi=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}},Fu={map:jt,forEach:function(t,e,n){jt(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return jt(t,function(){e++}),e},toArray:function(t){return jt(t,function(e){return e})||[]},only:function(t){if(!ar(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};b.Activity=Ou;b.Children=Fu;b.Component=Me;b.Fragment=Au;b.Profiler=wu;b.PureComponent=ir;b.StrictMode=Cu;b.Suspense=ku;b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w;b.__COMPILER_RUNTIME={__proto__:null,c:function(t){return w.H.useMemoCache(t)}};b.cache=function(t){return function(){return t.apply(null,arguments)}};b.cacheSignal=function(){return null};b.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var r=Qi({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!to.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(r[o]=e[o]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];r.children=s}return sr(t.type,i,r)};b.createContext=function(t){return t={$$typeof:Ru,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:_u,_context:t},t};b.createElement=function(t,e,n){var r,i={},o=null;if(e!=null)for(r in e.key!==void 0&&(o=""+e.key),e)to.call(e,r)&&r!=="key"&&r!=="__self"&&r!=="__source"&&(i[r]=e[r]);var s=arguments.length-2;if(s===1)i.children=n;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(r in s=t.defaultProps,s)i[r]===void 0&&(i[r]=s[r]);return sr(t,o,i)};b.createRef=function(){return{current:null}};b.forwardRef=function(t){return{$$typeof:Pu,render:t}};b.isValidElement=ar;b.lazy=function(t){return{$$typeof:Ji,_payload:{_status:-1,_result:t},_init:Mu}};b.memo=function(t,e){return{$$typeof:xu,type:t,compare:e===void 0?null:e}};b.startTransition=function(t){var e=w.T,n={};w.T=n;try{var r=t(),i=w.S;i!==null&&i(n,r),typeof r=="object"&&r!==null&&typeof r.then=="function"&&r.then(nr,Yi)}catch(o){Yi(o)}finally{e!==null&&n.types!==null&&(e.types=n.types),w.T=e}};b.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()};b.use=function(t){return w.H.use(t)};b.useActionState=function(t,e,n){return w.H.useActionState(t,e,n)};b.useCallback=function(t,e){return w.H.useCallback(t,e)};b.useContext=function(t){return w.H.useContext(t)};b.useDebugValue=function(){};b.useDeferredValue=function(t,e){return w.H.useDeferredValue(t,e)};b.useEffect=function(t,e){return w.H.useEffect(t,e)};b.useEffectEvent=function(t){return w.H.useEffectEvent(t)};b.useId=function(){return w.H.useId()};b.useImperativeHandle=function(t,e,n){return w.H.useImperativeHandle(t,e,n)};b.useInsertionEffect=function(t,e){return w.H.useInsertionEffect(t,e)};b.useLayoutEffect=function(t,e){return w.H.useLayoutEffect(t,e)};b.useMemo=function(t,e){return w.H.useMemo(t,e)};b.useOptimistic=function(t,e){return w.H.useOptimistic(t,e)};b.useReducer=function(t,e,n){return w.H.useReducer(t,e,n)};b.useRef=function(t){return w.H.useRef(t)};b.useState=function(t){return w.H.useState(t)};b.useSyncExternalStore=function(t,e,n){return w.H.useSyncExternalStore(t,e,n)};b.useTransition=function(){return w.H.useTransition()};b.version="19.2.4"});var cr=pr((yy,ro)=>{"use strict";ro.exports=no()});var Ur={};go(Ur,{AuthHardening:()=>bt,CURRENCY_MAP:()=>cn,ConditionBuilder:()=>Ie,DEFAULT_ERROR_MESSAGES:()=>ae,DoNotDevError:()=>_,SingletonManager:()=>pn,addMonths:()=>Ke,addYears:()=>hn,calculateSubscriptionEndDate:()=>$s,captureErrorToSentry:()=>sn,commonErrorCodeMappings:()=>qe,compactToISOString:()=>un,configureProviders:()=>Ss,createAsyncSingleton:()=>Rs,createErrorHandler:()=>$,createMetadata:()=>Qo,createMethodProxy:()=>Ps,createSingleton:()=>Ge,createSingletonWithParams:()=>_s,detectErrorSource:()=>rn,ensureSpreadable:()=>jo,evaluateCondition:()=>ue,evaluateFieldConditions:()=>Vs,filterVisibleFields:()=>Ns,formatCurrency:()=>es,formatDate:()=>kr,formatRelativeTime:()=>as,generateCodeChallenge:()=>Or,generateCodeVerifier:()=>xr,generateFirestoreRuleCondition:()=>fs,generatePKCEPair:()=>ms,getConditionDependencies:()=>Hs,getCurrencyLocale:()=>Pr,getCurrencySymbol:()=>Zo,getCurrentTimestamp:()=>rs,getListCardFieldNames:()=>je,getProvider:()=>As,getRoleFromClaims:()=>Is,getVisibleFields:()=>fn,getWeekFromISOString:()=>ss,handleError:()=>v,hasProvider:()=>Cs,hasRestrictedVisibility:()=>Ls,hasRoleAccess:()=>yt,hasTierAccess:()=>Ts,isCompactDateString:()=>ln,isFieldVisible:()=>Lr,isPKCESupported:()=>gs,isoToCompactString:()=>ts,lazyImport:()=>bs,mapToDoNotDevError:()=>ce,maybeTranslate:()=>hs,normalizeToISOString:()=>ns,parseDate:()=>dn,parseDateToNoonUTC:()=>us,parseISODate:()=>qs,parseServerCookie:()=>Ks,resetProviders:()=>ws,safeValidate:()=>Go,showNotification:()=>Bo,timestampToISOString:()=>os,toDateOnly:()=>ls,toISOString:()=>is,translateArray:()=>zo,translateArrayRange:()=>Jo,translateArrayWithIndices:()=>Xo,translateObjectArray:()=>Yo,updateMetadata:()=>ks,validateCodeChallenge:()=>ys,validateCodeVerifier:()=>vs,validateEnvVar:()=>js,validateMetadata:()=>Gs,validateUrl:()=>Ws,validateWithSchema:()=>Wo,when:()=>Bs,withErrorHandling:()=>Vo,withGracefulDegradation:()=>Es,wrapAuthError:()=>qo,wrapCrudError:()=>Ho,wrapStorageError:()=>$o});var O={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function Xu(t){Object.assign(O,t)}var Be={FREE:"free",PRO:"pro",PREMIUM:"premium"};function Qu(t){Object.assign(Be,t)}var Yt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Zu(t){Object.assign(Yt,t)}var Jt={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 el(t){Object.assign(Jt,t)}import*as l from"valibot";var ye={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function nl(t){Object.assign(ye,t)}var ht={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function rl(t){Object.assign(ht,t)}var il={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function ol(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var hr={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}},sl={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var mr=a.object({userId:a.optional(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([ht.PAYMENT,ht.SUBSCRIPTION]))}),gr=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),vr=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(ye)),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())}),yr=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(ye)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),Er=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),br=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function ul(t){return a.safeParse(mr,t)}function ll(t){return a.safeParse(gr,t)}function dl(t){return a.safeParse(vr,t)}function pl(t){return a.safeParse(yr,t)}function fl(t){return a.safeParse(Er,t)}function hl(t){return a.safeParse(br,t)}var yo=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()))}),Eo=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()))}),bo=a.variant("type",[yo,Eo]),ml=a.record(a.string(),bo),Io=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())})),To=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 gl(t){return a.parse(Io,t)}function vl(t){return a.parse(To,t)}function yl(){let t={createCheckoutSessionRequest:a.safeParse(mr,{}),createCheckoutSessionResponse:a.safeParse(gr,{}),subscriptionData:a.safeParse(vr,{}),subscriptionClaims:a.safeParse(yr,{}),webhookEvent:a.safeParse(Er,{}),checkoutSessionMetadata:a.safeParse(br,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var Ir=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(O))),customClaims:l.optional(l.record(l.string(),l.any()))}),Xt=l.object({userId:l.string(),tier:l.picklist(Object.values(Be)),status:l.picklist(Object.values(ye)),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())}),Tr=l.object({role:l.optional(l.picklist(Object.values(O))),subscription:l.optional(Xt),features:l.optional(l.array(l.picklist(Object.values(Yt)))),permissions:l.optional(l.array(l.picklist(Object.values(Jt)))),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 wl(t){return l.safeParse(Ir,t)}function _l(t){return l.safeParse(Xt,t)}function Rl(t){return l.safeParse(Tr,t)}function Pl(){let t={authUser:l.safeParse(Ir,{}),userSubscription:l.safeParse(Xt,{}),customClaims:l.safeParse(Tr,{}),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 xl={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},Ol={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Dl(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var S={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},oe={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},k={CLIENT:"client",SERVER:"server",BUILD:"build"},N={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},He={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Bl={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},Hl={USER:"user",GLOBAL:"global",SESSION:"session"},$l={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},ql={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Wl={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var jl={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},Kl={TRUE:!0,FALSE:!1,ADMIN:"admin",CREATE_ONLY:"create-only"},Qt={create:"admin",read:"guest",update:"admin",delete:"admin"},se={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},zl={ASC:"asc",DESC:"desc"},Yl={LIST:"list",LIST_CARD:"listCard"},Jl=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Zl={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},ed={EQ:se.EQ,NEQ:se.NEQ,LT:se.LT,LTE:se.LTE,GT:se.GT,GTE:se.GTE};import*as h from"valibot";var sd=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())}),ad=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"))}),cd=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)}),ud=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"))}),ld=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)),1e3),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.unknown()})))});var $e={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},bd={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},mt={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Zt={[$e.PERMISSION_DENIED]:{type:mt.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[$e.NOT_FOUND]:{type:mt.NOT_FOUND,message:"The requested resource was not found"},[$e.ALREADY_EXISTS]:{type:mt.ALREADY_EXISTS,message:"The resource already exists"},[$e.INVALID_ARGUMENT]:{type:mt.VALIDATION_ERROR,message:"Invalid argument provided"}},Sr=class extends Error{type;originalError;constructor(e,n,r){super(n),this.name="EntityHookError",this.type=e,this.originalError=r}},Id={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},_=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,n=$e.INTERNAL,r){super(e),Object.setPrototypeOf(this,t.prototype),this.code=n,this.details=r?.details,this.source=r?.source,this.originalError=r?.originalError,this.context=r?.context,this.displayable=r?.displayable??!0,this.userMessageProvided=r?.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 Cd={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 _d={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 Pd={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 xd={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 Dd={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 en={mobile:0,tablet:768,laptop:1024,desktop:1440},So={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function Ao(t){return t>=en.desktop?"desktop":t>=en.laptop?"laptop":t>=en.tablet?"tablet":"mobile"}function jd(t,e){let n=So[e];return t>=n.min&&t<=n.max}function Kd(t,e){let n=Ao(t);return{current:n,width:t,height:e,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var Yd="landing",Jd={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Ar=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var tn=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"))}),Co=f.picklist([...Ar]),sp=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:tn,permission:f.optional(Co,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),ap=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:tn}),cp=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:tn}),up=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()))}),lp=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"))}),dp=f.object({provider:f.string()}),pp=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var yp={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 g from"valibot";var Cr=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),wo=g.object({...Cr.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),gt=g.union([g.literal(""),g.pipe(g.string(),g.url())]),_o=g.object({authUrl:gt,tokenUrl:gt,profileUrl:gt,revokeUrl:g.optional(gt)}),Ro=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),Po=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),ko=g.object({...Cr.entries,type:g.picklist(["oauth","both"]),scopes:Ro,endpoints:_o,capabilities:Po}),Ee={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"}}},nn={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"}}},xo=g.record(g.string(),wo),Oo=g.record(g.string(),ko);function bp(){return g.safeParse(xo,Ee)}function Ip(){return g.safeParse(Oo,nn)}function Do(t){return t in Ee}function No(t){return t in nn}var wr={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},xp={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Op={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:wr.ANALYTICS},marketing:{requiresConsent:wr.MARKETING}};function rn(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 Rr from"valibot";function $(t){return(e,n)=>{if(e instanceof _)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new _(n||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let r;t.extractErrorCode?r=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(r=e.code);let i=t.defaultErrorCode;r&&t.errorCodeMapping&&r in t.errorCodeMapping&&(i=t.errorCodeMapping[r]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),r&&t.friendlyMessageMapping&&r in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[r]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},r&&(s.originalCode=r)),"originalError"in s||(s.originalError=e),new _(n||o,i,{details:s,source:t.errorSource})}}var qe={"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 ae={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",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."},Lo={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"},on={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},ee={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",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...qe},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",...qe},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(Lo).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:qe,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ae.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:ae["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ae.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},Uo=t=>t instanceof Rr.ValiError?new _(ae["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(ee.validation)(t),Mo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in on){let e=t,n=on[e.type]||"unknown";return new _(e.message||ae[n],n,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Zt[t.code]){let e=t,n=Zt[e.code];if(n){let r=on[n.type]||"unknown";return new _(n.message||ae[r],r,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(ee.entity)(t)},_r={auth:$(ee.auth),oauth:$(ee.oauth),api:$(ee.api),firebase:$(ee.firebase),ui:$(ee.ui),validation:Uo,entity:Mo,unknown:$(ee.unknown)};function ce(t,e,n){return t instanceof _?t:(_r[e]||_r.unknown)(t,n)}function sn(t,e,n={}){let r=globalThis.Sentry;r&&r.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(n).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||n.userId)&&i.setUser({id:t.details?.userId||n.userId,email:t.details?.userEmail||n.userEmail}),r.captureException(t)})}function Fo(){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":!1}function v(t,e){let n=typeof e=="string"?{userMessage:e}:e||{},{userMessage:r,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=n,p=rn(t),m=t instanceof _?t:ce(t,p,r);if(r&&!m.userMessageProvided&&(m.message.includes("Error")||m.message.includes("Failed")||m.message.length<10?m=new _(r,m.code,{details:{...m.details,originalMessage:m.message},source:p,userMessageProvided:!0}):m=new _(m.message,m.code,{details:{...m.details,userMessage:r},source:p,userMessageProvided:!0})),o){let T=Fo()||typeof window<"u"&&window.__DNDEV_DEBUG,x={code:m.code,message:m.message,source:p};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&sn(m,p,i),m}function Vo(t,e){return async(...n)=>{try{return await t(...n)}catch(r){throw v(r,e)}}}function Bo(t,e="info",n){let r=Date.now().toString();return r}function Ho(t,e,n,r,i){let o=`${e}.${n}(${r}${i?`, ${i}`:""})`;return ce(t,"api",`${o}: ${an(t)}`)}function $o(t,e,n,r){let i=`${e}.${n}(${r})`;return ce(t,"api",`${i}: ${an(t)}`)}function qo(t,e,n,r){let i=r?` ${JSON.stringify(r)}`:"",o=`${e}.${n}(${i})`,s=ce(t,"auth",`${o}: ${an(t)}`);return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&s.code==="unknown"&&t.code!=="unknown"?new _(s.message,s.code,{details:{...s.details,originalCode:t.code},source:s.source}):s}function an(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}import*as We from"valibot";function Wo(t,e,n){try{return We.parse(t,e)}catch(r){throw r instanceof We.ValiError?new _(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:e},source:"validation"}):new _(`Unexpected validation error in ${n}: ${Ko(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function Go(t,e){try{return We.parse(t,e)}catch{return null}}function jo(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{value:t}}function Ko(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}function zo(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(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 Yo(t,e,n,r){return Array.from({length:n},(i,o)=>{let s=`${e}.${o}.${String(r[0])}`;if(t(s)===s)return null;let u={};for(let p of r){let m=`${e}.${o}.${String(p)}`;u[p]=t(m)}return u}).filter(i=>i!==null)}function Jo(t,e,n,r,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:r-n},(u,p)=>{let m=n+p,T=`${e}.${m}`;return t(T)}).filter((u,p)=>{let m=n+p,T=`${e}.${m}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,m))})}function Xo(t,e,n,r={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=r;return Array.from({length:n},(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 Qo(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}var cn={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 Pr(t){return cn[t]?.locale??"en-US"}function Zo(t){return!t||typeof t!="string"?t??"":cn[t]?.symbol??t}function es(t,e,n={}){if(t==null||isNaN(t))return"";let r=Pr(e);return new Intl.NumberFormat(r,{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:0,currencyDisplay:"symbol",...n}).format(t)}function un(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 n=e[1],r=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(n,10),parseInt(r,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 ts(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=e.getUTCFullYear(),r=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`${n}${r}${i}:${o}${s}`}function ln(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function ns(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(ln(t))return un(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 rs(){return new Date().toISOString()}function is(t){return t.toISOString()}function os(t){return new Date(t).toISOString()}function ss(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let n=new Date(e.getFullYear(),0,1),r=Math.floor((e.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${e.getFullYear()}`}var U={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function as(t,e="en",n={}){if(!t)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:o=U.WEEK}=n,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),m=Math.abs(p);if(m>o)return kr(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:r,numeric:i});return m<U.MINUTE?T.format(p,"second"):m<U.HOUR?T.format(Math.round(p/U.MINUTE),"minute"):m<U.DAY?T.format(Math.round(p/U.HOUR),"hour"):m<U.WEEK?T.format(Math.round(p/U.DAY),"day"):m<U.MONTH?T.format(Math.round(p/U.WEEK),"week"):m<U.YEAR?T.format(Math.round(p/U.MONTH),"month"):T.format(Math.round(p/U.YEAR),"year")}function cs(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 kr(t,e="en",n="long"){if(!t)return"";let r;if(t instanceof Date)r=t;else if(typeof t=="string")r=new Date(t);else if(typeof t=="number")r=new Date(t);else if(typeof t=="object"&&"toDate"in t)r=t.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?cs(n):n;return new Intl.DateTimeFormat(e,i).format(r)}function dn(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(ln(e))try{return un(e)}catch{return}let n=new Date(e);return isNaN(n.getTime())?void 0:n.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 n=e.toDate();return isNaN(n.getTime())?void 0:n.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,n=e.seconds*1e3+(e.nanoseconds||0)/1e6,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function us(t){let e=dn(t);if(!e)return;let n=new Date(e);return n.setUTCHours(12,0,0,0),n.toISOString()}function ls(t){let e=dn(t);return e&&e.split("T")[0]||""}function ds(t){return typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:typeof t=="boolean"?t?"true":"false":String(t)}function ps(t){let e=`resource.data.${t.field}`,n=ds(t.value);return`${e} ${t.op} ${n}`}function fs(t){let e=[];if(t.publicCondition&&t.publicCondition.length>0){let n=t.publicCondition.map(ps).join(" && ");e.push(`(${n})`)}for(let n of t.ownerFields)e.push(`request.auth.uid == resource.data.${n}`);return e.length===0?"false":e.join(" || ")}function hs(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function xr(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Dr(t)}async function Or(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Dr(new Uint8Array(r))}async function ms(){let t=xr(),e=await Or(t);return{codeVerifier:t,codeChallenge:e}}function Dr(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gs(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function vs(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function ys(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function Es(t,e,n){try{return await t()}catch{return e(),!1}}var vt=new Map;function bs(t,e){if(vt.has(e))return vt.get(e);let n=t().catch(r=>{throw vt.delete(e),r});return vt.set(e,n),n}var Nr={[O.GUEST]:0,[O.USER]:1,[O.ADMIN]:2,[O.SUPER]:3};function yt(t,e){if(!t)return!1;let n=Nr[t]??-1,r=Nr[e]??1/0;return n>=r}function Is(t){return t?t.role===O.SUPER||t.isSuper===!0?O.SUPER:t.role===O.ADMIN||t.isAdmin===!0?O.ADMIN:t.role===O.USER?O.USER:t.role||O.USER:O.USER}function Ts(t,e,n){if(!t)return!1;let r=n??hr,i=r[t]?.level??-1,o=r[e]?.level??1/0;return i>=o}var be=null;function Ss(t){be=t}function As(t){if(!be)throw new Error(`[dndev] Provider "${t}" not available. Call configureProviders() at app startup.`);let e=be[t];if(!e)throw new Error(`[dndev] Provider "${t}" not configured. Pass it to configureProviders().`);return e}function Cs(t){return!!be?.[t]}function ws(){be=null}function Ge(t,...e){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?n=new t(...e):n=t(),n}finally{r=!1}}}function _s(t){let e=null,n=!1;return function(...i){if(e!==null)return e;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{n=!1}}}function Rs(t){let e=null,n=!1,r=null;return async function(){if(e!==null)return e;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=t(),e=await r,e}finally{n=!1,r=null}}}function Ps(t,e){return new Proxy({},{get(n,r){if(e.includes(r)){let o=t(),s=o[r];return typeof s=="function"?s.bind(o):s}return t()[r]}})}var pn=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,n,r={}){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(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",r.fallbackFactory){let i=r.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 n();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(typeof process<"u",r.cacheFailures&&this.initialized.add(e),r.fallbackFactory){let o=r.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 ks(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}function xs(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function Os(t){if(xs(t))return t.visibility}function Lr(t,e){let n=t??"guest";return n==="hidden"?!1:n==="technical"?yt(e,"admin"):n==="owner"?!1:yt(e,n)}function Ds(t,e,n){for(let r of n.ownerFields)if(t[r]===e)return!0;return!1}function fn(t,e,n){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let i=r.entries,o=[],{documentData:s,uid:c,ownership:u}=n??{},p=u&&c!=null&&s&&Ds(s,c,u);for(let[m,T]of Object.entries(i)){let x=Os(T);if(x==="owner"){p&&o.push(m);continue}Lr(x,e)&&o.push(m)}return o}function Ns(t,e,n,r){if(!t)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??t,uid:r.uid,ownership:r.ownership}:void 0,o=fn(e,n,i),s={};for(let c of o)Object.prototype.hasOwnProperty.call(t,c)&&(s[c]=t[c]);return s}function je(t){let e=t.listCardFields;if(e){if(Array.isArray(e))return e;let n=e,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return t.listFields&&t.listFields.length>0?t.listFields:t.fields?Object.keys(t.fields):[]}function Et(t){if(!(!t||typeof t!="object")){if(t.entries&&typeof t.entries=="object")return t.entries;if(Array.isArray(t.pipe))for(let e of t.pipe){let n=Et(e);if(n)return n}if(t.wrapped)return Et(t.wrapped);if(Array.isArray(t.options))for(let e of t.options){let n=Et(e);if(n)return n}}}function Ls(t){let e=Et(t);if(!e)return!1;for(let n of Object.values(e)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}var bt=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(e={}){this.maxAttempts=e.maxAttempts??5,this.lockoutMs=e.lockoutMs??900*1e3,this.sessionTimeoutMs=e.sessionTimeoutMs??480*60*1e3}checkLockout(e){let n=this.store.get(e);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(e)}}recordFailure(e){let n=Date.now();!this.store.has(e)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(e)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(e,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(e){for(let[n,r]of this.store)r.lockedUntil!==null&&e>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&e-r.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(e){this.store.delete(e)}isSessionExpired(e){return Date.now()-e>this.sessionTimeoutMs}getEntry(e){return this.store.get(e)}};function Us(t,e){if(e.includes(".")){let n=e.split("."),r=t;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}return r}return t[e]}function Ms(t,e){let n=Us(e,t.field);switch(t.operator){case"equals":return n===t.value;case"notEquals":return n!==t.value;case"in":return Array.isArray(t.value)&&t.value.includes(n);case"notIn":return Array.isArray(t.value)&&!t.value.includes(n);case"greaterThan":return typeof n=="number"&&typeof t.value=="number"&&n>t.value;case"lessThan":return typeof n=="number"&&typeof t.value=="number"&&n<t.value;case"greaterThanOrEqual":return typeof n=="number"&&typeof t.value=="number"&&n>=t.value;case"lessThanOrEqual":return typeof n=="number"&&typeof t.value=="number"&&n<=t.value;case"exists":return n!=null&&n!==""&&n!==!1;case"notExists":return n==null||n===""||n===!1;case"contains":return typeof n=="string"&&typeof t.value=="string"||Array.isArray(n)?n.includes(t.value):!1;default:return!1}}function Fs(t){return t instanceof Ie||"expression"in t?t.expression:t}function ue(t,e){let n=Fs(t);if(n.type==="condition")return Ms(n,e);let{logic:r,conditions:i}=n;return r==="and"?i.every(o=>ue(o,e)):i.some(o=>ue(o,e))}function Vs(t,e){return t?{visible:t.visible?ue(t.visible,e):!0,disabled:t.disabled?ue(t.disabled,e):!1,required:t.required?ue(t.required,e):!1,readonly:t.readonly?ue(t.readonly,e):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var Ie=class t{expression;constructor(e){this.expression=e}get type(){return this.expression.type}or(e){let n=e instanceof t?e.expression:e,r=this.expression;return r.type==="group"&&r.logic==="or"?new t({type:"group",logic:"or",conditions:[...r.conditions,n]}):new t({type:"group",logic:"or",conditions:[r,n]})}and(e){let n=e instanceof t?e.expression:e,r=this.expression;return r.type==="group"&&r.logic==="and"?new t({type:"group",logic:"and",conditions:[...r.conditions,n]}):new t({type:"group",logic:"and",conditions:[r,n]})}};function Bs(t){function e(n,r){return new Ie({type:"condition",field:t,operator:n,value:r})}return{equals:n=>e("equals",n),notEquals:n=>e("notEquals",n),in:n=>e("in",n),notIn:n=>e("notIn",n),greaterThan:n=>e("greaterThan",n),lessThan:n=>e("lessThan",n),greaterThanOrEqual:n=>e("greaterThanOrEqual",n),lessThanOrEqual:n=>e("lessThanOrEqual",n),exists:()=>e("exists"),notExists:()=>e("notExists"),contains:n=>e("contains",n)}}function Hs(t){let e=t instanceof Ie?t.expression:t,n=new Set;function r(i){if(i.type==="condition")n.add(i.field);else for(let o of i.conditions)r(o)}return r(e),n}function Ke(t,e){let n=new Date(t),r=n.getDate();return n.setMonth(n.getMonth()+e),n.getDate()!==r&&n.setDate(0),n}function hn(t,e){let n=new Date(t),r=n.getDate();return n.setFullYear(n.getFullYear()+e),n.getDate()!==r&&n.setDate(0),n}function $s(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return t==="1month"?n=Ke(e,1):t==="3months"?n=Ke(e,3):t==="6months"?n=Ke(e,6):t==="1year"?n=hn(e,1):t==="2years"?n=hn(e,2):n=Ke(e,1),n.toISOString()}function qs(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function Ws(t,e="URL"){try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol))throw new Error(`Invalid protocol: ${n.protocol}`);return t}catch(n){throw new Error(`Invalid ${e}: ${t}. ${n instanceof Error?n.message:"Invalid URL format"}`)}}function Gs(t){let e={};for(let[n,r]of Object.entries(t)){if(typeof r!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof r}`);if(/<[^>]*>/.test(r))throw new Error(`Metadata value for key '${n}' must not contain HTML`);let i=r;if(i.length>1e3)throw new Error(`Metadata value for key '${n}' is too long (max 1000 characters)`);if(n.length>100)throw new Error(`Metadata key '${n}' is too long (max 100 characters)`);e[n]=i}return e}function js(t,e=!0){let n=process.env[t];if(e&&!n)throw new Error(`Required environment variable '${t}' is not set`);return n||""}function Ks(t,e){if(!t)return null;let n=`${encodeURIComponent(e)}=`,r=t.split(";");for(let i=0;i<r.length;i++){let o=r[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(n)===0)return decodeURIComponent(o.substring(n.length,o.length))}}return null}function Vh(t,e){let n=t;return n.metadata=e,n}import*as d from"valibot";var ze=new Map;function y(t,e){ze.set(t,e)}function Hh(t){return ze.has(t)}function $h(){return Array.from(ze.keys())}function qh(){ze.clear()}function A(t,e){return e?t:d.nullish(t)}var It=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 n=e.length>0?d.pipe(d.string(),...e):d.string();return A(n,t.validation?.required)},zs=t=>{let e=d.pipe(d.string(),d.email("Invalid email address"));return A(e,t.validation?.required)},Ys=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 A(e,t.validation?.required)},Js=t=>{let e=d.pipe(d.string(),d.url("Invalid URL"));return A(e,t.validation?.required)},Te=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 n=e.length>0?d.pipe(d.number(),...e):d.number();return A(n,t.validation?.required)},Mr=t=>{let e=d.boolean();return A(e,t.validation?.required)},Se=t=>{let e=d.pipe(d.string(),d.isoTimestamp("Invalid date format"));return A(e,t.validation?.required)},Hr=d.object({url:d.string(),filename:d.string(),size:d.number(),mimeType:d.nullish(d.string()),uploadedAt:d.nullish(d.string())}),Fr=t=>{let e=d.nullable(Hr);return A(e,t.validation?.required)},Vr=t=>{let e=d.array(Hr);return A(e,t.validation?.required)},$r=d.object({fullUrl:d.string(),thumbUrl:d.string()}),Xs=t=>A($r,t.validation?.required),Qs=t=>{let e=d.array($r);return A(e,t.validation?.required)},Zs=t=>{let e=d.object({lat:d.number(),lng:d.number()});return A(e,t.validation?.required)},ea=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 A(e,t.validation?.required)},ta=t=>{let e=d.record(d.string(),d.unknown());return A(e,t.validation?.required)},na=t=>{let e=d.array(d.unknown());return A(e,t.validation?.required)},mn=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.picklist(r);return A(i,t.validation?.required)}let n=d.union([d.string(),d.number()]);return A(n,t.validation?.required)},ra=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let r=e.map(o=>o.value),i=d.array(d.picklist(r));return A(i,t.validation?.required)}let n=d.array(d.string());return A(n,t.validation?.required)},ia=t=>{let e=d.pipe(d.string(),d.minLength(1,"Invalid ID format"));return A(e,t.validation?.required)},gn=t=>{let e=d.string();return A(e,t.validation?.required)},oa=t=>{let e=d.string();return A(e,t.validation?.required)},sa=t=>{let e=t.validation?.minLength??15,n=t.validation?.maxLength??34,r=t.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(e!==void 0&&i.push(d.minLength(e,`IBAN must be at least ${e} characters`)),n!==void 0&&i.push(d.maxLength(n,`IBAN must not exceed ${n} characters`)),r){let s=typeof r=="string"?new RegExp(r):r;i.push(d.regex(s,"Invalid IBAN format"))}let o=i.length>0?d.pipe(d.string(),...i):d.string();return A(o,t.validation?.required)},Br=()=>d.never(),aa=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let r=[e.checkedValue,e.uncheckedValue],i=d.picklist(r);return A(i,t.validation?.required)}let n=d.boolean();return A(n,t.validation?.required)},ca=t=>d.custom(n=>t.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),ua=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 A(e,t.validation?.required)};function la(){y("text",It),y("textarea",It),y("richtext",It),y("color",It),y("email",zs),y("password",Ys),y("url",Js),y("tel",oa),y("iban",sa),y("number",Te),y("currency",Te),y("price",ua),y("range",Te),y("year",Te),y("rating",Te),y("duration",Te),y("boolean",Mr),y("checkbox",Mr),y("gdprConsent",ca),y("date",Se),y("datetime-local",Se),y("time",Se),y("week",Se),y("month",Se),y("timestamp",Se),y("file",Fr),y("files",Vr),y("document",Fr),y("documents",Vr),y("image",Xs),y("images",Qs),y("geopoint",Zs),y("address",ea),y("map",ta),y("array",na),y("select",mn),y("multiselect",ra),y("radio",mn),y("combobox",mn),y("switch",aa),y("reference",ia),y("hidden",gn),y("avatar",gn),y("badge",gn),y("submit",Br),y("reset",Br)}la();function Ye(t){if(t.validation?.schema){let r=t.validation.schema;return A(r,t.validation?.required)}let e=ze.get(t.type);if(e){let r=e(t);if(r!==null)return r}let n=d.unknown();return A(n,t.validation?.required)}var da={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var qr=function(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},pa=function(t){let e=[],n=0,r=0;for(;n<t.length;){let i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[n++];e[r++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[n++],s=t[n++],c=t[n++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[r++]=String.fromCharCode(55296+(u>>10)),e[r++]=String.fromCharCode(56320+(u&1023))}else{let o=t[n++],s=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},Wr={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 n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];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,m=o>>2,T=(o&3)<<4|c>>4,x=(c&15)<<2|p>>6,H=p&63;u||(H=64,s||(x=64)),r.push(n[m],n[T],n[x],n[H])}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(qr(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):pa(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<t.length;){let o=n[t.charAt(i++)],c=i<t.length?n[t.charAt(i)]:0;++i;let p=i<t.length?n[t.charAt(i)]:64;++i;let T=i<t.length?n[t.charAt(i)]:64;if(++i,o==null||c==null||p==null||T==null)throw new yn;let x=o<<2|c>>4;if(r.push(x),p!==64){let H=c<<4&240|p>>2;if(r.push(H),T!==64){let ie=p<<6&192|T;r.push(ie)}}}return r},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)}}},yn=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},fa=function(t){let e=qr(t);return Wr.encodeByteArray(e,!0)},bn=function(t){return fa(t).replace(/\./g,"")},In=function(t){try{return Wr.decodeString(t,!0)}catch{}return null};function Tn(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function V(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Gr(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(V())}function jr(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Kr(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function zr(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Yr(){try{return typeof indexedDB=="object"}catch{return!1}}function Jr(){return new Promise((t,e)=>{try{let n=!0,r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{e(i.error?.message||"")}}catch(n){e(n)}})}var ha="FirebaseError",q=class t extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=ha,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,J.prototype.create)}},J=class{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r}create(e,...n){let r=n[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?ma(o,r):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new q(i,c,r)}};function ma(t,e){return t.replace(ga,(n,r)=>{let i=e[r];return i!=null?String(i):`<${r}?>`})}var ga=/\{\$([^}]+)}/g;function Tt(t){let e=[];for(let[n,r]of Object.entries(t))Array.isArray(r)?r.forEach(i=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return e.length?"&"+e.join("&"):""}function Ae(t){let e={};return t.replace(/^\?/,"").split("&").forEach(r=>{if(r){let[i,o]=r.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function Ce(t){let e=t.indexOf("?");if(!e)return"";let n=t.indexOf("#",e);return t.substring(e,n>0?n:void 0)}function Xr(t,e){let n=new En(t,e);return n.subscribe.bind(n)}var En=class{constructor(e,n){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=n,this.task.then(()=>{e(this)}).catch(r=>{this.error(r)})}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(e===void 0&&n===void 0&&r===void 0)throw new Error("Missing Observer.");va(e,["next","error","complete"])?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=vn),i.error===void 0&&(i.error=vn),i.complete===void 0&&(i.complete=vn);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 n=0;n<this.observers.length;n++)this.sendOne(n,e)}sendOne(e,n){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{n(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 va(t,e){if(typeof t!="object"||t===null)return!1;for(let n of e)if(n in t&&typeof t[n]=="function")return!0;return!1}function vn(){}var zh=14400*1e3;function Je(t){return t&&t._delegate?t._delegate:t}da.NODE_CLIENT=!0;var X=class{constructor(e,n,r){this.name=e,this.instanceFactory=n,this.type=r,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 ya=[],C;(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"})(C||(C={}));var Ea={debug:C.DEBUG,verbose:C.VERBOSE,info:C.INFO,warn:C.WARN,error:C.ERROR,silent:C.SILENT},ba=C.INFO,Ia={[C.DEBUG]:"log",[C.VERBOSE]:"log",[C.INFO]:"info",[C.WARN]:"warn",[C.ERROR]:"error"},Ta=(t,e,...n)=>{if(e<t.logLevel)return;let r=new Date().toISOString(),i=Ia[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},we=class{constructor(e){this.name=e,this._logLevel=ba,this._logHandler=Ta,this._userLogHandler=null,ya.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in C))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?Ea[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,C.DEBUG,...e),this._logHandler(this,C.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,C.VERBOSE,...e),this._logHandler(this,C.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,C.INFO,...e),this._logHandler(this,C.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,C.WARN,...e),this._logHandler(this,C.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,C.ERROR,...e),this._logHandler(this,C.ERROR,...e)}};var Sa=(t,e)=>e.some(n=>t instanceof n),Qr,Zr;function Aa(){return Qr||(Qr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ca(){return Zr||(Zr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var ei=new WeakMap,An=new WeakMap,ti=new WeakMap,Sn=new WeakMap,wn=new WeakMap;function wa(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{n(W(t.result)),i()},s=()=>{r(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(n=>{n instanceof IDBCursor&&ei.set(n,t)}).catch(()=>{}),wn.set(e,t),e}function _a(t){if(An.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{n(),i()},s=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});An.set(t,e)}var Cn={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return An.get(t);if(e==="objectStoreNames")return t.objectStoreNames||ti.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return W(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function ni(t){Cn=t(Cn)}function Ra(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(St(this),e,...n);return ti.set(r,e.sort?e.sort():[e]),W(r)}:Ca().includes(t)?function(...e){return t.apply(St(this),e),W(ei.get(this))}:function(...e){return W(t.apply(St(this),e))}}function Pa(t){return typeof t=="function"?Ra(t):(t instanceof IDBTransaction&&_a(t),Sa(t,Aa())?new Proxy(t,Cn):t)}function W(t){if(t instanceof IDBRequest)return wa(t);if(Sn.has(t))return Sn.get(t);let e=Pa(t);return e!==t&&(Sn.set(t,e),wn.set(e,t)),e}var St=t=>wn.get(t);function ii(t,e,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=W(s);return r&&s.addEventListener("upgradeneeded",u=>{r(W(s.result),u.oldVersion,u.newVersion,W(s.transaction),u)}),n&&s.addEventListener("blocked",u=>n(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 ka=["get","getKey","getAll","getAllKeys","count"],xa=["put","add","delete","clear"],_n=new Map;function ri(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(_n.get(e))return _n.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=xa.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||ka.includes(n)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),p=u.store;return r&&(p=p.index(c.shift())),(await Promise.all([p[n](...c),i&&u.done]))[0]};return _n.set(e,o),o}ni(t=>({...t,get:(e,n,r)=>ri(e,n)||t.get(e,n,r),has:(e,n)=>!!ri(e,n)||t.has(e,n)}));var Pn=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(Da(n)){let r=n.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}};function Da(t){return t.getComponent()?.type==="VERSION"}var kn="@firebase/app",oi="0.14.9";var Q=new we("@firebase/app"),Na="@firebase/app-compat",La="@firebase/analytics-compat",Ua="@firebase/analytics",Ma="@firebase/app-check-compat",Fa="@firebase/app-check",Va="@firebase/auth",Ba="@firebase/auth-compat",Ha="@firebase/database",$a="@firebase/data-connect",qa="@firebase/database-compat",Wa="@firebase/functions",Ga="@firebase/functions-compat",ja="@firebase/installations",Ka="@firebase/installations-compat",za="@firebase/messaging",Ya="@firebase/messaging-compat",Ja="@firebase/performance",Xa="@firebase/performance-compat",Qa="@firebase/remote-config",Za="@firebase/remote-config-compat",ec="@firebase/storage",tc="@firebase/storage-compat",nc="@firebase/firestore",rc="@firebase/ai",ic="@firebase/firestore-compat",oc="firebase",sc="12.10.0";var ac={[kn]:"fire-core",[Na]:"fire-core-compat",[Ua]:"fire-analytics",[La]:"fire-analytics-compat",[Fa]:"fire-app-check",[Ma]:"fire-app-check-compat",[Va]:"fire-auth",[Ba]:"fire-auth-compat",[Ha]:"fire-rtdb",[$a]:"fire-data-connect",[qa]:"fire-rtdb-compat",[Wa]:"fire-fn",[Ga]:"fire-fn-compat",[ja]:"fire-iid",[Ka]:"fire-iid-compat",[za]:"fire-fcm",[Ya]:"fire-fcm-compat",[Ja]:"fire-perf",[Xa]:"fire-perf-compat",[Qa]:"fire-rc",[Za]:"fire-rc-compat",[ec]:"fire-gcs",[tc]:"fire-gcs-compat",[nc]:"fire-fst",[ic]:"fire-fst-compat",[rc]:"fire-vertex","fire-js":"fire-js",[oc]:"fire-js-all"};var cc=new Map,uc=new Map,si=new Map;function ai(t,e){try{t.container.addComponent(e)}catch(n){Q.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function Re(t){let e=t.name;if(si.has(e))return Q.debug(`There were multiple attempts to register component ${e}.`),!1;si.set(e,t);for(let n of cc.values())ai(n,t);for(let n of uc.values())ai(n,t);return!0}function le(t){return t==null?!1:t.settings!==void 0}var lc={"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."},Dn=new J("app","Firebase",lc);var At=sc;function _e(t,e,n){let r=ac[t]??t;n&&(r+=`-${n}`);let i=r.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${r}" with version "${e}":`];i&&s.push(`library name "${r}" 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}Re(new X(`${r}-version`,()=>({library:r,version:e}),"VERSION"))}var dc="firebase-heartbeat-database",pc=1,Xe="firebase-heartbeat-store",Rn=null;function di(){return Rn||(Rn=ii(dc,pc,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(Xe)}catch{}}}}).catch(t=>{throw Dn.create("idb-open",{originalErrorMessage:t.message})})),Rn}async function fc(t){try{let n=(await di()).transaction(Xe),r=await n.objectStore(Xe).get(pi(t));return await n.done,r}catch(e){if(e instanceof q)Q.warn(e.message);else{let n=Dn.create("idb-get",{originalErrorMessage:e?.message});Q.warn(n.message)}}}async function ci(t,e){try{let r=(await di()).transaction(Xe,"readwrite");await r.objectStore(Xe).put(e,pi(t)),await r.done}catch(n){if(n instanceof q)Q.warn(n.message);else{let r=Dn.create("idb-set",{originalErrorMessage:n?.message});Q.warn(r.message)}}}function pi(t){return`${t.name}!${t.options.appId}`}var hc=1024,mc=30,xn=class{constructor(e){this.container=e,this._heartbeatsCache=null;let n=this.container.getProvider("app").getImmediate();this._storage=new On(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=ui();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(i=>i.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats.length>mc){let i=vc(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=ui(),{heartbeatsToSend:n,unsentEntries:r}=gc(this._heartbeatsCache.heartbeats),i=bn(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Q.warn(e),""}}};function ui(){return new Date().toISOString().substring(0,10)}function gc(t,e=hc){let n=[],r=t.slice();for(let i of t){let o=n.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),li(n)>e){o.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),li(n)>e){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}var On=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Yr()?Jr().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let n=await fc(this.app);return n?.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ci(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return ci(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}};function li(t){return bn(JSON.stringify({version:2,heartbeats:t})).length}function vc(t){if(t.length===0)return-1;let e=0,n=t[0].date;for(let r=1;r<t.length;r++)t[r].date<n&&(n=t[r].date,e=r);return e}function yc(t){Re(new X("platform-logger",e=>new Pn(e),"PRIVATE")),Re(new X("heartbeat",e=>new xn(e),"PRIVATE")),_e(kn,oi,t),_e(kn,oi,"esm2020"),_e("fire-js","")}yc("");function Ii(){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 Ti=Ii,Si=new J("auth","Firebase",Ii());var Pt=new we("@firebase/auth");function Ec(t,...e){Pt.logLevel<=C.WARN&&Pt.warn(`Auth (${At}): ${t}`,...e)}function _t(t,...e){Pt.logLevel<=C.ERROR&&Pt.error(`Auth (${At}): ${t}`,...e)}function Pe(t,...e){throw Qn(t,...e)}function Xn(t,...e){return Qn(t,...e)}function Ai(t,e,n){let r={...Ti(),[e]:n};return new J("auth","Firebase",r).create(e,{appName:t.name})}function Rt(t){return Ai(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Qn(t,...e){if(typeof t!="string"){let n=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=t.name),t._errorFactory.create(n,...r)}return Si.create(t,...e)}function I(t,e,...n){if(!t)throw Qn(e,...n)}function G(t){let e="INTERNAL ASSERTION FAILED: "+t;throw _t(e),new Error(e)}function kt(t,e){t||G(e)}function bc(){return fi()==="http:"||fi()==="https:"}function fi(){return typeof self<"u"&&self.location?.protocol||null}function Ic(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(bc()||Kr()||"connection"in navigator)?navigator.onLine:!0}function Tc(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var Mn=class{constructor(e,n){this.shortDelay=e,this.longDelay=n,kt(n>e,"Short delay should be less than long delay!"),this.isMobile=Gr()||zr()}get(){return Ic()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function Sc(t,e){kt(t.emulator,"Emulator should always be set here");let{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}var tt=class{static initialize(e,n,r){this.fetchImpl=e,n&&(this.headersImpl=n),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;G("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;G("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;G("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var Ac={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 Cc=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],wc=new Mn(3e4,6e4);function j(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function K(t,e,n,r,i={}){return Ci(t,i,async()=>{let o={},s={};r&&(e==="GET"?s=r:o={body:JSON.stringify(r)});let c=Tt({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 jr()||(p.referrerPolicy="no-referrer"),t.emulatorConfig&&Tn(t.emulatorConfig.host)&&(p.credentials="include"),tt.fetch()(await wi(t,t.config.apiHost,n,c),p)})}async function Ci(t,e,n){t._canInitEmulator=!1;let r={...Ac,...e};try{let i=new Fn(t),o=await Promise.race([n(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw Ct(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 Ct(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw Ct(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw Ct(t,"user-disabled",s);let m=r[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(p)throw Ai(t,m,p);Pe(t,m)}}catch(i){if(i instanceof q)throw i;Pe(t,"network-request-failed",{message:String(i)})}}async function Ht(t,e,n,r,i={}){let o=await K(t,e,n,r,i);return"mfaPendingCredential"in o&&Pe(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function wi(t,e,n,r){let i=`${e}${n}?${r}`,o=t,s=o.config.emulator?Sc(t.config,i):`${t.config.apiScheme}://${i}`;return Cc.includes(n)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function _c(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var Fn=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((n,r)=>{this.timer=setTimeout(()=>r(Xn(this.auth,"network-request-failed")),wc.get())})}};function Ct(t,e,n){let r={appName:t.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);let i=Xn(t,e,r);return i.customData._tokenResponse=n,i}function hi(t){return t!==void 0&&t.enterprise!==void 0}var Vn=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 n of this.recaptchaEnforcementState)if(n.provider&&n.provider===e)return _c(n.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 Rc(t,e){return K(t,"GET","/v2/recaptchaConfig",j(t,e))}async function Pc(t,e){return K(t,"POST","/v1/accounts:delete",e)}async function xt(t,e){return K(t,"POST","/v1/accounts:lookup",e)}function Ze(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function _i(t,e=!1){let n=Je(t),r=await n.getIdToken(e),i=Ri(r);I(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:r,authTime:Ze(Nn(i.auth_time)),issuedAtTime:Ze(Nn(i.iat)),expirationTime:Ze(Nn(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function Nn(t){return Number(t)*1e3}function Ri(t){let[e,n,r]=t.split(".");if(e===void 0||n===void 0||r===void 0)return _t("JWT malformed, contained fewer than 3 sections"),null;try{let i=In(n);return i?JSON.parse(i):(_t("Failed to decode base64 JWT payload"),null)}catch(i){return _t("Caught error parsing JWT payload as JSON",i?.toString()),null}}function mi(t){let e=Ri(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 Bn(t,e,n=!1){if(n)return e;try{return await e}catch(r){throw r instanceof q&&kc(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function kc({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var Hn=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 n=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),n}else{this.errorBackoff=3e4;let r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;let n=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},n)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var nt=class{constructor(e,n){this.createdAt=e,this.lastLoginAt=n,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ze(this.lastLoginAt),this.creationTime=Ze(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function Ot(t){let e=t.auth,n=await t.getIdToken(),r=await Bn(t,xt(e,{idToken:n}));I(r?.users.length,e,"internal-error");let i=r.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?ki(i.providerUserInfo):[],s=xc(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,p=c?u:!1,m={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 nt(i.createdAt,i.lastLoginAt),isAnonymous:p};Object.assign(t,m)}async function Pi(t){let e=Je(t);await Ot(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function xc(t,e){return[...t.filter(r=>!e.some(i=>i.providerId===r.providerId)),...e]}function ki(t){return t.map(({providerId:e,...n})=>({providerId:e,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}))}async function Oc(t,e){let n=await Ci(t,{},async()=>{let r=Tt({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await wi(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:r};return t.emulatorConfig&&Tn(t.emulatorConfig.host)&&(u.credentials="include"),tt.fetch()(s,u)});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function Dc(t,e){return K(t,"POST","/v2/accounts:revokeToken",j(t,e))}var et=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 n="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):mi(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}updateFromIdToken(e){I(e.length!==0,"internal-error");let n=mi(e);this.updateTokensAndExpiration(e,null,n)}async getToken(e,n=!1){return!n&&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,n){let{accessToken:r,refreshToken:i,expiresIn:o}=await Oc(e,n);this.updateTokensAndExpiration(r,i,Number(o))}updateTokensAndExpiration(e,n,r){this.refreshToken=n||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,n){let{refreshToken:r,accessToken:i,expirationTime:o}=n,s=new t;return r&&(I(typeof r=="string","internal-error",{appName:e}),s.refreshToken=r),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 G("not implemented")}};function te(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var de=class t{constructor({uid:e,auth:n,stsTokenManager:r,...i}){this.providerId="firebase",this.proactiveRefresh=new Hn(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=n,this.stsTokenManager=r,this.accessToken=r.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 nt(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let n=await Bn(this,this.stsTokenManager.getToken(this.auth,e));return I(n,this.auth,"internal-error"),this.accessToken!==n&&(this.accessToken=n,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),n}getIdTokenResult(e){return _i(this,e)}reload(){return Pi(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(n=>({...n})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let n=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return n.metadata._copy(this.metadata),n}_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,n=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),n&&await Ot(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(le(this.auth.app))return Promise.reject(Rt(this.auth));let e=await this.getIdToken();return await Bn(this,Pc(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,n){let r=n.displayName??void 0,i=n.email??void 0,o=n.phoneNumber??void 0,s=n.photoURL??void 0,c=n.tenantId??void 0,u=n._redirectEventId??void 0,p=n.createdAt??void 0,m=n.lastLoginAt??void 0,{uid:T,emailVerified:x,isAnonymous:H,providerData:ie,stsTokenManager:ft}=n;I(T&&ft,e,"internal-error");let D=et.fromJSON(this.name,ft);I(typeof T=="string",e,"internal-error"),te(r,e.name),te(i,e.name),I(typeof x=="boolean",e,"internal-error"),I(typeof H=="boolean",e,"internal-error"),te(o,e.name),te(s,e.name),te(c,e.name),te(u,e.name),te(p,e.name),te(m,e.name);let P=new t({uid:T,auth:e,email:i,emailVerified:x,displayName:r,isAnonymous:H,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:D,createdAt:p,lastLoginAt:m});return ie&&Array.isArray(ie)&&(P.providerData=ie.map(Y=>({...Y}))),u&&(P._redirectEventId=u),P}static async _fromIdTokenResponse(e,n,r=!1){let i=new et;i.updateFromServerResponse(n);let o=new t({uid:n.localId,auth:e,stsTokenManager:i,isAnonymous:r});return await Ot(o),o}static async _fromGetAccountInfoResponse(e,n,r){let i=n.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?ki(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new et;c.updateFromIdToken(r);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 nt(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,p),u}};var gi=new Map;function pe(t){kt(t instanceof Function,"Expected a class definition");let e=gi.get(t);return e?(kt(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,gi.set(t,e),e)}var Dt=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,n){this.storage[e]=n}async _get(e){let n=this.storage[e];return n===void 0?null:n}async _remove(e){delete this.storage[e]}_addListener(e,n){}_removeListener(e,n){}};Dt.type="NONE";var $n=Dt;function Ln(t,e,n){return`firebase:${t}:${e}:${n}`}var Nt=class t{constructor(e,n,r){this.persistence=e,this.auth=n,this.userKey=r;let{config:i,name:o}=this.auth;this.fullUserKey=Ln(this.userKey,i.apiKey,o),this.fullPersistenceKey=Ln("persistence",i.apiKey,o),this.boundEventHandler=n._onStorageEvent.bind(n),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 n=await xt(this.auth,{idToken:e}).catch(()=>{});return n?de._fromGetAccountInfoResponse(this.auth,n,e):null}return de._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 n=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,n)return this.setCurrentUser(n)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,n,r="authUser"){if(!n.length)return new t(pe($n),e,r);let i=(await Promise.all(n.map(async p=>{if(await p._isAvailable())return p}))).filter(p=>p),o=i[0]||pe($n),s=Ln(r,e.config.apiKey,e.name),c=null;for(let p of n)try{let m=await p._get(s);if(m){let T;if(typeof m=="string"){let x=await xt(e,{idToken:m}).catch(()=>{});if(!x)break;T=await de._fromGetAccountInfoResponse(e,x,m)}else T=de._fromJSON(e,m);p!==o&&(c=T),o=p;break}}catch{}let u=i.filter(p=>p._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,r):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(n.map(async p=>{if(p!==o)try{await p._remove(s)}catch{}})),new t(o,e,r))}};function vi(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(Mc(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Nc(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(Vc(e))return"Blackberry";if(Bc(e))return"Webos";if(Lc(e))return"Safari";if((e.includes("chrome/")||Uc(e))&&!e.includes("edge/"))return"Chrome";if(Fc(e))return"Android";{let n=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=t.match(n);if(r?.length===2)return r[1]}return"Other"}function Nc(t=V()){return/firefox\//i.test(t)}function Lc(t=V()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function Uc(t=V()){return/crios\//i.test(t)}function Mc(t=V()){return/iemobile/i.test(t)}function Fc(t=V()){return/android/i.test(t)}function Vc(t=V()){return/blackberry/i.test(t)}function Bc(t=V()){return/webos/i.test(t)}function xi(t,e=[]){let n;switch(t){case"Browser":n=vi(V());break;case"Worker":n=`${vi(V())}-${t}`;break;default:n=t}let r=e.length?e.join(","):"FirebaseCore-web";return`${n}/JsCore/${At}/${r}`}var qn=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,n){let r=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});r.onAbort=n,this.queue.push(r);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let n=[];try{for(let r of this.queue)await r(e),r.onAbort&&n.push(r.onAbort)}catch(r){n.reverse();for(let i of n)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}};async function Hc(t,e={}){return K(t,"GET","/v2/passwordPolicy",j(t,e))}var $c=6,Wn=class{constructor(e){let n=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=n.minPasswordLength??$c,n.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=n.maxPasswordLength),n.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=n.containsLowercaseCharacter),n.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=n.containsUppercaseCharacter),n.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=n.containsNumericCharacter),n.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=n.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 n={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,n),this.validatePasswordCharacterOptions(e,n),n.isValid&&(n.isValid=n.meetsMinPasswordLength??!0),n.isValid&&(n.isValid=n.meetsMaxPasswordLength??!0),n.isValid&&(n.isValid=n.containsLowercaseLetter??!0),n.isValid&&(n.isValid=n.containsUppercaseLetter??!0),n.isValid&&(n.isValid=n.containsNumericCharacter??!0),n.isValid&&(n.isValid=n.containsNonAlphanumericCharacter??!0),n}validatePasswordLengthOptions(e,n){let r=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;r&&(n.meetsMinPasswordLength=e.length>=r),i&&(n.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,n){this.updatePasswordCharacterOptionsStatuses(n,!1,!1,!1,!1);let r;for(let i=0;i<e.length;i++)r=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(n,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,n,r,i,o){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=n)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=o))}};var Lt=class{constructor(e,n,r,i){this.app=e,this.heartbeatServiceProvider=n,this.appCheckServiceProvider=r,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Ut(this),this.idTokenSubscription=new Ut(this),this.beforeStateQueue=new qn(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=Si,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,n){return n&&(this._popupRedirectResolver=pe(n)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Nt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(n),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 n=await xt(this,{idToken:e}),r=await de._fromGetAccountInfoResponse(this,n,e);await this.directlySetCurrentUser(r)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(le(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let n=await this.assertedPersistence.getCurrentUser(),r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(r=c.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(o){r=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return I(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let n=null;try{n=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return n}async reloadAndSetCurrentUserOrClear(e){try{await Ot(e)}catch(n){if(n?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=Tc()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(le(this.app))return Promise.reject(Rt(this));let n=e?Je(e):null;return n&&I(n.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(n&&n._clone(this))}async _updateCurrentUser(e,n=!1){if(!this._deleted)return e&&I(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),n||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return le(this.app)?Promise.reject(Rt(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return le(this.app)?Promise.reject(Rt(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(pe(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let n=this._getPasswordPolicyInternal();return n.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):n.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=await Hc(this),n=new Wn(e);this.tenantId===null?this._projectPasswordPolicy=n:this._tenantPasswordPolicies[this.tenantId]=n}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new J("auth","Firebase",e())}onAuthStateChanged(e,n,r){return this.registerStateListener(this.authStateSubscription,e,n,r)}beforeAuthStateChanged(e,n){return this.beforeStateQueue.pushCallback(e,n)}onIdTokenChanged(e,n,r){return this.registerStateListener(this.idTokenSubscription,e,n,r)}authStateReady(){return new Promise((e,n)=>{if(this.currentUser)e();else{let r=this.onAuthStateChanged(()=>{r(),e()},n)}})}async revokeAccessToken(e){if(this.currentUser){let n=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:n};this.tenantId!=null&&(r.tenantId=this.tenantId),await Dc(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,n){let r=await this.getOrInitRedirectPersistenceManager(n);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let n=e&&pe(e)||this._popupRedirectResolver;I(n,this,"argument-error"),this.redirectPersistenceManager=await Nt.create(this,[pe(n._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,n,r,i){if(this._deleted)return()=>{};let o=typeof n=="function"?n:n.next.bind(n),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof n=="function"){let u=e.addObserver(n,r,i);return()=>{s=!0,u()}}else{let u=e.addObserver(n);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=xi(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 n=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();n&&(e["X-Firebase-Client"]=n);let r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(le(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&Ec(`Error while retrieving App Check token: ${e.error}`),e?.token}};function Oi(t){return Je(t)}var Ut=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Xr(n=>this.observer=n)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var Di={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function qc(t){return Di.loadJS(t)}function Wc(){return Di.recaptchaEnterpriseScript}var Gn=class{constructor(){this.enterprise=new jn}ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},jn=class{ready(e){e()}execute(e,n){return Promise.resolve("token")}render(e,n){return""}},Gc="recaptcha-enterprise",Ni="NO_RECAPTCHA",Kn=class{constructor(e){this.type=Gc,this.auth=Oi(e)}async verify(e="verify",n=!1){async function r(o){if(!n){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)=>{Rc(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 Vn(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;hi(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(p=>{s(p)}).catch(()=>{s(Ni)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new Gn().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{r(this.auth).then(c=>{if(!n&&hi(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=Wc();u.length!==0&&(u+=c),qc(u).then(()=>{i(c,o,s)}).catch(p=>{s(p)})}}).catch(c=>{s(c)})})}};async function Qe(t,e,n,r=!1,i=!1){let o=new Kn(t),s;if(i)s=Ni;else try{s=await o.verify(n)}catch{s=await o.verify(n,!0)}let c={...e};if(n==="mfaSmsEnrollment"||n==="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 r?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 yi(t,e,n,r,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await Qe(t,e,n,n==="getOobCode");return r(t,o)}else return r(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await Qe(t,e,n,n==="getOobCode");return r(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await Qe(t,e,n);return r(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,n,!1,!0);return r(t,c)}return Promise.reject(s)})}else{let o=await Qe(t,e,n,!1,!0);return r(t,o)}else return Promise.reject(i+" provider is not supported.")}function jc(t,e){let n=e?.persistence||[],r=(Array.isArray(n)?n:[n]).map(pe);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,e?.popupRedirectResolver)}var rt=class{constructor(e,n){this.providerId=e,this.signInMethod=n}toJSON(){return G("not implemented")}_getIdTokenResponse(e){return G("not implemented")}_linkToIdToken(e,n){return G("not implemented")}_getReauthenticationResolver(e){return G("not implemented")}};async function Kc(t,e){return K(t,"POST","/v1/accounts:signUp",e)}async function zc(t,e){return Ht(t,"POST","/v1/accounts:signInWithPassword",j(t,e))}async function Yc(t,e){return Ht(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}async function Jc(t,e){return Ht(t,"POST","/v1/accounts:signInWithEmailLink",j(t,e))}var it=class t extends rt{constructor(e,n,r,i=null){super("password",r),this._email=e,this._password=n,this._tenantId=i}static _fromEmailAndPassword(e,n){return new t(e,n,"password")}static _fromEmailAndCode(e,n,r=null){return new t(e,n,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e;if(n?.email&&n?.password){if(n.signInMethod==="password")return this._fromEmailAndPassword(n.email,n.password);if(n.signInMethod==="emailLink")return this._fromEmailAndCode(n.email,n.password,n.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let n={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return yi(e,n,"signInWithPassword",zc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return Yc(e,{email:this._email,oobCode:this._password});default:Pe(e,"internal-error")}}async _linkToIdToken(e,n){switch(this.signInMethod){case"password":let r={idToken:n,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return yi(e,r,"signUpPassword",Kc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return Jc(e,{idToken:n,email:this._email,oobCode:this._password});default:Pe(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Un(t,e){return Ht(t,"POST","/v1/accounts:signInWithIdp",j(t,e))}var Xc="http://localhost",fe=class t extends rt{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let n=new t(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(n.idToken=e.idToken),e.accessToken&&(n.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(n.nonce=e.nonce),e.pendingToken&&(n.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(n.accessToken=e.oauthToken,n.secret=e.oauthTokenSecret):Pe("argument-error"),n}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:i,...o}=n;if(!r||!i)return null;let s=new t(r,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 n=this.buildRequest();return Un(e,n)}_linkToIdToken(e,n){let r=this.buildRequest();return r.idToken=n,Un(e,r)}_getReauthenticationResolver(e){let n=this.buildRequest();return n.autoCreate=!1,Un(e,n)}buildRequest(){let e={requestUri:Xc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let n={};this.idToken&&(n.id_token=this.idToken),this.accessToken&&(n.access_token=this.accessToken),this.secret&&(n.oauth_token_secret=this.secret),n.providerId=this.providerId,this.nonce&&!this.pendingToken&&(n.nonce=this.nonce),e.postBody=Tt(n)}return e}};function Qc(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 Zc(t){let e=Ae(Ce(t)).link,n=e?Ae(Ce(e)).deep_link_id:null,r=Ae(Ce(t)).deep_link_id;return(r?Ae(Ce(r)).link:null)||r||n||e||t}var Mt=class t{constructor(e){let n=Ae(Ce(e)),r=n.apiKey??null,i=n.oobCode??null,o=Qc(n.mode??null);I(r&&i&&o,"argument-error"),this.apiKey=r,this.operation=o,this.code=i,this.continueUrl=n.continueUrl??null,this.languageCode=n.lang??null,this.tenantId=n.tenantId??null}static parseLink(e){let n=Zc(e);try{return new t(n)}catch{return null}}};var ke=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,n){return it._fromEmailAndPassword(e,n)}static credentialWithLink(e,n){let r=Mt.parseLink(n);return I(r,"argument-error"),it._fromEmailAndCode(e,r.code,r.tenantId)}};ke.PROVIDER_ID="password";ke.EMAIL_PASSWORD_SIGN_IN_METHOD="password";ke.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var zn=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 xe=class extends zn{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var Oe=class t extends xe{constructor(){super("facebook.com")}static credential(e){return fe._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}}};Oe.FACEBOOK_SIGN_IN_METHOD="facebook.com";Oe.PROVIDER_ID="facebook.com";var De=class t extends xe{constructor(){super("google.com"),this.addScope("profile")}static credential(e,n){return fe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:n})}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:n,oauthAccessToken:r}=e;if(!n&&!r)return null;try{return t.credential(n,r)}catch{return null}}};De.GOOGLE_SIGN_IN_METHOD="google.com";De.PROVIDER_ID="google.com";var Ne=class t extends xe{constructor(){super("github.com")}static credential(e){return fe._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}}};Ne.GITHUB_SIGN_IN_METHOD="github.com";Ne.PROVIDER_ID="github.com";var Le=class t extends xe{constructor(){super("twitter.com")}static credential(e,n){return fe._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:n})}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:n,oauthTokenSecret:r}=e;if(!n||!r)return null;try{return t.credential(n,r)}catch{return null}}};Le.TWITTER_SIGN_IN_METHOD="twitter.com";Le.PROVIDER_ID="twitter.com";function eu(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:start",j(t,e))}function tu(t,e){return K(t,"POST","/v2/accounts/mfaEnrollment:finalize",j(t,e))}var Ei="@firebase/auth",bi="1.12.1";var Yn=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 n=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,n),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let n=this.internalListeners.get(e);n&&(this.internalListeners.delete(e),n(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function nu(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 ru(t){Re(new X("auth",(e,{options:n})=>{let r=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=r.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:r.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:xi(t)},p=new Lt(r,i,o,u);return jc(p,n),p},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,n,r)=>{e.getProvider("auth-internal").initialize()})),Re(new X("auth-internal",e=>{let n=Oi(e.getProvider("auth").getImmediate());return(r=>new Yn(r))(n)},"PRIVATE").setInstantiationMode("EXPLICIT")),_e(Ei,bi,nu(t)),_e(Ei,bi,"esm2020")}tt.initialize(fetch,Headers,Response);ru("Node");var wm=Xn("operation-not-supported-in-this-environment");Lt.prototype.setPersistence=async()=>{};function iu(t,e){return K(t,"POST","/v2/accounts/mfaSignIn:finalize",j(t,e))}var Jn=class{constructor(e){this.factorId=e}_process(e,n,r){switch(n.type){case"enroll":return this._finalizeEnroll(e,n.credential,r);case"signin":return this._finalizeSignIn(e,n.credential);default:return G("unexpected MultiFactorSessionType")}}},Ft=class{static assertionForEnrollment(e,n){return Vt._fromSecret(e,n)}static assertionForSignIn(e,n){return Vt._fromEnrollmentId(e,n)}static async generateSecret(e){let n=e;I(typeof n.user?.auth<"u","internal-error");let r=await eu(n.user.auth,{idToken:n.credential,totpEnrollmentInfo:{}});return Bt._fromStartTotpMfaEnrollmentResponse(r,n.user.auth)}};Ft.FACTOR_ID="totp";var Vt=class t extends Jn{constructor(e,n,r){super("totp"),this.otp=e,this.enrollmentId=n,this.secret=r}static _fromSecret(e,n){return new t(n,void 0,e)}static _fromEnrollmentId(e,n){return new t(n,e)}async _finalizeEnroll(e,n,r){return I(typeof this.secret<"u",e,"argument-error"),tu(e,{idToken:n,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,n){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let r={verificationCode:this.otp};return iu(e,{mfaPendingCredential:n,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}},Bt=class t{constructor(e,n,r,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=n,this.codeLength=r,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,n){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,n)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,n){let r=!1;return(wt(e)||wt(n))&&(r=!0),r&&(wt(e)&&(e=this.auth.currentUser?.email||"unknownuser"),wt(n)&&(n=this.auth.name)),`otpauth://totp/${n}:${e}?secret=${this.secretKey}&issuer=${n}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function wt(t){return typeof t>"u"||t?.length===0}import*as E from"valibot";function M(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var ne=null;function at(){return Ui().platform}function Ui(){if(ne)return ne;let t=M();if(t?.platform)return ne={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},ne;let e=[];e.push(...su()),e.push(...au()),e.push(...cu());let n=e.sort((r,i)=>i.confidence-r.confidence)[0];return!n||n.confidence<N.MINIMUM?(ne={platform:S.UNKNOWN,mode:Li(),context:uu(),metadata:{detectedAt:Date.now()}},ne):(ne={platform:n.platform,mode:Li(),context:n.context,version:lu(n.platform),metadata:{...n.metadata,detectedAt:Date.now()}},ne)}var ot=null,st=null;function Mi(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return st=!0,!0;if(st===!0)return!0;let t=M();if(t?.platform){let n=t.platform===S.NEXTJS;return n&&(st=!0),n}let e=at()===S.NEXTJS;return e&&(st=!0),e}function Fi(){if(ot!==null)return ot;let t=M();if(t?.platform)return ot=t.platform===S.VITE,ot;let e=at()===S.VITE;return ot=e,e}function F(){return typeof window<"u"&&typeof document<"u"}function Zn(){return typeof process<"u"&&!!process.versions?.node}function su(){let t=[];if(F()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:S.VITE,confidence:N.HIGH,context:k.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=M();e?.platform===S.VITE&&t.push({platform:S.VITE,confidence:N.HIGH,context:k.CLIENT}),e?.i18n?.mapping&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:k.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:S.VITE,confidence:N.LOW,context:k.CLIENT})}return Zn()&&(process.env.VITE&&t.push({platform:S.VITE,confidence:N.MEDIUM,context:k.SERVER}),process.env.npm_lifecycle_event?.includes(S.VITE)&&t.push({platform:S.VITE,confidence:N.LOW,context:k.BUILD})),t}function au(){let t=[];return Zn()&&(process.env.NEXT_RUNTIME&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:k.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:S.NEXTJS,confidence:N.MEDIUM,context:k.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:k.SERVER})),F()&&(M()?.platform===S.NEXTJS&&t.push({platform:S.NEXTJS,confidence:N.HIGH,context:k.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:S.NEXTJS,confidence:N.LOW,context:k.CLIENT})),t}function cu(){let t=[];try{typeof globalThis<"u"&&globalThis.expo?.Constants?.expoConfig&&t.push({platform:S.EXPO,confidence:N.HIGH,context:k.CLIENT})}catch{}try{typeof globalThis<"u"&&globalThis.Platform?.OS&&!F()&&t.push({platform:S.REACT_NATIVE,confidence:N.MEDIUM,context:k.CLIENT})}catch{}let e=M();return e?.platform===S.EXPO?t.push({platform:S.EXPO,confidence:N.HIGH,context:k.CLIENT}):e?.platform===S.REACT_NATIVE&&t.push({platform:S.REACT_NATIVE,confidence:N.HIGH,context:k.CLIENT}),t}function Li(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===oe.PRODUCTION?oe.PRODUCTION:t===oe.TEST?oe.TEST:oe.DEVELOPMENT}function uu(){return F()?k.CLIENT:Zn()?oe.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?k.BUILD:k.SERVER:k.CLIENT}function lu(t){if(!(typeof process>"u"))return t===S.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===S.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 Vi(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function du(t){let e,n=M();return n?.env&&typeof n.env=="object"&&(e=n.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Vi(e)}function pu(t){let e=M(),n;return e?.env&&typeof e.env=="object"&&(n=e.env[t]),n===void 0&&typeof process<"u"&&process.env&&(n=process.env[t]),Vi(n)}function L(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=M();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 n=M()?.platform,r=e||n||(Fi()?"vite":Mi()?"nextjs":at()),i=["MODE","DEV","PROD","SSR"],o;return r==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:r==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,r==="vite"?du(o):r==="nextjs"?pu(o):void 0}function Z(){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=L("APP_ENV"),e=L("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var Bi=E.object({name:E.string(),color:E.string(),icon:E.string(),button:E.object({backgroundColor:E.string(),textColor:E.string(),borderColor:E.string(),hoverBackgroundColor:E.string(),focusOutlineColor:E.string(),fontWeight:E.optional(E.string(),"500")})}),fu=E.object({...Bi.entries,type:E.picklist(["auth","both"]),scopes:E.optional(E.array(E.string())),firebaseProviderId:E.optional(E.string())}),$t=E.union([E.literal(""),E.pipe(E.string(),E.url())]),hu=E.object({authUrl:$t,tokenUrl:$t,profileUrl:$t,revokeUrl:E.optional($t)}),mu=E.object({authentication:E.optional(E.array(E.string())),"api-access":E.array(E.string())}),pv=E.object({...Bi.entries,type:E.picklist(["oauth","both"]),scopes:mu,endpoints:hu}),ct=null;function gu(){let t=[];for(let[e,n]of Object.entries(Ee))E.safeParse(fu,n).success?t.push(e):typeof window<"u"&&Z();return t}function qt(){if(ct!==null)return ct;let t=L("AUTH_PARTNERS");if(!t)return ct=[],ct;let e=gu(),n=t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>e.includes(r));return ct=n,n}function ut(t){return typeof t=="object"&&t!==null&&"currentUser"in t&&typeof t.currentUser=="object"&&t.currentUser!==null}var vu=12e4,er=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,n={}){this.authInstance=e,this.refreshBuffer=n.refreshBufferMs??vu,this.maxRefreshAttempts=n.maxRefreshAttempts??3,this.autoRefresh=n.autoRefresh!==!1,this.onTokenExpired=n.onTokenExpired,this.onFatalError=n.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let n=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:n},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 n=await e.getIdToken(!0),r=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:n,expiresAt:r}),this.refreshAttempts=0,n}else if(e&&typeof e.getIdTokenResult=="function"){let n=await e.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}if(ut(this.authInstance)){let n=await this.authInstance.currentUser.getIdTokenResult(!0),r=new Date(n.expirationTime);return this.updateTokenInfo({token:n.token,expiresAt:r}),this.refreshAttempts=0,n.token}throw v(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(n){return this.handleError(n instanceof Error?n:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:n}=this.tokenInfo;if(e==="valid")return n;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(ut(this.authInstance))return await this.forceRefresh(this.authInstance.currentUser)}catch(r){this.handleError(r instanceof Error?r:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:n}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let n={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},r=this.calculateTokenStatus(n.expiresAt);this.tokenInfo={...n,status:r},this.autoRefresh&&n.expiresAt&&this.scheduleRefresh(n.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let n=new Date;if(n>=e)return"expired";let r=new Date(e.getTime()-this.refreshBuffer);return n>=r?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let n=new Date,r=e.getTime()-n.getTime()-this.refreshBuffer;if(r<=0){ut(this.authInstance)&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{ut(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},r)}handleRefreshError(e){if(Z(),this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let n=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);Z(),setTimeout(()=>{ut(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(r=>{this.handleRefreshError(r)}):this.refreshCallback&&this.refreshCallback().catch(r=>{this.handleRefreshError(r)})},n)}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){Z(),this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},Dv=Ge(er,null,{});var Wt=class{buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){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:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var he=null,yu="dndev-keys",lt="encryption-keys",Hi="main";async function $i(){return new Promise((t,e)=>{let n=indexedDB.open(yu,1);n.onupgradeneeded=()=>{n.result.createObjectStore(lt)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Eu(t){let e=await $i();return new Promise((n,r)=>{let i=e.transaction(lt,"readwrite");i.objectStore(lt).put(t,Hi),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async function bu(){try{let t=await $i();return new Promise((e,n)=>{let i=t.transaction(lt,"readonly").objectStore(lt).get(Hi);i.onsuccess=()=>e(i.result??null),i.onerror=()=>n(i.error)})}catch{return null}}async function Iu(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw v(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function qi(){if(he)return he;try{let t=await bu();return t?(he=t,he):(he=await Iu(),await Eu(he),he)}catch(t){throw v(t,{userMessage:"Failed to get or create encryption key"})}}async function Wi(t){try{let e=await qi(),n=window.crypto.getRandomValues(new Uint8Array(12)),r=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(r),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,o),c=new Uint8Array(n.length+s.byteLength);return c.set(n,0),c.set(new Uint8Array(s),n.length),btoa(String.fromCharCode(...c))}catch(e){throw v(e,{userMessage:"Failed to encrypt data"})}}async function Gi(t){try{let e=await qi(),n=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),r=n.slice(0,12),i=n.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r},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 Wt{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,n={}){let{scope:r="user",encryption:i=!1}=n,o=this.buildKey(e,r,this.userId,!0);if(!o)return null;try{if(!F())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 Gi(u)),u}catch(s){throw v(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:n}})}}async set(e,n,r={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=r,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=n;o&&(u=await Wi(n));let p=s>0?new Date(Date.now()+s*1e3).toISOString():null,m=JSON.stringify({value:u,expiresAt:p,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,m)}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:r}})}}async remove(e){let n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,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 n=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(n));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var dt=class{localStrategy;userId;apiEndpoint;getAuthToken;constructor(e,n="/api/storage",r){if(!e)throw v("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=n,this.getAuthToken=r}async buildHeaders(e){let n={};if(e&&(n["Content-Type"]=e),this.getAuthToken){let r=await this.getAuthToken();r&&(n.Authorization=`Bearer ${r}`)}return n}async get(e,n={}){try{let r=await this.localStrategy.get(e,n);return r!==null?r:await this.getFromCloud(e,n)}catch(r){try{return await this.localStrategy.get(e,n)}catch(i){throw v(r,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:n,fallbackError:i}})}}}async set(e,n,r={}){try{await this.localStrategy.set(e,n,r),this.setToCloud(e,n,r).catch(i=>{})}catch(i){throw v(i,{userMessage:"Failed to store data",context:{key:e,options:r}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(n=>{})}catch(n){throw v(n,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(n=>{})}catch(n){throw v(n,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,n,r,i=!1){let o="dndev";switch(n){case"user":if(!r){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:n}})}return`${o}:user:${r}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,n){try{let{scope:r="user"}=n,i=this.buildKey(e,r,this.userId,!0);if(!i)return null;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{headers:await this.buildHeaders()});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,n).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,n,r){let{scope:i="user",expiry:o=0}=r,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:n,expiresAt:c,createdAt:new Date().toISOString()},p=await fetch(`${this.apiEndpoint}/${encodeURIComponent(s)}`,{method:"PUT",headers:await this.buildHeaders("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 n=["user","global","session"];for(let r of n)try{let i=this.buildKey(e,r,this.userId,!0);if(!i)continue;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE",headers:await this.buildHeaders()});!o.ok&&o.status}catch{}}async clearFromCloud(e){try{let n=new URLSearchParams;e&&n.append("scope",e),e==="user"&&n.append("userId",this.userId);let r=n.toString(),i=r?`${this.apiEndpoint}/clear?${r}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE",headers:await this.buildHeaders()})).ok}catch{}}};var Gt=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{Z()}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,n){this.initialize(),n&&e?this.strategy=new dt(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new dt(this.userId):this.strategy=new re(this.userId)}async get(e,n={}){return this.initialize(),this.strategy.get(e,n)}async set(e,n,r={}){return this.initialize(),this.strategy.set(e,n,r)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,n,r={}){return this.initialize(),this.set(e,n,{...r,encryption:!0})}async getSecure(e,n={}){return this.initialize(),this.get(e,{...n,encryption:!0})}},Tu=Ge(Gt);var B={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function me(t){return!!t&&t.trim()!==""}var hy={[B.AUTH]:()=>qt().length>0,[B.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=>me(L(e))),[B.I18N]:()=>!0,[B.BILLING]:()=>!!(me(L("STRIPE_PUBLISHABLE_KEY"))||me(L("BILLING_ENABLED"))&&L("BILLING_ENABLED")==="true"),[B.ROUTES]:()=>!0,[B.THEMES]:()=>!0,[B.COMPONENTS]:()=>!0,[B.CRUD]:()=>!0,[B.FORMS]:()=>!0,[B.REALTIME]:()=>!!(me(L("REALTIME_ENABLED"))&&L("REALTIME_ENABLED")==="true"||me(L("FIREBASE_CONFIG"))),[B.STORAGE]:()=>!!(me(L("STORAGE_ENABLED"))&&L("STORAGE_ENABLED")==="true"||me(L("FIREBASE_CONFIG")))};var Vu=fr(cr(),1);var Bu=fr(cr(),1);var ur=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!1,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}once(e,n,r){if(typeof n!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:n,once:!0,context:r};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,n)}}off(e,n){let r=this.events.get(e);if(!r||r.length===0)return!1;let i=r.findIndex(o=>o.handler===n);return i===-1?!1:(r.splice(i,1),r.length===0&&this.events.delete(e),!0)}emit(e,...n){this.cacheEvent(e,n);let r=this.events.get(e);if(!r||r.length===0)return!1;let i=[...r],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,n):s.handler(...n),s.once&&o.push(s)}catch(c){v(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:n},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 n=this.events.get(e);return!!n&&n.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let n=this.events.get(e);return n?n.map(r=>r.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 n=this.events.get(e);return n||(n=[],this.events.set(e,n)),n}checkListenerCount(e){let n=this.listenerCount(e);this.maxListeners!==1/0&&n>this.maxListeners}cacheEvent(e,n){let r=this.eventCache.get(e);r||(r=[],this.eventCache.set(e,r)),r.push({data:n,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let n=this.eventCache.get(e);return!n||n.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,n=null,r=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(n===null||c.timestamp<n)&&(n=c.timestamp),(r===null||c.timestamp>r)&&(r=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:n,newestEvent:r,memoryEstimate:i}}cleanupCache(e){let n=Date.now()-this.cacheTTL;if(e){let r=this.eventCache.get(e);if(r){let i=r.filter(o=>o.timestamp>n);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[r,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>n);o.length===0?this.eventCache.delete(r):this.eventCache.set(r,o)}}},Qy=new ur;var iE={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},setRememberMe:async()=>{},error:null,emailVerification:{status:"pending"},getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:He.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:O.GUEST,userTier:Be.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},oE={status:He.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},sE={status:He.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},aE={status:He.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var io=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function oo(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function Kt(t,e=""){if(Array.isArray(t))t.forEach((n,r)=>{let i=`${e}[${r}]`;if(typeof n=="string"&&oo(n)){if(!io.test(n))throw v(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${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&&Kt(n,i)});else if(typeof t=="object"&&t!==null)for(let[n,r]of Object.entries(t)){let i=e?`${e}.${n}`:n;if(typeof r=="string"&&oo(r)){if(!io.test(r))throw v(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${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&&Kt(r,i)}}import*as ao from"valibot";var lr={};function HE(t){lr.uniqueConstraintValidator=t}async function so(t,e,n){let{uniqueFields:r=[],collection:i}=t.metadata;r.length!==0&&lr.uniqueConstraintValidator&&await Promise.all(r.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await lr.uniqueConstraintValidator.checkDuplicate(i,o,c,n))throw v(new Error(s||`${o} must be unique`),{userMessage:s||`${o} must be unique`,context:{field:o}})}))}async function GE(t,e,n,r){ao.parse(t,e),Kt(e),await so(t,e,r),t.metadata.customValidate&&await t.metadata.customValidate(e,n)}function Hu(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function eb(t){if(!Hu(t)){let e=t,n=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:n}})}return t.metadata.collection}var dr=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],rb="available",ib=["draft","deleted"],Fe=["id","createdAt","updatedAt","createdById","updatedById"],$u=[...Fe,"status"];function ob(t){return $u.includes(t)}function sb(t){return Fe.includes(t)}var R={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...dr]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},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}}};var qu=new Set(["__proto__","constructor","prototype"]);function Wu(t){for(let e of Object.keys(t.fields))if(qu.has(e))throw v(new Error(`Field name '${e}' in entity '${t.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${e}' in entity '${t.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:t.name,fieldName:e,operation:"defineEntity"},severity:"error"})}function Gu(t){let e=t.field.endsWith("Id")?t.field.slice(0,-2):t.field,n=t.collection||(e.endsWith("y")?e.slice(0,-1)+"ies":e+"s");return{name:t.field,label:`crud:fields.${t.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:n}}}function ju(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let n=t.map(i=>({value:i.value,label:i.label})),r=new Set(t.map(i=>i.value));for(let i of e)r.has(i.value)||n.push(i);return n}function Ku(t,e){if(!(!t.uniqueKeys||t.uniqueKeys.length===0))for(let n=0;n<t.uniqueKeys.length;n++){let r=t.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw v(new Error(`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' must have at least one field`,context:{entityName:t.name,uniqueKeyIndex:n},severity:"error"});let i=r.fields.filter(o=>!e.has(o));if(i.length>0)throw v(new Error(`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:t.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function zu(t){let{form:e,fields:n}=t,r=Object.keys(n);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=>!r.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);r.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(m=>m.field):[i.condition.field]).filter(m=>!r.includes(m));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(m=>!r.includes(m));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(n).forEach(([i,o])=>{if(o.dependsOn&&!r.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 Yu(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 db(t){try{Wu(t),zu(t);let e=Yu(t),n={...t.fields,...R,...t.fields.createdAt&&{createdAt:{...R.createdAt,...t.fields.createdAt,type:R.createdAt.type,visibility:R.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...R.updatedAt,...t.fields.updatedAt,type:R.updatedAt.type,visibility:R.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...R.createdById,...t.fields.createdById,type:R.createdById.type,visibility:R.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...R.updatedById,...t.fields.updatedById,type:R.updatedById.type,visibility:R.updatedById.visibility}},...t.fields.status&&{status:{...R.status,...t.fields.status,type:R.status.type,visibility:R.status.visibility,editable:R.status.editable,validation:{...R.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:ju(dr,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:Gu(t.scope)}};if(t.listFields){let o=new Set(Object.keys(n)),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(n)),c=je(t).filter(u=>!o.has(u));if(c.length>0)throw v(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${c.join(", ")}`,context:{entityName:t.name,invalidFields:c,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let o=new Set(Object.keys(n));Ku(t,o)}let r={...Qt,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:n,access:r,namespace:i,...t.search&&{search:t.search},...t.defaultSort&&{defaultSort:t.defaultSort}}}catch(e){throw v(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}import*as z from"valibot";function pt(t,e){return Object.assign(t,{visibility:e})}function ge(t,e){let n=t;return n.metadata={collection:e.collection,entity:e.name,...e.uniqueKeys&&{uniqueKeys:e.uniqueKeys}},n}function co(t){let e=Ye(t);return pt(e,t.visibility)}function uo(t){let e=Ye({...t,validation:{...t.validation,required:!1}});return pt(e,t.visibility)}function vb(t){let e=t.fields,n={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(n[D]=co(P));let r=ge(z.object(n),t),i={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(Fe.includes(D)||(i[D]=co(P)));let o=ge(z.object(i),t),s={};for(let[D,P]of Object.entries(e))if(P.visibility!=="hidden"&&!Fe.includes(D))if(D==="status"){let Y=z.literal("draft");s[D]=pt(Y,P.visibility)}else s[D]=uo(P);let c=ge(z.object(s),t),u={};for(let[D,P]of Object.entries(e))P.visibility!=="hidden"&&(Fe.includes(D)||(u[D]=uo(P)));u.id=pt(Ye(R.id),"technical");let p=ge(z.object(u),t),m;if(t.listFields&&t.listFields.length>0){let D=["id","status"],P=[...new Set([...D,...t.listFields])];m={};for(let Y of P){let Ve=n[Y];Ve&&(m[Y]=Ve)}}else m=n;let T=ge(z.object(m),t),x,H=je(t);if(H.length>0){let D=["id","status"],P=[...new Set([...D,...H])];x={};for(let Y of P){let Ve=n[Y];Ve&&(x[Y]=Ve)}}else x=n;let ie=ge(z.object(x),t),ft=ge(z.object({id:pt(Ye(R.id),"technical")}),t);return{create:o,draft:c,update:p,get:r,list:T,listCard:ie,delete:ft}}function Eb(t,e,n=1,r=!1){let i=[];if(r)for(let o=e;o>=t;o-=n)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=n)i.push({value:String(o),label:String(o)});return i}var ve=new Map;function Ib(t,e){ve.has(t),ve.set(t,e)}function Tb(t){ve.delete(t)}function Sb(t){let e=ve.get(t);return e?e():null}function Ab(t){return ve.has(t)}function Cb(){return Array.from(ve.keys())}function wb(){ve.clear()}export{ed as AGGREGATE_FILTER_OPERATORS,Zl as AGGREGATE_OPERATIONS,Cd as AUTH_EVENTS,Ee as AUTH_PARTNERS,Ol as AUTH_PARTNER_STATE,bt as AuthHardening,Ir as AuthUserSchema,Fe as BACKEND_GENERATED_FIELD_NAMES,_d as BILLING_EVENTS,So as BREAKPOINT_RANGES,en as BREAKPOINT_THRESHOLDS,hr as COMMON_TIER_CONFIGS,N as CONFIDENCE_LEVELS,wr as CONSENT_CATEGORY,k as CONTEXTS,se as CRUD_OPERATORS,cn as CURRENCY_MAP,br as CheckoutSessionMetadataSchema,Ie as ConditionBuilder,mr as CreateCheckoutSessionRequestSchema,gr as CreateCheckoutSessionResponseSchema,Tr as CustomClaimsSchema,Qt as DEFAULT_ENTITY_ACCESS,ae as DEFAULT_ERROR_MESSAGES,Yd as DEFAULT_LAYOUT_PRESET,dr as DEFAULT_STATUS_OPTIONS,rb as DEFAULT_STATUS_VALUE,sl as DEFAULT_SUBSCRIPTION,xp as DENSITY,_ as DoNotDevError,Kl as EDITABLE,xl as EMAIL_VERIFICATION_STATUS,mt as ENTITY_HOOK_ERRORS,oe as ENVIRONMENTS,$e as ERROR_CODES,bd as ERROR_SEVERITY,Id as ERROR_SOURCE,Sr as EntityHookError,Yt as FEATURES,Op as FEATURE_CONSENT_MATRIX,He as FEATURE_STATUS,Jl as FIELD_TYPES,Zt as FIREBASE_ERROR_MAP,Ar as GITHUB_PERMISSION_LEVELS,ib as HIDDEN_STATUSES,Jd as LAYOUT_PRESET,Yl as LIST_SCHEMA_TYPE,Pd as OAUTH_EVENTS,nn as OAUTH_PARTNERS,zl as ORDER_DIRECTION,yp as PARTNER_ICONS,xd as PAYLOAD_EVENTS,Jt as PERMISSIONS,S as PLATFORMS,ql as PWA_ASSET_TYPES,$l as PWA_DISPLAY_MODES,bo as ProductDeclarationSchema,ml as ProductDeclarationsSchema,Wl as ROUTE_SOURCES,Hl as STORAGE_SCOPES,Bl as STORAGE_TYPES,Dd as STRIPE_EVENTS,ht as STRIPE_MODES,il as SUBSCRIPTION_DURATIONS,ye as SUBSCRIPTION_STATUS,Be as SUBSCRIPTION_TIERS,Ur as ServerUtils,pn as SingletonManager,To as StripeBackConfigSchema,Io as StripeFrontConfigSchema,yo as StripePaymentSchema,Eo as StripeSubscriptionSchema,yr as SubscriptionClaimsSchema,vr as SubscriptionDataSchema,$u as TECHNICAL_FIELD_NAMES,O as USER_ROLES,Xt as UserSubscriptionSchema,jl as VISIBILITY,Er as WebhookEventSchema,Ke as addMonths,hn as addYears,ea as addressSchema,na as arraySchema,R as baseFields,Mr as booleanSchema,$s as calculateSubscriptionEndDate,sn as captureErrorToSentry,cp as checkGitHubAccessSchema,qh as clearSchemaGenerators,wb as clearScopeProviders,qe as commonErrorCodeMappings,un as compactToISOString,Ss as configureProviders,Rs as createAsyncSingleton,ol as createDefaultSubscriptionClaims,Dl as createDefaultUserProfile,sd as createEntitySchema,$ as createErrorHandler,Qo as createMetadata,Ps as createMethodProxy,vb as createSchemas,Ge as createSingleton,_s as createSingletonWithParams,Se as dateSchema,db as defineEntity,ud as deleteEntitySchema,rn as detectErrorSource,dp as disconnectOAuthSchema,zs as emailSchema,Vh as enhanceSchema,jo as ensureSpreadable,ue as evaluateCondition,Vs as evaluateFieldConditions,up as exchangeTokenSchema,Fr as fileSchema,Vr as filesSchema,Ns as filterVisibleFields,es as formatCurrency,kr as formatDate,as as formatRelativeTime,ca as gdprConsentSchema,Or as generateCodeChallenge,xr as generateCodeVerifier,fs as generateFirestoreRuleCondition,ms as generatePKCEPair,Zs as geopointSchema,Ao as getBreakpointFromWidth,Kd as getBreakpointUtils,eb as getCollectionName,Hs as getConditionDependencies,pp as getConnectionsSchema,Pr as getCurrencyLocale,Zo as getCurrencySymbol,rs as getCurrentTimestamp,ad as getEntitySchema,je as getListCardFieldNames,As as getProvider,$h as getRegisteredSchemaTypes,Cb as getRegisteredScopeProviders,Is as getRoleFromClaims,Ye as getSchemaType,Sb as getScopeValue,fn as getVisibleFields,ss as getWeekFromISOString,Co as githubPermissionSchema,tn as githubRepoConfigSchema,sp as grantGitHubAccessSchema,v as handleError,Hh as hasCustomSchemaGenerator,Hu as hasMetadata,Cs as hasProvider,Ls as hasRestrictedVisibility,yt as hasRoleAccess,Ab as hasScopeProvider,Ts as hasTierAccess,sa as ibanSchema,Do as isAuthPartnerId,sb as isBackendGeneratedField,jd as isBreakpoint,ln as isCompactDateString,Lr as isFieldVisible,ob as isFrameworkField,No as isOAuthPartnerId,gs as isPKCESupported,ts as isoToCompactString,bs as lazyImport,ld as listEntitiesSchema,ta as mapSchema,ce as mapToDoNotDevError,hs as maybeTranslate,ra as multiselectSchema,Br as neverSchema,ns as normalizeToISOString,Te as numberSchema,Zu as overrideFeatures,rl as overridePaymentModes,el as overridePermissions,nl as overrideSubscriptionStatus,Qu as overrideSubscriptionTiers,Xu as overrideUserRoles,dn as parseDate,us as parseDateToNoonUTC,qs as parseISODate,Ks as parseServerCookie,Ys as passwordSchema,Xs as pictureSchema,Qs as picturesSchema,ua as priceSchema,Eb as rangeOptions,ia as referenceSchema,lp as refreshTokenSchema,y as registerSchemaGenerator,Ib as registerScopeProvider,HE as registerUniqueConstraintValidator,ws as resetProviders,ap as revokeGitHubAccessSchema,Go as safeValidate,mn as selectSchema,Bo as showNotification,gn as stringSchema,aa as switchSchema,oa as telSchema,It as textSchema,os as timestampToISOString,ls as toDateOnly,is as toISOString,zo as translateArray,Jo as translateArrayRange,Xo as translateArrayWithIndices,Yo as translateObjectArray,Tb as unregisterScopeProvider,cd as updateEntitySchema,ks as updateMetadata,Js as urlSchema,bp as validateAuthPartners,Pl as validateAuthSchemas,wl as validateAuthUser,yl as validateBillingSchemas,hl as validateCheckoutSessionMetadata,ys as validateCodeChallenge,vs as validateCodeVerifier,ul as validateCreateCheckoutSessionRequest,ll as validateCreateCheckoutSessionResponse,Rl as validateCustomClaims,Kt as validateDates,GE as validateDocument,js as validateEnvVar,Gs as validateMetadata,Ip as validateOAuthPartners,vl as validateStripeBackConfig,gl as validateStripeFrontConfig,pl as validateSubscriptionClaims,dl as validateSubscriptionData,so as validateUniqueFields,Ws as validateUrl,_l as validateUserSubscription,fl as validateWebhookEvent,Wo as validateWithSchema,Bs as when,Vo as withErrorHandling,Es as withGracefulDegradation,qo as wrapAuthError,Ho as wrapCrudError,$o as wrapStorageError};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
react/cjs/react.production.js:
|