@donotdev/core 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.js CHANGED
@@ -1 +1,384 @@
1
- var ht=Object.defineProperty;var vt=(e,t)=>()=>(e&&(t=e(e=0)),t);var yt=(e,t)=>{for(var r in t)ht(e,r,{get:t[r],enumerable:!0})};import{Buffer as p}from"node:buffer";import{createRequire as bt}from"node:module";import{dirname as St,resolve as Zr}from"node:path";import l from"node:process";import{fileURLToPath as Et}from"node:url";var xt,u,m,i=vt(()=>{"use strict";xt=bt(import.meta.url),u=Et(import.meta.url),m=St(u);typeof globalThis<"u"&&(globalThis.require=xt,globalThis.__filename=u,globalThis.__dirname=m,globalThis.Buffer=p,globalThis.process=l,typeof global>"u"&&(globalThis.global=globalThis))});i();var et={};yt(et,{DEFAULT_ERROR_MESSAGES:()=>H,DoNotDevError:()=>D,SingletonManager:()=>Ce,addMonths:()=>Z,addYears:()=>Ae,calculateSubscriptionEndDate:()=>Er,captureErrorToSentry:()=>xe,commonErrorCodeMappings:()=>X,compactToISOString:()=>ce,createAsyncSingleton:()=>fr,createErrorHandler:()=>L,createMetadata:()=>kt,createMethodProxy:()=>hr,createSingleton:()=>mr,createSingletonWithParams:()=>gr,detectErrorSource:()=>be,filterVisibleFields:()=>Sr,formatDate:()=>we,formatRelativeTime:()=>Nt,generateCodeChallenge:()=>Xe,generateCodeVerifier:()=>Ke,generatePKCEPair:()=>ar,getCurrentTimestamp:()=>_t,getVisibleFields:()=>Ie,getWeekFromISOString:()=>Dt,handleError:()=>O,hasRoleAccess:()=>ie,hasTierAccess:()=>pr,isCompactDateString:()=>le,isFieldVisible:()=>Je,isPKCESupported:()=>sr,isoToCompactString:()=>Rt,lazyImport:()=>dr,mapToDoNotDevError:()=>Ee,maybeTranslate:()=>or,normalizeToISOString:()=>Pt,parseDate:()=>ue,parseDateToNoonUTC:()=>Ut,parseISODate:()=>xr,parseServerCookie:()=>Ar,showNotification:()=>ir,timestampToISOString:()=>Ot,toDateOnly:()=>Mt,toISOString:()=>wt,translateArray:()=>Tt,translateArrayRange:()=>It,translateArrayWithIndices:()=>At,translateObjectArray:()=>Ct,updateMetadata:()=>vr,validateCodeChallenge:()=>lr,validateCodeVerifier:()=>cr,validateEnvVar:()=>Ir,validateMetadata:()=>Cr,validateUrl:()=>Tr,withErrorHandling:()=>nr,withGracefulDegradation:()=>ur});i();i();i();function Tt(e,t,r,o={}){let{minLength:s=0,excludeEmpty:d=!0,customFilter:C}=o;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return e(R)}).filter((A,P)=>{let R=`${t}.${P}`;return!(A===R||d&&A.trim()===""||A.length<s||C&&!C(A,P))})}function Ct(e,t,r,o){return Array.from({length:r},(s,d)=>{let C=`${t}.${d}.${String(o[0])}`;if(e(C)===C)return null;let P={};for(let R of o){let I=`${t}.${d}.${String(R)}`;P[R]=e(I)}return P}).filter(s=>s!==null)}function It(e,t,r,o,s={}){let{minLength:d=0,excludeEmpty:C=!0,customFilter:A}=s;return Array.from({length:o-r},(P,R)=>{let I=r+R,U=`${t}.${I}`;return e(U)}).filter((P,R)=>{let I=r+R,U=`${t}.${I}`;return!(P===U||C&&P.trim()===""||P.length<d||A&&!A(P,I))})}function At(e,t,r,o={}){let{minLength:s=0,excludeEmpty:d=!0,customFilter:C}=o;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return{item:e(R),originalIndex:P}}).filter(({item:A,originalIndex:P})=>{let R=`${t}.${P}`;return!(A===R||d&&A.trim()===""||A.length<s||C&&!C(A,P))})}i();function kt(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}i();function ce(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let r=t[1],o=t[2],s=t[3],d=t[4],C=t[5],A=new Date(parseInt(r,10),parseInt(o,10)-1,parseInt(s,10),parseInt(d,10),parseInt(C,10));if(isNaN(A.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return A.toISOString()}function Rt(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),d=String(t.getUTCHours()).padStart(2,"0"),C=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${o}${s}:${d}${C}`}function le(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function Pt(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(le(e))return ce(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")return t.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof e}`)}function _t(){return new Date().toISOString()}function wt(e){return e.toISOString()}function Ot(e){return new Date(e).toISOString()}function Dt(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=new Date(t.getFullYear(),0,1),o=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((o+r.getDay()+1)/7)}, ${t.getFullYear()}`}var M={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Nt(e,t="en",r={}){if(!e)return"";let{style:o="long",numeric:s="auto",fallbackThreshold:d=M.WEEK}=r,C;if(e instanceof Date)C=e;else if(typeof e=="string")C=new Date(e);else if(typeof e=="number")C=new Date(e);else if(typeof e=="object"&&"toDate"in e)C=e.toDate();else return"";if(isNaN(C.getTime()))return"";let A=new Date,P=C.getTime()-A.getTime(),R=Math.round(P/1e3),I=Math.abs(R);if(I>d)return we(C.toISOString(),t);let U=new Intl.RelativeTimeFormat(t,{style:o,numeric:s});return I<M.MINUTE?U.format(R,"second"):I<M.HOUR?U.format(Math.round(R/M.MINUTE),"minute"):I<M.DAY?U.format(Math.round(R/M.HOUR),"hour"):I<M.WEEK?U.format(Math.round(R/M.DAY),"day"):I<M.MONTH?U.format(Math.round(R/M.WEEK),"week"):I<M.YEAR?U.format(Math.round(R/M.MONTH),"month"):U.format(Math.round(R/M.YEAR),"year")}function Ft(e){switch(e){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 we(e,t="en",r="long"){if(!e)return"";let o;if(e instanceof Date)o=e;else if(typeof e=="string")o=new Date(e);else if(typeof e=="number")o=new Date(e);else if(typeof e=="object"&&"toDate"in e)o=e.toDate();else return"";if(isNaN(o.getTime()))return"";let s=typeof r=="string"?Ft(r):r;return new Intl.DateTimeFormat(t,s).format(o)}function ue(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(le(t))try{return ce(t)}catch{return}let r=new Date(t);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")try{let r=t.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,r=t.seconds*1e3+(t.nanoseconds||0)/1e6,o=new Date(r);return isNaN(o.getTime())?void 0:o.toISOString()}}}function Ut(e){let t=ue(e);if(!t)return;let r=new Date(t);return r.setUTCHours(12,0,0,0),r.toISOString()}function Mt(e){let t=ue(e);return t&&t.split("T")[0]||""}i();i();i();i();i();var q={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function cn(e){Object.assign(q,e)}var de={FREE:"free",PRO:"pro",PREMIUM:"premium"};function ln(e){Object.assign(de,e)}var pe={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function un(e){Object.assign(pe,e)}var me={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 dn(e){Object.assign(me,e)}i();import*as a from"valibot";i();i();var G={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function gn(e){Object.assign(G,e)}var te={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function fn(e){Object.assign(te,e)}var hn={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function vn(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var Oe={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}},yn={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};i();import*as n from"valibot";var De=n.object({userId:n.string(),productId:n.optional(n.string()),priceId:n.string(),successUrl:n.pipe(n.string(),n.url()),cancelUrl:n.pipe(n.string(),n.url()),customerEmail:n.optional(n.pipe(n.string(),n.email())),userEmail:n.optional(n.pipe(n.string(),n.email())),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean()),mode:n.optional(n.picklist([te.PAYMENT,te.SUBSCRIPTION]))}),Ne=n.object({sessionId:n.string(),sessionUrl:n.nullable(n.pipe(n.string(),n.url()))}),Fe=n.object({userId:n.string(),tier:n.string(),status:n.picklist(Object.values(G)),subscriptionId:n.nullable(n.string()),customerId:n.string(),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp())}),Ue=n.object({tier:n.string(),subscriptionId:n.nullable(n.string()),customerId:n.string(),status:n.picklist(Object.values(G)),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp()),isDefault:n.optional(n.boolean())}),Me=n.object({id:n.string(),type:n.string(),data:n.object({object:n.any()}),created:n.pipe(n.string(),n.isoTimestamp())}),Le=n.looseObject({userId:n.optional(n.string()),firebaseUid:n.optional(n.string()),productType:n.optional(n.string())});function xn(e){return n.safeParse(De,e)}function Tn(e){return n.safeParse(Ne,e)}function Cn(e){return n.safeParse(Fe,e)}function In(e){return n.safeParse(Ue,e)}function An(e){return n.safeParse(Me,e)}function kn(e){return n.safeParse(Le,e)}var Lt=n.object({type:n.literal("StripePayment"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.pipe(n.string(),n.minLength(1,"Duration is required")),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),Bt=n.object({type:n.literal("StripeSubscription"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),qt=n.variant("type",[Lt,Bt]),Rn=n.record(n.string(),qt),Vt=n.record(n.string(),n.object({name:n.string(),price:n.string(),currency:n.string(),description:n.optional(n.string()),features:n.optional(n.array(n.string())),priceId:n.string(),allowPromotionCodes:n.optional(n.boolean())})),jt=n.record(n.string(),n.object({type:n.picklist(["StripePayment","StripeSubscription"]),name:n.string(),price:n.number(),currency:n.string(),priceId:n.string(),tier:n.string(),duration:n.string(),description:n.optional(n.string()),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean())}));function Pn(e){return n.parse(Vt,e)}function _n(e){return n.parse(jt,e)}function wn(){let e={createCheckoutSessionRequest:n.safeParse(De,{}),createCheckoutSessionResponse:n.safeParse(Ne,{}),subscriptionData:n.safeParse(Fe,{}),subscriptionClaims:n.safeParse(Ue,{}),webhookEvent:n.safeParse(Me,{}),checkoutSessionMetadata:n.safeParse(Le,{})};return{success:Object.values(e).every(t=>t.success),results:e}}i();var Be=a.object({id:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),emailVerified:a.optional(a.boolean()),lastLoginAt:a.optional(a.string()),providerData:a.optional(a.array(a.object({providerId:a.string(),uid:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),phoneNumber:a.optional(a.nullable(a.string()))}))),role:a.optional(a.picklist(Object.values(q))),customClaims:a.optional(a.record(a.string(),a.any()))}),ge=a.object({userId:a.string(),tier:a.picklist(Object.values(de)),status:a.picklist(Object.values(G)),isActive:a.optional(a.boolean()),features:a.optional(a.array(a.string())),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())}),qe=a.object({role:a.optional(a.picklist(Object.values(q))),subscription:a.optional(ge),features:a.optional(a.array(a.picklist(Object.values(pe)))),permissions:a.optional(a.array(a.picklist(Object.values(me)))),githubAccess:a.optional(a.object({username:a.optional(a.string()),teamAccess:a.optional(a.array(a.string())),repoAccess:a.optional(a.array(a.string()))}))});function jn(e){return a.safeParse(Be,e)}function Hn(e){return a.safeParse(ge,e)}function $n(e){return a.safeParse(qe,e)}function Gn(){let e={authUser:a.safeParse(Be,{}),userSubscription:a.safeParse(ge,{}),customClaims:a.safeParse(qe,{}),getUserAuthStatus:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1))}),{}),getCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.optional(a.array(a.string()))}),{}),setCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claims:a.record(a.string(),a.any()),merge:a.optional(a.boolean(),!1)}),{}),removeCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.pipe(a.array(a.string()),a.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}i();var Yn={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Kn(e){return{userId:e,role:"user",preferences:{},metadata:{}}}i();var ni={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},ii={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},oi={CLIENT:"client",SERVER:"server",BUILD:"build"},ai={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},si={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},ci={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},li={USER:"user",GLOBAL:"global",SESSION:"session"},ui={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},di={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},pi={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};i();i();i();import*as x from"valibot";i();var fe={create:"admin",read:"guest",update:"admin",delete:"admin"};var re=/^[0-9a-zA-Z]+$/,xi=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),data:x.record(x.string(),x.unknown()),idempotencyKey:x.optional(x.string())}),Ti=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required"))}),Ci=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required")),data:x.record(x.string(),x.unknown()),merge:x.optional(x.boolean(),!1)}),Ii=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required"))}),Ai=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),limit:x.optional(x.pipe(x.number(),x.minValue(1),x.maxValue(1e3)),50),offset:x.optional(x.pipe(x.number(),x.minValue(0)),0),orderBy:x.optional(x.string()),orderDirection:x.optional(x.picklist(["asc","desc"]),"desc"),where:x.optional(x.array(x.object({field:x.string(),operator:x.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:x.any()})))});i();i();i();var he={"permission-denied":{type:"PERMISSION_DENIED",message:"You do not have permission to perform this action"},"not-found":{type:"NOT_FOUND",message:"The requested resource was not found"},"already-exists":{type:"ALREADY_EXISTS",message:"The resource already exists"},"invalid-argument":{type:"VALIDATION_ERROR",message:"Invalid argument provided"}},Ve=class extends Error{type;originalError;constructor(t,r,o){super(r),this.name="EntityHookError",this.type=t,this.originalError=o}},D=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r="internal",o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.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}}};i();i();var qi={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"};i();var Hi={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"};i();var Wi={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"};i();var Ki={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"};i();var Qi={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"};i();i();i();i();import"valibot";i();i();i();i();i();i();var ve={mobile:0,tablet:768,laptop:1024,desktop:1440},Ht={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function $t(e){return e>=ve.desktop?"desktop":e>=ve.laptop?"laptop":e>=ve.tablet?"tablet":"mobile"}function xo(e,t){let r=Ht[t];return e>=r.min&&e<=r.max}function To(e,t){let r=$t(e);return{current:r,width:e,height:t,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}i();var Ao="landing";i();i();i();i();i();var je=["pull","push","admin","maintain","triage"];i();import"valibot";i();import*as E from"valibot";var ye=E.object({owner:E.pipe(E.string(),E.minLength(1,"Repository owner is required")),repo:E.pipe(E.string(),E.minLength(1,"Repository name is required"))}),Gt=E.picklist([...je]),Ho=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye,permission:E.optional(Gt,"push"),customClaims:E.optional(E.record(E.string(),E.any()))}),$o=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye}),Go=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye}),Wo=E.object({provider:E.string(),purpose:E.picklist(["authentication","api-access"]),code:E.pipe(E.string(),E.minLength(1,"Authorization code is required")),redirectUri:E.pipe(E.string(),E.url("Valid redirect URI is required")),codeVerifier:E.optional(E.string()),state:E.optional(E.string()),instance:E.optional(E.pipe(E.string(),E.url()))}),zo=E.object({provider:E.string(),refreshToken:E.pipe(E.string(),E.minLength(1,"Refresh token is required")),redirectUri:E.pipe(E.string(),E.url("Valid redirect URI is required"))}),Yo=E.object({provider:E.string()}),Ko=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required"))});i();i();var na={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"};i();import*as T from"valibot";var He=T.object({name:T.string(),color:T.string(),icon:T.string(),customParameters:T.optional(T.record(T.string(),T.string())),button:T.object({backgroundColor:T.string(),textColor:T.string(),borderColor:T.string(),hoverBackgroundColor:T.string(),focusOutlineColor:T.string(),fontWeight:T.optional(T.string(),"500"),textKey:T.optional(T.string())})}),Wt=T.object({...He.entries,type:T.picklist(["auth","both"]),scopes:T.optional(T.array(T.string())),firebaseProviderId:T.optional(T.string())}),ne=T.union([T.literal(""),T.pipe(T.string(),T.url())]),zt=T.object({authUrl:ne,tokenUrl:ne,profileUrl:ne,revokeUrl:T.optional(ne)}),Yt=T.object({authentication:T.optional(T.array(T.string())),"api-access":T.array(T.string())}),Kt=T.optional(T.object({pkce:T.optional(T.boolean(),!1),codeChallengeMethod:T.optional(T.picklist(["S256","plain"]),"S256")})),Xt=T.object({...He.entries,type:T.picklist(["oauth","both"]),scopes:Yt,endpoints:zt,capabilities:Kt}),$e={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"}}},Ge={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"}}},Zt=T.record(T.string(),Wt),Qt=T.record(T.string(),Xt);function aa(){return T.safeParse(Zt,$e)}function sa(){return T.safeParse(Qt,Ge)}function ca(e){return e in $e}function la(e){return e in Ge}i();i();i();i();i();var We={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Ea={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"},xa={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Ta={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:We.ANALYTICS},marketing:{requiresConsent:We.MARKETING}};i();i();i();i();i();function be(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}i();import*as Ye from"valibot";i();function L(e){return(t,r)=>{if(t instanceof D)return t;if(typeof t!="object"||t===null){let A=typeof t=="string"?t:e.defaultErrorMessage;return new D(r||A,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let s=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(s=e.errorCodeMapping[o]);let d;e.extractErrorMessage?d=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(d=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(d=e.friendlyMessageMapping[o]),d||(d=e.defaultErrorMessage);let C;return e.processMetadata?C=e.processMetadata(t):(C={originalError:t},o&&(C.originalCode=o)),"originalError"in C||(C.originalError=t),new D(r||d,s,{details:C,source:e.errorSource})}}var X={"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 H={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Jt={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"},Se={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},V={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",...X},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",...X},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(Jt).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},processMetadata:e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:X,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:H.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:H["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:H.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},er=e=>e instanceof Ye.ValiError?new D(H["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):L(V.validation)(e),tr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Se){let t=e,r=Se[t.type]||"unknown";return new D(t.message||H[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&he[e.code]){let t=e,r=he[t.code];if(r){let o=Se[r.type]||"unknown";return new D(r.message||H[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return L(V.entity)(e)},ze={auth:L(V.auth),oauth:L(V.oauth),api:L(V.api),firebase:L(V.firebase),ui:L(V.ui),validation:er,entity:tr,unknown:L(V.unknown)};function Ee(e,t,r){return e instanceof D?e:(ze[t]||ze.unknown)(e,r)}i();function xe(e,t,r={}){let o=globalThis.Sentry;o&&o.withScope(s=>{s.setTag("errorSource",t),s.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([d,C])=>{if(typeof C!="function"&&d!=="originalError")try{s.setExtra(d,C)}catch{s.setExtra(d,`[${typeof C}]`)}}),Object.entries(r).forEach(([d,C])=>{if(typeof C!="function")try{s.setExtra(`context.${d}`,C)}catch{s.setExtra(`context.${d}`,`[${typeof C}]`)}}),(e.details?.userId||r.userId)&&s.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),o.captureException(e)})}function rr(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof l<"u"&&l.env?"production".toLowerCase()!=="production":!0}function O(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:s={},log:d=!0,reportToSentry:C=!0,showNotification:A=!1,severity:P="error"}=r,R=be(e),I=e instanceof D?e:Ee(e,R,o);if(o&&!I.userMessageProvided&&(I.message.includes("Error")||I.message.includes("Failed")||I.message.length<10?I=new D(o,I.code,{details:{...I.details,originalMessage:I.message},source:R,userMessageProvided:!0}):I=new D(I.message,I.code,{details:{...I.details,userMessage:o},source:R,userMessageProvided:!0})),d){let U=rr()||typeof window<"u"&&window.__DNDEV_DEBUG,Y={code:I.code,message:I.message,source:R};switch(P){case"warning":break;case"info":break;case"success":break;default:}}return C&&xe(I,R,s),I}function nr(e,t){return async(...r)=>{try{return await e(...r)}catch(o){throw O(o,t)}}}function ir(e,t="info",r){let o=Date.now().toString();return o}i();function or(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}i();function Ke(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ze(e)}async function Xe(e){let r=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",r);return Ze(new Uint8Array(o))}async function ar(){let e=Ke(),t=await Xe(e);return{codeVerifier:e,codeChallenge:t}}function Ze(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function sr(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function cr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function lr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}i();async function ur(e,t,r){try{return await e()}catch{return t(),!1}}i();var Te=new Map;function dr(e,t){if(Te.has(t))return Te.get(t);let r=e();return Te.set(t,r),r}i();var Qe={[q.GUEST]:0,[q.USER]:1,[q.ADMIN]:2,[q.SUPER]:3};function ie(e,t){if(!e)return!1;let r=Qe[e]??-1,o=Qe[t]??1/0;return r>=o}i();function pr(e,t,r){if(!e)return!1;let o=r??Oe,s=o[e]?.level??-1,d=o[t]?.level??1/0;return s>=d}i();function mr(e,...t){let r=null,o=!1;return function(){if(r!==null)return r;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{o=!1}}}function gr(e){let t=null,r=!1;return function(...s){if(t!==null)return t;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?t=new e(...s):t=e(...s),t}finally{r=!1}}}function fr(e){let t=null,r=!1,o=null;return async function(){if(t!==null)return t;if(r&&o)return o;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return o=e(),t=await o,t}finally{r=!1,o=null}}}function hr(e,t){return new Proxy({},{get(r,o){if(t.includes(o)){let d=e(),C=d[o];return typeof C=="function"?C.bind(d):C}return e()[o]}})}var Ce=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,o={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(o.ssrSafe===!1&&typeof window>"u"){if(o.fallbackFactory){let s=o.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let s=await r();return this.instances.set(t,s),this.initialized.add(t),s}catch(s){if(o.cacheFailures&&this.initialized.add(t),o.fallbackFactory){let d=o.fallbackFactory();return this.instances.set(t,d),this.initialized.add(t),d}throw s}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};i();function vr(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}i();i();import"valibot";i();import"valibot";function yr(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function br(e){if(yr(e))return e.visibility}function Je(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?ie(t,"admin"):ie(t,r)}function Ie(e,t){let r=e;if(!r||typeof r!="object"||!r.entries)return[];let o=r.entries,s=[];for(let[d,C]of Object.entries(o)){let A=br(C);Je(A,t)&&s.push(d)}return s}function Sr(e,t,r){if(!e)return{};let o=Ie(t,r),s={};for(let d of o)Object.prototype.hasOwnProperty.call(e,d)&&(s[d]=e[d]);return s}i();function Z(e,t){let r=new Date(e),o=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==o&&r.setDate(0),r}function Ae(e,t){let r=new Date(e),o=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==o&&r.setDate(0),r}function Er(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=Z(t,1):e==="3months"?r=Z(t,3):e==="6months"?r=Z(t,6):e==="1year"?r=Ae(t,1):e==="2years"?r=Ae(t,2):r=Z(t,1),r.toISOString()}function xr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}i();function Tr(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function Cr(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);let s=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(s.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=s}return t}function Ir(e,t=!0){let r=l.env[e];if(t&&!r)throw new Error(`Required environment variable '${e}' is not set`);return r||""}i();function Ar(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,o=e.split(";");for(let s=0;s<o.length;s++){let d=o[s];if(d){for(;d.charAt(0)===" ";)d=d.substring(1,d.length);if(d.indexOf(r)===0)return decodeURIComponent(d.substring(r.length,d.length))}}return null}i();i();i();import*as B from"valibot";i();import*as c from"valibot";var Q=new Map;function k(e,t){Q.set(e,t)}function Dc(e){return Q.has(e)}function Nc(){return Array.from(Q.keys())}function Fc(){Q.clear()}function _(e,t){return t?e:c.nullish(e)}var oe=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(c.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(c.regex(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?c.pipe(c.string(),...t):c.string();return _(r,e.validation?.required)},kr=e=>{let t=c.pipe(c.string(),c.email("Invalid email address"));return _(t,e.validation?.required)},Rr=e=>{let t=e.validation?.minLength!==void 0?c.pipe(c.string(),c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):c.string();return _(t,e.validation?.required)},Pr=e=>{let t=c.pipe(c.string(),c.url("Invalid URL"));return _(t,e.validation?.required)},tt=e=>{let t=[];e.validation?.min!==void 0&&t.push(c.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(c.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?c.pipe(c.number(),...t):c.number();return _(r,e.validation?.required)},rt=e=>{let t=c.boolean();return _(t,e.validation?.required)},W=e=>{let t=c.pipe(c.string(),c.isoTimestamp("Invalid date format"));return _(t,e.validation?.required)},at=c.object({url:c.string(),filename:c.string(),size:c.number(),mimeType:c.nullish(c.string()),uploadedAt:c.nullish(c.string())}),nt=e=>{let t=c.nullable(at);return _(t,e.validation?.required)},it=e=>{let t=c.array(at);return _(t,e.validation?.required)},st=c.object({fullUrl:c.string(),thumbUrl:c.string()}),_r=e=>_(st,e.validation?.required),wr=e=>{let t=c.array(st);return _(t,e.validation?.required)},Or=e=>{let t=c.object({lat:c.number(),lng:c.number()});return _(t,e.validation?.required)},Dr=e=>{let t=c.object({formatted_address:c.string(),latitude:c.number(),longitude:c.number(),street_number:c.nullish(c.string()),route:c.nullish(c.string()),locality:c.nullish(c.string()),administrative_area_level_1:c.nullish(c.string()),administrative_area_level_2:c.nullish(c.string()),country:c.nullish(c.string()),postal_code:c.nullish(c.string())});return _(t,e.validation?.required)},Nr=e=>{let t=c.record(c.string(),c.unknown());return _(t,e.validation?.required)},Fr=e=>{let t=c.array(c.unknown());return _(t,e.validation?.required)},ke=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(d=>d.value),s=c.picklist(o);return _(s,e.validation?.required)}let r=c.union([c.string(),c.number()]);return _(r,e.validation?.required)},Ur=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(d=>d.value),s=c.array(c.picklist(o));return _(s,e.validation?.required)}let r=c.array(c.string());return _(r,e.validation?.required)},Mr=e=>{let t=c.pipe(c.string(),c.regex(re,"Invalid ID format"));return _(t,e.validation?.required)},Re=e=>{let t=c.string();return _(t,e.validation?.required)},Lr=e=>{let t=c.string();return _(t,e.validation?.required)},ot=()=>c.never(),Br=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],s=c.picklist(o);return _(s,e.validation?.required)}let r=c.boolean();return _(r,e.validation?.required)};function qr(){k("text",oe),k("textarea",oe),k("richtext",oe),k("color",oe),k("email",kr),k("password",Rr),k("url",Pr),k("tel",Lr),k("number",tt),k("range",tt),k("boolean",rt),k("checkbox",rt),k("date",W),k("datetime-local",W),k("time",W),k("week",W),k("month",W),k("timestamp",W),k("file",nt),k("files",it),k("document",nt),k("documents",it),k("image",_r),k("images",wr),k("geopoint",Or),k("address",Dr),k("map",Nr),k("array",Fr),k("select",ke),k("multiselect",Ur),k("radio",ke),k("combobox",ke),k("switch",Br),k("reference",Mr),k("hidden",Re),k("avatar",Re),k("badge",Re),k("submit",ot),k("reset",ot)}qr();function J(e){if(e.validation?.schema){let o=e.validation.schema;return _(o,e.validation?.required)}let t=Q.get(e.type);if(t){let o=t(e);if(o!==null)return o}let r=c.unknown();return _(r,e.validation?.required)}i();var Pe=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],Bc="available",qc=["draft","deleted"],z=["id","createdAt","updatedAt","createdById","updatedById"],Vr=[...z,"status"];function Vc(e){return Vr.includes(e)}function jc(e){return z.includes(e)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Pe]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:re.source}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};function ee(e,t){return Object.assign(e,{visibility:t})}function $(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name},r}function ct(e){let t=J(e);return ee(t,e.visibility)}function lt(e){let t=J({...e,validation:{...e.validation,required:!1}});return ee(t,e.visibility)}function jr(e){let t=e.fields,r={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(r[N]=ct(F));let o=$(B.object(r),e),s={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(s[N]=ct(F)));let d=$(B.object(s),e),C={};for(let[N,F]of Object.entries(t))if(F.visibility!=="hidden"&&!z.includes(N))if(N==="status"){let j=B.literal("draft");C[N]=ee(j,F.visibility)}else C[N]=lt(F);let A=$(B.object(C),e),P={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(P[N]=lt(F)));P.id=ee(J(w.id),"technical");let R=$(B.object(P),e),I;if(e.listFields&&e.listFields.length>0){let N=["id","status"],F=[...new Set([...N,...e.listFields])];I={};for(let j of F){let K=r[j];K&&(I[j]=K)}}else I=r;let U=$(B.object(I),e),Y,se=e.listCardFields??e.listFields;if(se&&se.length>0){let N=["id","status"],F=[...new Set([...N,...se])];Y={};for(let j of F){let K=r[j];K&&(Y[j]=K)}}else Y=r;let gt=$(B.object(Y),e),ft=$(B.object({id:ee(J(w.id),"technical")}),e);return{create:d,draft:A,update:R,get:o,list:U,listCard:gt,delete:ft}}i();i();i();import"valibot";function el(e,t){let r=e;return r.metadata=t,r}i();var ut=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function dt(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function ae(e,t=""){if(Array.isArray(e))e.forEach((r,o)=>{let s=`${t}[${o}]`;if(typeof r=="string"&&dt(r)){if(!ut.test(r))throw O({userMessage:`Invalid date format for ${s}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:s,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&ae(r,s)});else if(typeof e=="object"&&e!==null)for(let[r,o]of Object.entries(e)){let s=t?`${t}.${r}`:r;if(typeof o=="string"&&dt(o)){if(!ut.test(o))throw O({userMessage:`Invalid date format for field "${s}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${o}"`,context:{field:s,value:o},severity:"error"})}else typeof o=="object"&&o!==null&&ae(o,s)}}i();import*as mt from"valibot";i();var _e={};function sl(e){_e.uniqueConstraintValidator=e}async function pt(e,t,r){let{uniqueFields:o=[],collection:s}=e.metadata;o.length!==0&&_e.uniqueConstraintValidator&&await Promise.all(o.map(async({field:d,errorMessage:C})=>{let A=t[d];if(A==null)return;if(await _e.uniqueConstraintValidator.checkDuplicate(s,d,A,r))throw O({userMessage:C||`${d} must be unique`,code:"already-exists",context:{field:d}})}))}async function pl(e,t,r,o){mt.parse(e,t),ae(t),await pt(e,t,o),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}i();function Hr(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Tl(e){if(!Hr(e)){let t=e,r=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw O(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return e.metadata.collection}i();function $r(e,t){if(!t||t.length===0)return e.map(s=>({value:s.value,label:s.label}));let r=e.map(s=>({value:s.value,label:s.label})),o=new Set(e.map(s=>s.value));for(let s of t)o.has(s.value)||r.push(s);return r}function Gr(e){let{form:t,fields:r}=e,o=Object.keys(r);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw O(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let s=t.steps.flatMap(P=>P.fields),d=s.filter(P=>!o.includes(P));if(d.length>0)throw O(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${d.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"validateFormConfig"},severity:"error"});let C=new Set(s);o.filter(P=>!C.has(P)).length>0}t.rules&&t.rules.forEach((s,d)=>{let A=(Array.isArray(s.condition)?s.condition.map(I=>I.field):[s.condition.field]).filter(I=>!o.includes(I));if(A.length>0)throw O(new Error(`Dynamic form rule ${d} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`),{userMessage:`Dynamic form rule ${d} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`,context:{entityName:e.name,ruleIndex:d,invalidFields:A,operation:"validateFormConfig"},severity:"error"});let R=[...s.showFields||[],...s.hideFields||[],...s.disableFields||[],...s.enableFields||[]].filter(I=>!o.includes(I));if(R.length>0)throw O(new Error(`Dynamic form rule ${d} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`),{userMessage:`Dynamic form rule ${d} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`,context:{entityName:e.name,ruleIndex:d,invalidFields:R,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([s,d])=>{if(d.dependsOn&&!o.includes(d.dependsOn.field))throw O(new Error(`Field '${s}' in entity '${e.name}' depends on non-existent field: ${d.dependsOn.field}`),{userMessage:`Field '${s}' in entity '${e.name}' depends on non-existent field: ${d.dependsOn.field}`,context:{entityName:e.name,fieldName:s,dependsOnField:d.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Wr(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Pl(e){try{Gr(e);let t=Wr(e),r={...e.fields,...w,...e.fields.createdAt&&{createdAt:{...w.createdAt,...e.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...w.updatedAt,...e.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...w.createdById,...e.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...w.updatedById,...e.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...e.fields.status&&{status:{...w.status,...e.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:e.fields.status.validation?.nullable,options:$r(Pe,e.fields.status.validation?.options)}}}};if(e.listFields){let s=new Set(Object.keys(r)),d=e.listFields.filter(C=>!s.has(C));if(d.length>0)throw O(new Error(`Entity '${e.name}' defines listFields that do not exist: ${d.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),d=e.listCardFields.filter(C=>!s.has(C));if(d.length>0)throw O(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${d.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"defineEntity"},severity:"error"})}let o={...fe,...e.access||{}};return{...e,form:t,fields:r,access:o}}catch(t){throw O(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}export{qi as AUTH_EVENTS,$e as AUTH_PARTNERS,Yn as AUTH_PARTNER_STATE,Be as AuthUserSchema,z as BACKEND_GENERATED_FIELD_NAMES,Hi as BILLING_EVENTS,Ht as BREAKPOINT_RANGES,ve as BREAKPOINT_THRESHOLDS,Oe as COMMON_TIER_CONFIGS,ai as CONFIDENCE_LEVELS,We as CONSENT_CATEGORY,oi as CONTEXTS,Le as CheckoutSessionMetadataSchema,De as CreateCheckoutSessionRequestSchema,Ne as CreateCheckoutSessionResponseSchema,qe as CustomClaimsSchema,fe as DEFAULT_ENTITY_ACCESS,H as DEFAULT_ERROR_MESSAGES,Ao as DEFAULT_LAYOUT_PRESET,Pe as DEFAULT_STATUS_OPTIONS,Bc as DEFAULT_STATUS_VALUE,yn as DEFAULT_SUBSCRIPTION,xa as DENSITY,D as DoNotDevError,ii as ENVIRONMENTS,Ve as EntityHookError,pe as FEATURES,Ta as FEATURE_CONSENT_MATRIX,si as FEATURE_STATUS,he as FIREBASE_ERROR_MAP,re as FIRESTORE_ID_PATTERN,je as GITHUB_PERMISSION_LEVELS,qc as HIDDEN_STATUSES,Ea as LAYOUT_PRESET,Wi as OAUTH_EVENTS,Ge as OAUTH_PARTNERS,na as PARTNER_ICONS,Ki as PAYLOAD_EVENTS,me as PERMISSIONS,ni as PLATFORMS,di as PWA_ASSET_TYPES,ui as PWA_DISPLAY_MODES,qt as ProductDeclarationSchema,Rn as ProductDeclarationsSchema,pi as ROUTE_SOURCES,li as STORAGE_SCOPES,ci as STORAGE_TYPES,Qi as STRIPE_EVENTS,te as STRIPE_MODES,hn as SUBSCRIPTION_DURATIONS,G as SUBSCRIPTION_STATUS,de as SUBSCRIPTION_TIERS,et as ServerUtils,Ce as SingletonManager,jt as StripeBackConfigSchema,Vt as StripeFrontConfigSchema,Lt as StripePaymentSchema,Bt as StripeSubscriptionSchema,Ue as SubscriptionClaimsSchema,Fe as SubscriptionDataSchema,Vr as TECHNICAL_FIELD_NAMES,q as USER_ROLES,ge as UserSubscriptionSchema,Me as WebhookEventSchema,Z as addMonths,Ae as addYears,w as baseFields,Er as calculateSubscriptionEndDate,xe as captureErrorToSentry,Go as checkGitHubAccessSchema,Fc as clearSchemaGenerators,X as commonErrorCodeMappings,ce as compactToISOString,fr as createAsyncSingleton,vn as createDefaultSubscriptionClaims,Kn as createDefaultUserProfile,xi as createEntitySchema,L as createErrorHandler,kt as createMetadata,hr as createMethodProxy,jr as createSchemas,mr as createSingleton,gr as createSingletonWithParams,Pl as defineEntity,Ii as deleteEntitySchema,be as detectErrorSource,Yo as disconnectOAuthSchema,el as enhanceSchema,Wo as exchangeTokenSchema,Sr as filterVisibleFields,we as formatDate,Nt as formatRelativeTime,Xe as generateCodeChallenge,Ke as generateCodeVerifier,ar as generatePKCEPair,$t as getBreakpointFromWidth,To as getBreakpointUtils,Tl as getCollectionName,Ko as getConnectionsSchema,_t as getCurrentTimestamp,Ti as getEntitySchema,Nc as getRegisteredSchemaTypes,J as getSchemaType,Ie as getVisibleFields,Dt as getWeekFromISOString,Gt as githubPermissionSchema,ye as githubRepoConfigSchema,Ho as grantGitHubAccessSchema,O as handleError,Dc as hasCustomSchemaGenerator,Hr as hasMetadata,ie as hasRoleAccess,pr as hasTierAccess,ca as isAuthPartnerId,jc as isBackendGeneratedField,xo as isBreakpoint,le as isCompactDateString,Je as isFieldVisible,Vc as isFrameworkField,la as isOAuthPartnerId,sr as isPKCESupported,Rt as isoToCompactString,dr as lazyImport,Ai as listEntitiesSchema,Ee as mapToDoNotDevError,or as maybeTranslate,Pt as normalizeToISOString,un as overrideFeatures,fn as overridePaymentModes,dn as overridePermissions,gn as overrideSubscriptionStatus,ln as overrideSubscriptionTiers,cn as overrideUserRoles,ue as parseDate,Ut as parseDateToNoonUTC,xr as parseISODate,Ar as parseServerCookie,zo as refreshTokenSchema,k as registerSchemaGenerator,sl as registerUniqueConstraintValidator,$o as revokeGitHubAccessSchema,ir as showNotification,Ot as timestampToISOString,Mt as toDateOnly,wt as toISOString,Tt as translateArray,It as translateArrayRange,At as translateArrayWithIndices,Ct as translateObjectArray,Ci as updateEntitySchema,vr as updateMetadata,aa as validateAuthPartners,Gn as validateAuthSchemas,jn as validateAuthUser,wn as validateBillingSchemas,kn as validateCheckoutSessionMetadata,lr as validateCodeChallenge,cr as validateCodeVerifier,xn as validateCreateCheckoutSessionRequest,Tn as validateCreateCheckoutSessionResponse,$n as validateCustomClaims,ae as validateDates,pl as validateDocument,Ir as validateEnvVar,Cr as validateMetadata,sa as validateOAuthPartners,_n as validateStripeBackConfig,Pn as validateStripeFrontConfig,In as validateSubscriptionClaims,Cn as validateSubscriptionData,pt as validateUniqueFields,Tr as validateUrl,Hn as validateUserSubscription,An as validateWebhookEvent,nr as withErrorHandling,ur as withGracefulDegradation};
1
+ var Ji=Object.create;var Nt=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var Qi=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty;var Zr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),to=(t,e)=>{for(var r in e)Nt(t,r,{get:e[r],enumerable:!0})},ro=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zi(e))!eo.call(t,i)&&i!==r&&Nt(t,i,{get:()=>e[i],enumerable:!(n=Xi(e,i))||n.enumerable});return t};var Qr=(t,e,r)=>(r=t!=null?Ji(Qi(t)):{},ro(e||!t||!t.__esModule?Nt(r,"default",{value:t,enumerable:!0}):r,t));var qi=Zr(b=>{"use strict";var qr=Symbol.for("react.transitional.element"),Vc=Symbol.for("react.portal"),Bc=Symbol.for("react.fragment"),Hc=Symbol.for("react.strict_mode"),$c=Symbol.for("react.profiler"),Wc=Symbol.for("react.consumer"),qc=Symbol.for("react.context"),Gc=Symbol.for("react.forward_ref"),jc=Symbol.for("react.suspense"),Kc=Symbol.for("react.memo"),Fi=Symbol.for("react.lazy"),zc=Symbol.for("react.activity"),Ni=Symbol.iterator;function Yc(t){return t===null||typeof t!="object"?null:(t=Ni&&t[Ni]||t["@@iterator"],typeof t=="function"?t:null)}var Vi={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Bi=Object.assign,Hi={};function ke(t,e,r){this.props=t,this.context=e,this.refs=Hi,this.updater=r||Vi}ke.prototype.isReactComponent={};ke.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};ke.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function $i(){}$i.prototype=ke.prototype;function Gr(t,e,r){this.props=t,this.context=e,this.refs=Hi,this.updater=r||Vi}var jr=Gr.prototype=new $i;jr.constructor=Gr;Bi(jr,ke.prototype);jr.isPureReactComponent=!0;var Ui=Array.isArray;function Wr(){}var C={H:null,A:null,T:null,S:null},Wi=Object.prototype.hasOwnProperty;function Kr(t,e,r){var n=r.ref;return{$$typeof:qr,type:t,key:e,ref:n!==void 0?n:null,props:r}}function Jc(t,e){return Kr(t.type,e,t.props)}function zr(t){return typeof t=="object"&&t!==null&&t.$$typeof===qr}function Xc(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var Li=/\/+/g;function $r(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Xc(""+t.key):e.toString(36)}function Zc(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Wr,Wr):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function xe(t,e,r,n,i){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(o){case"bigint":case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case qr:case Vc:s=!0;break;case Fi:return s=t._init,xe(s(t._payload),e,r,n,i)}}if(s)return i=i(t),s=n===""?"."+$r(t,0):n,Ui(i)?(r="",s!=null&&(r=s.replace(Li,"$&/")+"/"),xe(i,e,r,"",function(p){return p})):i!=null&&(zr(i)&&(i=Jc(i,r+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(Li,"$&/")+"/")+s)),e.push(i)),1;s=0;var c=n===""?".":n+":";if(Ui(t))for(var u=0;u<t.length;u++)n=t[u],o=c+$r(n,u),s+=xe(n,e,r,o,i);else if(u=Yc(t),typeof u=="function")for(t=u.call(t),u=0;!(n=t.next()).done;)n=n.value,o=c+$r(n,u++),s+=xe(n,e,r,o,i);else if(o==="object"){if(typeof t.then=="function")return xe(Zc(t),e,r,n,i);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return s}function Ot(t,e,r){if(t==null)return t;var n=[],i=0;return xe(t,n,"","",function(o){return e.call(r,o,i++)}),n}function Qc(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Mi=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}},eu={map:Ot,forEach:function(t,e,r){Ot(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return Ot(t,function(){e++}),e},toArray:function(t){return Ot(t,function(e){return e})||[]},only:function(t){if(!zr(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};b.Activity=zc;b.Children=eu;b.Component=ke;b.Fragment=Bc;b.Profiler=$c;b.PureComponent=Gr;b.StrictMode=Hc;b.Suspense=jc;b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C;b.__COMPILER_RUNTIME={__proto__:null,c:function(t){return C.H.useMemoCache(t)}};b.cache=function(t){return function(){return t.apply(null,arguments)}};b.cacheSignal=function(){return null};b.cloneElement=function(t,e,r){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var n=Bi({},t.props),i=t.key;if(e!=null)for(o in e.key!==void 0&&(i=""+e.key),e)!Wi.call(e,o)||o==="key"||o==="__self"||o==="__source"||o==="ref"&&e.ref===void 0||(n[o]=e[o]);var o=arguments.length-2;if(o===1)n.children=r;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];n.children=s}return Kr(t.type,i,n)};b.createContext=function(t){return t={$$typeof:qc,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:Wc,_context:t},t};b.createElement=function(t,e,r){var n,i={},o=null;if(e!=null)for(n in e.key!==void 0&&(o=""+e.key),e)Wi.call(e,n)&&n!=="key"&&n!=="__self"&&n!=="__source"&&(i[n]=e[n]);var s=arguments.length-2;if(s===1)i.children=r;else if(1<s){for(var c=Array(s),u=0;u<s;u++)c[u]=arguments[u+2];i.children=c}if(t&&t.defaultProps)for(n in s=t.defaultProps,s)i[n]===void 0&&(i[n]=s[n]);return Kr(t,o,i)};b.createRef=function(){return{current:null}};b.forwardRef=function(t){return{$$typeof:Gc,render:t}};b.isValidElement=zr;b.lazy=function(t){return{$$typeof:Fi,_payload:{_status:-1,_result:t},_init:Qc}};b.memo=function(t,e){return{$$typeof:Kc,type:t,compare:e===void 0?null:e}};b.startTransition=function(t){var e=C.T,r={};C.T=r;try{var n=t(),i=C.S;i!==null&&i(r,n),typeof n=="object"&&n!==null&&typeof n.then=="function"&&n.then(Wr,Mi)}catch(o){Mi(o)}finally{e!==null&&r.types!==null&&(e.types=r.types),C.T=e}};b.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()};b.use=function(t){return C.H.use(t)};b.useActionState=function(t,e,r){return C.H.useActionState(t,e,r)};b.useCallback=function(t,e){return C.H.useCallback(t,e)};b.useContext=function(t){return C.H.useContext(t)};b.useDebugValue=function(){};b.useDeferredValue=function(t,e){return C.H.useDeferredValue(t,e)};b.useEffect=function(t,e){return C.H.useEffect(t,e)};b.useEffectEvent=function(t){return C.H.useEffectEvent(t)};b.useId=function(){return C.H.useId()};b.useImperativeHandle=function(t,e,r){return C.H.useImperativeHandle(t,e,r)};b.useInsertionEffect=function(t,e){return C.H.useInsertionEffect(t,e)};b.useLayoutEffect=function(t,e){return C.H.useLayoutEffect(t,e)};b.useMemo=function(t,e){return C.H.useMemo(t,e)};b.useOptimistic=function(t,e){return C.H.useOptimistic(t,e)};b.useReducer=function(t,e,r){return C.H.useReducer(t,e,r)};b.useRef=function(t){return C.H.useRef(t)};b.useState=function(t){return C.H.useState(t)};b.useSyncExternalStore=function(t,e,r){return C.H.useSyncExternalStore(t,e,r)};b.useTransition=function(){return C.H.useTransition()};b.version="19.2.4"});var Yr=Zr((ev,Gi)=>{"use strict";Gi.exports=qi()});var Sn={};to(Sn,{CURRENCY_MAP:()=>Ut,DEFAULT_ERROR_MESSAGES:()=>oe,DoNotDevError:()=>x,SingletonManager:()=>Zt,addMonths:()=>Me,addYears:()=>er,calculateSubscriptionEndDate:()=>os,captureErrorToSentry:()=>Jt,commonErrorCodeMappings:()=>Ue,compactToISOString:()=>Lt,createAsyncSingleton:()=>Qo,createErrorHandler:()=>$,createMetadata:()=>ao,createMethodProxy:()=>es,createSingleton:()=>Le,createSingletonWithParams:()=>Zo,detectErrorSource:()=>Kt,filterVisibleFields:()=>is,formatCurrency:()=>uo,formatDate:()=>tn,formatRelativeTime:()=>vo,generateCodeChallenge:()=>En,generateCodeVerifier:()=>yn,generatePKCEPair:()=>Go,getCurrencyLocale:()=>en,getCurrencySymbol:()=>co,getCurrentTimestamp:()=>fo,getVisibleFields:()=>Qt,getWeekFromISOString:()=>go,handleError:()=>v,hasRoleAccess:()=>st,hasTierAccess:()=>Xo,isCompactDateString:()=>Mt,isFieldVisible:()=>Tn,isPKCESupported:()=>jo,isoToCompactString:()=>lo,lazyImport:()=>Jo,mapToDoNotDevError:()=>Yt,maybeTranslate:()=>qo,normalizeToISOString:()=>po,parseDate:()=>Ft,parseDateToNoonUTC:()=>Eo,parseISODate:()=>ss,parseServerCookie:()=>ls,showNotification:()=>Wo,timestampToISOString:()=>mo,toDateOnly:()=>bo,toISOString:()=>ho,translateArray:()=>no,translateArrayRange:()=>oo,translateArrayWithIndices:()=>so,translateObjectArray:()=>io,updateMetadata:()=>ts,validateCodeChallenge:()=>zo,validateCodeVerifier:()=>Ko,validateEnvVar:()=>us,validateMetadata:()=>cs,validateUrl:()=>as,withErrorHandling:()=>$o,withGracefulDegradation:()=>Yo});function no(t,e,r,n={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=n;return Array.from({length:r},(c,u)=>{let p=`${e}.${u}`;return t(p)}).filter((c,u)=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function io(t,e,r,n){return Array.from({length:r},(i,o)=>{let s=`${e}.${o}.${String(n[0])}`;if(t(s)===s)return null;let u={};for(let p of n){let g=`${e}.${o}.${String(p)}`;u[p]=t(g)}return u}).filter(i=>i!==null)}function oo(t,e,r,n,i={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:c}=i;return Array.from({length:n-r},(u,p)=>{let g=r+p,T=`${e}.${g}`;return t(T)}).filter((u,p)=>{let g=r+p,T=`${e}.${g}`;return!(u===T||s&&u.trim()===""||u.length<o||c&&!c(u,g))})}function so(t,e,r,n={}){let{minLength:i=0,excludeEmpty:o=!0,customFilter:s}=n;return Array.from({length:r},(c,u)=>{let p=`${e}.${u}`;return{item:t(p),originalIndex:u}}).filter(({item:c,originalIndex:u})=>{let p=`${e}.${u}`;return!(c===p||o&&c.trim()===""||c.length<i||s&&!s(c,u))})}function ao(t){let e=new Date().toISOString();return{_createdAt:e,_updatedAt:e,_createdBy:t,_updatedBy:t}}var Ut={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function en(t){return Ut[t]?.locale??"en-US"}function co(t){return!t||typeof t!="string"?t??"":Ut[t]?.symbol??t}function uo(t,e,r={}){if(t==null||isNaN(t))return"";let n=en(e);return new Intl.NumberFormat(n,{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:0,currencyDisplay:"symbol",...r}).format(t)}function Lt(t){let e=t.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!e||e.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${t}`);let r=e[1],n=e[2],i=e[3],o=e[4],s=e[5],c=new Date(parseInt(r,10),parseInt(n,10)-1,parseInt(i,10),parseInt(o,10),parseInt(s,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${t}`);return c.toISOString()}function lo(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0");return`${r}${n}${i}:${o}${s}`}function Mt(t){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(t)}function po(t){if(!t)return new Date().toISOString();if(t instanceof Date){if(isNaN(t.getTime()))throw new Error("Invalid Date object");return t.toISOString()}if(typeof t=="string"){if(Mt(t))return Lt(t);let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid date string: ${t}`);return e.toISOString()}if(typeof t=="number"){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid timestamp: ${t}`);return e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")return e.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof t}`)}function fo(){return new Date().toISOString()}function ho(t){return t.toISOString()}function mo(t){return new Date(t).toISOString()}function go(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);let r=new Date(e.getFullYear(),0,1),n=Math.floor((e.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((n+r.getDay()+1)/7)}, ${e.getFullYear()}`}var N={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function vo(t,e="en",r={}){if(!t)return"";let{style:n="long",numeric:i="auto",fallbackThreshold:o=N.WEEK}=r,s;if(t instanceof Date)s=t;else if(typeof t=="string")s=new Date(t);else if(typeof t=="number")s=new Date(t);else if(typeof t=="object"&&"toDate"in t)s=t.toDate();else return"";if(isNaN(s.getTime()))return"";let c=new Date,u=s.getTime()-c.getTime(),p=Math.round(u/1e3),g=Math.abs(p);if(g>o)return tn(s.toISOString(),e);let T=new Intl.RelativeTimeFormat(e,{style:n,numeric:i});return g<N.MINUTE?T.format(p,"second"):g<N.HOUR?T.format(Math.round(p/N.MINUTE),"minute"):g<N.DAY?T.format(Math.round(p/N.HOUR),"hour"):g<N.WEEK?T.format(Math.round(p/N.DAY),"day"):g<N.MONTH?T.format(Math.round(p/N.WEEK),"week"):g<N.YEAR?T.format(Math.round(p/N.MONTH),"month"):T.format(Math.round(p/N.YEAR),"year")}function yo(t){switch(t){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function tn(t,e="en",r="long"){if(!t)return"";let n;if(t instanceof Date)n=t;else if(typeof t=="string")n=new Date(t);else if(typeof t=="number")n=new Date(t);else if(typeof t=="object"&&"toDate"in t)n=t.toDate();else return"";if(isNaN(n.getTime()))return"";let i=typeof r=="string"?yo(r):r;return new Intl.DateTimeFormat(e,i).format(n)}function Ft(t){if(t!=null){if(t instanceof Date)return isNaN(t.getTime())?void 0:t.toISOString();if(typeof t=="string"){let e=t.trim();if(!e)return;if(Mt(e))try{return Lt(e)}catch{return}let r=new Date(e);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof t=="number"){if(!Number.isFinite(t))return;let e=new Date(t);return isNaN(e.getTime())?void 0:e.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t){let e=t;if(typeof e.toDate=="function")try{let r=e.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof t=="object"&&t!==null&&"seconds"in t&&typeof t.seconds=="number"){let e=t,r=e.seconds*1e3+(e.nanoseconds||0)/1e6,n=new Date(r);return isNaN(n.getTime())?void 0:n.toISOString()}}}function Eo(t){let e=Ft(t);if(!e)return;let r=new Date(e);return r.setUTCHours(12,0,0,0),r.toISOString()}function bo(t){let e=Ft(t);return e&&e.split("T")[0]||""}var V={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function hu(t){Object.assign(V,t)}var De={FREE:"free",PRO:"pro",PREMIUM:"premium"};function mu(t){Object.assign(De,t)}var Vt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function gu(t){Object.assign(Vt,t)}var Bt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function vu(t){Object.assign(Bt,t)}import*as l from"valibot";var he={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Eu(t){Object.assign(he,t)}var nt={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function bu(t){Object.assign(nt,t)}var Iu={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Tu(t){return{tier:"free",status:"active",subscriptionId:null,customerId:t,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var rn={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Su={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as a from"valibot";var nn=a.object({userId:a.string(),productId:a.optional(a.string()),priceId:a.string(),successUrl:a.pipe(a.string(),a.url()),cancelUrl:a.pipe(a.string(),a.url()),customerEmail:a.optional(a.pipe(a.string(),a.email())),userEmail:a.optional(a.pipe(a.string(),a.email())),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean()),mode:a.optional(a.picklist([nt.PAYMENT,nt.SUBSCRIPTION]))}),on=a.object({sessionId:a.string(),sessionUrl:a.nullable(a.pipe(a.string(),a.url()))}),sn=a.object({userId:a.string(),tier:a.string(),status:a.picklist(Object.values(he)),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),an=a.object({tier:a.string(),subscriptionId:a.nullable(a.string()),customerId:a.string(),status:a.picklist(Object.values(he)),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp()),isDefault:a.optional(a.boolean())}),cn=a.object({id:a.string(),type:a.string(),data:a.object({object:a.any()}),created:a.pipe(a.string(),a.isoTimestamp())}),un=a.looseObject({userId:a.optional(a.string()),firebaseUid:a.optional(a.string()),productType:a.optional(a.string())});function Au(t){return a.safeParse(nn,t)}function wu(t){return a.safeParse(on,t)}function Pu(t){return a.safeParse(sn,t)}function Ru(t){return a.safeParse(an,t)}function xu(t){return a.safeParse(cn,t)}function ku(t){return a.safeParse(un,t)}var Io=a.object({type:a.literal("StripePayment"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.pipe(a.string(),a.minLength(1,"Duration is required")),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),To=a.object({type:a.literal("StripeSubscription"),name:a.pipe(a.string(),a.minLength(1,"Product name is required")),description:a.optional(a.string()),price:a.string(),currency:a.optional(a.pipe(a.string(),a.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a.pipe(a.string(),a.minLength(1,"Stripe price ID is required")),tier:a.pipe(a.string(),a.minLength(1,"Tier is required")),duration:a.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:a.optional(a.boolean()),metadata:a.optional(a.record(a.string(),a.string()))}),So=a.variant("type",[Io,To]),Ou=a.record(a.string(),So),_o=a.record(a.string(),a.object({name:a.string(),price:a.string(),currency:a.string(),description:a.optional(a.string()),features:a.optional(a.array(a.string())),priceId:a.string(),allowPromotionCodes:a.optional(a.boolean())})),Co=a.record(a.string(),a.object({type:a.picklist(["StripePayment","StripeSubscription"]),name:a.string(),price:a.number(),currency:a.string(),priceId:a.string(),tier:a.string(),duration:a.string(),description:a.optional(a.string()),metadata:a.optional(a.record(a.string(),a.string())),allowPromotionCodes:a.optional(a.boolean())}));function Du(t){return a.parse(_o,t)}function Nu(t){return a.parse(Co,t)}function Uu(){let t={createCheckoutSessionRequest:a.safeParse(nn,{}),createCheckoutSessionResponse:a.safeParse(on,{}),subscriptionData:a.safeParse(sn,{}),subscriptionClaims:a.safeParse(an,{}),webhookEvent:a.safeParse(cn,{}),checkoutSessionMetadata:a.safeParse(un,{})};return{success:Object.values(t).every(e=>e.success),results:t}}var ln=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(V))),customClaims:l.optional(l.record(l.string(),l.any()))}),Ht=l.object({userId:l.string(),tier:l.picklist(Object.values(De)),status:l.picklist(Object.values(he)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),dn=l.object({role:l.optional(l.picklist(Object.values(V))),subscription:l.optional(Ht),features:l.optional(l.array(l.picklist(Object.values(Vt)))),permissions:l.optional(l.array(l.picklist(Object.values(Bt)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function Wu(t){return l.safeParse(ln,t)}function qu(t){return l.safeParse(Ht,t)}function Gu(t){return l.safeParse(dn,t)}function ju(){let t={authUser:l.safeParse(ln,{}),userSubscription:l.safeParse(Ht,{}),customClaims:l.safeParse(dn,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(t).every(e=>e.success),results:t}}var zu={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Yu(t){return{userId:t,role:"user",preferences:{},metadata:{}}}var A={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},ie={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},D={CLIENT:"client",SERVER:"server",BUILD:"build"},U={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ne={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},tl={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},rl={USER:"user",GLOBAL:"global",SESSION:"session"},nl={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},il={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},ol={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};import*as h from"valibot";var $t={create:"admin",read:"guest",update:"admin",delete:"admin"};var it=/^[0-9a-zA-Z]+$/,pl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),data:h.record(h.string(),h.unknown()),idempotencyKey:h.optional(h.string())}),fl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),hl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required")),data:h.record(h.string(),h.unknown()),merge:h.optional(h.boolean(),!1)}),ml=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),gl=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),limit:h.optional(h.pipe(h.number(),h.minValue(1),h.maxValue(1e3)),50),offset:h.optional(h.pipe(h.number(),h.minValue(0)),0),orderBy:h.optional(h.string()),orderDirection:h.optional(h.picklist(["asc","desc"]),"desc"),where:h.optional(h.array(h.object({field:h.string(),operator:h.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:h.any()})))});var Wt={"permission-denied":{type:"PERMISSION_DENIED",message:"You do not have permission to perform this action"},"not-found":{type:"NOT_FOUND",message:"The requested resource was not found"},"already-exists":{type:"ALREADY_EXISTS",message:"The resource already exists"},"invalid-argument":{type:"VALIDATION_ERROR",message:"Invalid argument provided"}},pn=class extends Error{type;originalError;constructor(e,r,n){super(r),this.name="EntityHookError",this.type=e,this.originalError=n}},x=class t extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(e,r="internal",n){super(e),Object.setPrototypeOf(this,t.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var Al={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var Pl={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var xl={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Ol={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Nl={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var qt={mobile:0,tablet:768,laptop:1024,desktop:1440},Ao={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function wo(t){return t>=qt.desktop?"desktop":t>=qt.laptop?"laptop":t>=qt.tablet?"tablet":"mobile"}function Kl(t,e){let r=Ao[e];return t>=r.min&&t<=r.max}function zl(t,e){let r=wo(t);return{current:r,width:t,height:e,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}var Jl="landing",Xl={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var fn=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var Gt=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),Po=f.picklist([...fn]),ad=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Gt,permission:f.optional(Po,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),cd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Gt}),ud=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Gt}),ld=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),dd=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),pd=f.object({provider:f.string()}),fd=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var Ed={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as m from"valibot";var hn=m.object({name:m.string(),color:m.string(),icon:m.string(),customParameters:m.optional(m.record(m.string(),m.string())),button:m.object({backgroundColor:m.string(),textColor:m.string(),borderColor:m.string(),hoverBackgroundColor:m.string(),focusOutlineColor:m.string(),fontWeight:m.optional(m.string(),"500"),textKey:m.optional(m.string())})}),Ro=m.object({...hn.entries,type:m.picklist(["auth","both"]),scopes:m.optional(m.array(m.string())),firebaseProviderId:m.optional(m.string())}),ot=m.union([m.literal(""),m.pipe(m.string(),m.url())]),xo=m.object({authUrl:ot,tokenUrl:ot,profileUrl:ot,revokeUrl:m.optional(ot)}),ko=m.object({authentication:m.optional(m.array(m.string())),"api-access":m.array(m.string())}),Oo=m.optional(m.object({pkce:m.optional(m.boolean(),!1),codeChallengeMethod:m.optional(m.picklist(["S256","plain"]),"S256")})),Do=m.object({...hn.entries,type:m.picklist(["oauth","both"]),scopes:ko,endpoints:xo,capabilities:Oo}),me={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},jt={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},No=m.record(m.string(),Ro),Uo=m.record(m.string(),Do);function Id(){return m.safeParse(No,me)}function Td(){return m.safeParse(Uo,jt)}function Lo(t){return t in me}function Mo(t){return t in jt}var mn={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Rd={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},xd={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:mn.ANALYTICS},marketing:{requiresConsent:mn.MARKETING}};function Kt(t){return t instanceof Error&&"source"in t&&typeof t.source=="string"?t.source:typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("auth/")?"auth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&t.code.startsWith("oauth/")?"oauth":typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(t.code)?"firebase":typeof t=="object"&&t!==null&&"issues"in t&&Array.isArray(t.issues)&&"name"in t&&t.name==="ValiError"?"validation":t instanceof Error&&t.name==="EntityHookError"?"entity":typeof t=="object"&&t!==null&&("response"in t||"status"in t||"statusText"in t)?"api":typeof t=="object"&&t!==null&&"componentStack"in t?"ui":"unknown"}import*as vn from"valibot";function $(t){return(e,r)=>{if(e instanceof x)return e;if(typeof e!="object"||e===null){let c=typeof e=="string"?e:t.defaultErrorMessage;return new x(r||c,t.defaultErrorCode,{details:{originalError:e},source:t.errorSource})}let n;t.extractErrorCode?n=t.extractErrorCode(e):"code"in e&&typeof e.code=="string"&&(n=e.code);let i=t.defaultErrorCode;n&&t.errorCodeMapping&&n in t.errorCodeMapping&&(i=t.errorCodeMapping[n]);let o;t.extractErrorMessage?o=t.extractErrorMessage(e):("message"in e&&typeof e.message=="string"||e instanceof Error)&&(o=e.message),n&&t.friendlyMessageMapping&&n in t.friendlyMessageMapping&&(o=t.friendlyMessageMapping[n]),o||(o=t.defaultErrorMessage);let s;return t.processMetadata?s=t.processMetadata(e):(s={originalError:e},n&&(s.originalCode=n)),"originalError"in s||(s.originalError=e),new x(r||o,i,{details:s,source:t.errorSource})}}var Ue={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var oe={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Fo={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},zt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Q={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",...Ue},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...Ue},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(Fo).map(([t,e])=>[t,e])),friendlyMessageMapping:{},extractErrorCode:t=>{if(typeof t!="object"||t===null)return;let e;return"response"in t&&t.response&&"status"in t.response?e=t.response.status:"status"in t&&typeof t.status=="number"&&(e=t.status),e?.toString()},processMetadata:t=>{let e={originalError:t};return typeof t!="object"||t===null||("response"in t&&t.response?("status"in t.response&&(e.statusCode=t.response.status),"data"in t.response&&(e.responseData=t.response.data)):"status"in t&&(e.statusCode=t.status)),e}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:Ue,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:oe.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:t=>{let e={originalError:t};return typeof t=="object"&&t!==null&&"componentStack"in t&&(e.componentStack=t.componentStack),e}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:oe["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:oe.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:t=>{if(t instanceof Error)return t.name}}},Vo=t=>t instanceof vn.ValiError?new x(oe["validation-failed"],"validation-failed",{details:{validationErrors:t.issues.map(e=>({path:e.path.join("."),message:e.message})),originalError:t},source:"validation"}):$(Q.validation)(t),Bo=t=>{if(t instanceof Error&&"type"in t&&typeof t.type=="string"&&t.type in zt){let e=t,r=zt[e.type]||"unknown";return new x(e.message||oe[r],r,{details:{originalError:t},source:"entity"})}if(typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&Wt[t.code]){let e=t,r=Wt[e.code];if(r){let n=zt[r.type]||"unknown";return new x(r.message||oe[n],n,{details:{originalCode:e.code,originalError:t},source:"entity"})}}return $(Q.entity)(t)},gn={auth:$(Q.auth),oauth:$(Q.oauth),api:$(Q.api),firebase:$(Q.firebase),ui:$(Q.ui),validation:Vo,entity:Bo,unknown:$(Q.unknown)};function Yt(t,e,r){return t instanceof x?t:(gn[e]||gn.unknown)(t,r)}function Jt(t,e,r={}){let n=globalThis.Sentry;n&&n.withScope(i=>{i.setTag("errorSource",e),i.setTag("errorCode",t.code),t.details&&Object.entries(t.details).forEach(([o,s])=>{if(typeof s!="function"&&o!=="originalError")try{i.setExtra(o,s)}catch{i.setExtra(o,`[${typeof s}]`)}}),Object.entries(r).forEach(([o,s])=>{if(typeof s!="function")try{i.setExtra(`context.${o}`,s)}catch{i.setExtra(`context.${o}`,`[${typeof s}]`)}}),(t.details?.userId||r.userId)&&i.setUser({id:t.details?.userId||r.userId,email:t.details?.userEmail||r.userEmail}),n.captureException(t)})}function Ho(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!0}function v(t,e){let r=typeof e=="string"?{userMessage:e}:e||{},{userMessage:n,context:i={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:u="error"}=r,p=Kt(t),g=t instanceof x?t:Yt(t,p,n);if(n&&!g.userMessageProvided&&(g.message.includes("Error")||g.message.includes("Failed")||g.message.length<10?g=new x(n,g.code,{details:{...g.details,originalMessage:g.message},source:p,userMessageProvided:!0}):g=new x(g.message,g.code,{details:{...g.details,userMessage:n},source:p,userMessageProvided:!0})),o){let T=Ho()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:g.code,message:g.message,source:p};switch(u){case"warning":break;case"info":break;case"success":break;default:}}return s&&Jt(g,p,i),g}function $o(t,e){return async(...r)=>{try{return await t(...r)}catch(n){throw v(n,e)}}}function Wo(t,e="info",r){let n=Date.now().toString();return n}function qo(t,e){return e?!e.includes(".")&&!e.includes(":")?e:t(e):""}function yn(){let t=new Uint8Array(32);return crypto.getRandomValues(t),bn(t)}async function En(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return bn(new Uint8Array(n))}async function Go(){let t=yn(),e=await En(t);return{codeVerifier:t,codeChallenge:e}}function bn(t){return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function jo(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Ko(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}function zo(t){return t.length<43||t.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(t)}async function Yo(t,e,r){try{return await t()}catch{return e(),!1}}var Xt=new Map;function Jo(t,e){if(Xt.has(e))return Xt.get(e);let r=t();return Xt.set(e,r),r}var In={[V.GUEST]:0,[V.USER]:1,[V.ADMIN]:2,[V.SUPER]:3};function st(t,e){if(!t)return!1;let r=In[t]??-1,n=In[e]??1/0;return r>=n}function Xo(t,e,r){if(!t)return!1;let n=r??rn,i=n[t]?.level??-1,o=n[e]?.level??1/0;return i>=o}function Le(t,...e){let r=null,n=!1;return function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof t=="function"&&t.prototype?r=new t(...e):r=t(),r}finally{n=!1}}}function Zo(t){let e=null,r=!1;return function(...i){if(e!==null)return e;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof t=="function"&&t.prototype?e=new t(...i):e=t(...i),e}finally{r=!1}}}function Qo(t){let e=null,r=!1,n=null;return async function(){if(e!==null)return e;if(r&&n)return n;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return n=t(),e=await n,e}finally{r=!1,n=null}}}function es(t,e){return new Proxy({},{get(r,n){if(e.includes(n)){let o=t(),s=o[n];return typeof s=="function"?s.bind(o):s}return t()[n]}})}var Zt=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(e,r,n={}){if(this.instances.has(e))return this.instances.get(e);if(this.initialized.has(e))return this.instances.get(e);if(this.initializing.has(e))throw new Error(`Circular dependency detected for singleton: ${e}`);if(n.ssrSafe===!1&&typeof window>"u"){if(n.fallbackFactory){let i=n.fallbackFactory();return this.instances.set(e,i),this.initialized.add(e),i}throw new Error(`Singleton ${e} requires client-side environment`)}this.initializing.add(e);try{let i=await r();return this.instances.set(e,i),this.initialized.add(e),i}catch(i){if(n.cacheFailures&&this.initialized.add(e),n.fallbackFactory){let o=n.fallbackFactory();return this.instances.set(e,o),this.initialized.add(e),o}throw i}finally{this.initializing.delete(e)}}static isInitialized(e){return this.initialized.has(e)}static clear(e){this.instances.delete(e),this.initialized.delete(e),this.initializing.delete(e)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function ts(t){return{_updatedAt:new Date().toISOString(),_updatedBy:t}}import"valibot";import"valibot";function rs(t){return typeof t=="object"&&t!==null&&"visibility"in t&&typeof t.visibility=="string"}function ns(t){if(rs(t))return t.visibility}function Tn(t,e){let r=t??"guest";return r==="hidden"?!1:r==="technical"?st(e,"admin"):st(e,r)}function Qt(t,e){let r=t;if(!r||typeof r!="object"||!r.entries)return[];let n=r.entries,i=[];for(let[o,s]of Object.entries(n)){let c=ns(s);Tn(c,e)&&i.push(o)}return i}function is(t,e,r){if(!t)return{};let n=Qt(e,r),i={};for(let o of n)Object.prototype.hasOwnProperty.call(t,o)&&(i[o]=t[o]);return i}function Me(t,e){let r=new Date(t),n=r.getDate();return r.setMonth(r.getMonth()+e),r.getDate()!==n&&r.setDate(0),r}function er(t,e){let r=new Date(t),n=r.getDate();return r.setFullYear(r.getFullYear()+e),r.getDate()!==n&&r.setDate(0),r}function os(t,e=new Date){if(t==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return t==="1month"?r=Me(e,1):t==="3months"?r=Me(e,3):t==="6months"?r=Me(e,6):t==="1year"?r=er(e,1):t==="2years"?r=er(e,2):r=Me(e,1),r.toISOString()}function ss(t){let e=new Date(t);if(isNaN(e.getTime()))throw new Error(`Invalid ISO date string: ${t}`);return e}function as(t,e="URL"){try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return t}catch(r){throw new Error(`Invalid ${e}: ${t}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function cs(t){let e={};for(let[r,n]of Object.entries(t)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let i=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(i.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);e[r]=i}return e}function us(t,e=!0){let r=process.env[t];if(e&&!r)throw new Error(`Required environment variable '${t}' is not set`);return r||""}function ls(t,e){if(!t)return null;let r=`${encodeURIComponent(e)}=`,n=t.split(";");for(let i=0;i<n.length;i++){let o=n[i];if(o){for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(r)===0)return decodeURIComponent(o.substring(r.length,o.length))}}return null}import*as W from"valibot";import*as d from"valibot";var Ve=new Map;function E(t,e){Ve.set(t,e)}function ff(t){return Ve.has(t)}function hf(){return Array.from(Ve.keys())}function mf(){Ve.clear()}function _(t,e){return e?t:d.nullish(t)}var at=t=>{let e=[];t.validation?.minLength!==void 0&&e.push(d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)),t.validation?.maxLength!==void 0&&e.push(d.maxLength(t.validation.maxLength,`Must be at most ${t.validation.maxLength} characters`)),t.validation?.pattern&&e.push(d.regex(new RegExp(t.validation.pattern),"Invalid format"));let r=e.length>0?d.pipe(d.string(),...e):d.string();return _(r,t.validation?.required)},ds=t=>{let e=d.pipe(d.string(),d.email("Invalid email address"));return _(e,t.validation?.required)},ps=t=>{let e=t.validation?.minLength!==void 0?d.pipe(d.string(),d.minLength(t.validation.minLength,`Must be at least ${t.validation.minLength} characters`)):d.string();return _(e,t.validation?.required)},fs=t=>{let e=d.pipe(d.string(),d.url("Invalid URL"));return _(e,t.validation?.required)},Fe=t=>{let e=[];t.validation?.min!==void 0&&e.push(d.minValue(t.validation.min,`Must be at least ${t.validation.min}`)),t.validation?.max!==void 0&&e.push(d.maxValue(t.validation.max,`Must be at most ${t.validation.max}`));let r=e.length>0?d.pipe(d.number(),...e):d.number();return _(r,t.validation?.required)},_n=t=>{let e=d.boolean();return _(e,t.validation?.required)},ge=t=>{let e=d.pipe(d.string(),d.isoTimestamp("Invalid date format"));return _(e,t.validation?.required)},Pn=d.object({url:d.string(),filename:d.string(),size:d.number(),mimeType:d.nullish(d.string()),uploadedAt:d.nullish(d.string())}),Cn=t=>{let e=d.nullable(Pn);return _(e,t.validation?.required)},An=t=>{let e=d.array(Pn);return _(e,t.validation?.required)},Rn=d.object({fullUrl:d.string(),thumbUrl:d.string()}),hs=t=>_(Rn,t.validation?.required),ms=t=>{let e=d.array(Rn);return _(e,t.validation?.required)},gs=t=>{let e=d.object({lat:d.number(),lng:d.number()});return _(e,t.validation?.required)},vs=t=>{let e=d.object({formatted_address:d.string(),latitude:d.number(),longitude:d.number(),street_number:d.nullish(d.string()),route:d.nullish(d.string()),locality:d.nullish(d.string()),administrative_area_level_1:d.nullish(d.string()),administrative_area_level_2:d.nullish(d.string()),country:d.nullish(d.string()),postal_code:d.nullish(d.string())});return _(e,t.validation?.required)},ys=t=>{let e=d.record(d.string(),d.unknown());return _(e,t.validation?.required)},Es=t=>{let e=d.array(d.unknown());return _(e,t.validation?.required)},tr=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let n=e.map(o=>o.value),i=d.picklist(n);return _(i,t.validation?.required)}let r=d.union([d.string(),d.number()]);return _(r,t.validation?.required)},bs=t=>{let e=t.validation?.options;if(Array.isArray(e)&&e.length>0){let n=e.map(o=>o.value),i=d.array(d.picklist(n));return _(i,t.validation?.required)}let r=d.array(d.string());return _(r,t.validation?.required)},Is=t=>{let e=d.pipe(d.string(),d.regex(it,"Invalid ID format"));return _(e,t.validation?.required)},rr=t=>{let e=d.string();return _(e,t.validation?.required)},Ts=t=>{let e=d.string();return _(e,t.validation?.required)},wn=()=>d.never(),Ss=t=>{let e=t.options?.fieldSpecific;if(e?.checkedValue&&e?.uncheckedValue){let n=[e.checkedValue,e.uncheckedValue],i=d.picklist(n);return _(i,t.validation?.required)}let r=d.boolean();return _(r,t.validation?.required)},_s=t=>d.custom(r=>t.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),Cs=t=>{let e=d.object({amount:d.number(),currency:d.optional(d.string()),vatIncluded:d.optional(d.boolean()),discountPercent:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(100)))});return _(e,t.validation?.required)};function As(){E("text",at),E("textarea",at),E("richtext",at),E("color",at),E("email",ds),E("password",ps),E("url",fs),E("tel",Ts),E("number",Fe),E("currency",Fe),E("price",Cs),E("range",Fe),E("year",Fe),E("rating",Fe),E("boolean",_n),E("checkbox",_n),E("gdprConsent",_s),E("date",ge),E("datetime-local",ge),E("time",ge),E("week",ge),E("month",ge),E("timestamp",ge),E("file",Cn),E("files",An),E("document",Cn),E("documents",An),E("image",hs),E("images",ms),E("geopoint",gs),E("address",vs),E("map",ys),E("array",Es),E("select",tr),E("multiselect",bs),E("radio",tr),E("combobox",tr),E("switch",Ss),E("reference",Is),E("hidden",rr),E("avatar",rr),E("badge",rr),E("submit",wn),E("reset",wn)}As();function Be(t){if(t.validation?.schema){let n=t.validation.schema;return _(n,t.validation?.required)}let e=Ve.get(t.type);if(e){let n=e(t);if(n!==null)return n}let r=d.unknown();return _(r,t.validation?.required)}var nr=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],yf="available",Ef=["draft","deleted"],ve=["id","createdAt","updatedAt","createdById","updatedById"],ws=[...ve,"status"];function bf(t){return ws.includes(t)}function If(t){return ve.includes(t)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...nr]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:it.source}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};function He(t,e){return Object.assign(t,{visibility:e})}function se(t,e){let r=t;return r.metadata={collection:e.collection,entity:e.name,...e.uniqueKeys&&{uniqueKeys:e.uniqueKeys}},r}function xn(t){let e=Be(t);return He(e,t.visibility)}function kn(t){let e=Be({...t,validation:{...t.validation,required:!1}});return He(e,t.visibility)}function Ps(t){let e=t.fields,r={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(r[R]=xn(P));let n=se(W.object(r),t),i={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(ve.includes(R)||(i[R]=xn(P)));let o=se(W.object(i),t),s={};for(let[R,P]of Object.entries(e))if(P.visibility!=="hidden"&&!ve.includes(R))if(R==="status"){let Y=W.literal("draft");s[R]=He(Y,P.visibility)}else s[R]=kn(P);let c=se(W.object(s),t),u={};for(let[R,P]of Object.entries(e))P.visibility!=="hidden"&&(ve.includes(R)||(u[R]=kn(P)));u.id=He(Be(w.id),"technical");let p=se(W.object(u),t),g;if(t.listFields&&t.listFields.length>0){let R=["id","status"],P=[...new Set([...R,...t.listFields])];g={};for(let Y of P){let Oe=r[Y];Oe&&(g[Y]=Oe)}}else g=r;let T=se(W.object(g),t),O,F=t.listCardFields??t.listFields;if(F&&F.length>0){let R=["id","status"],P=[...new Set([...R,...F])];O={};for(let Y of P){let Oe=r[Y];Oe&&(O[Y]=Oe)}}else O=r;let ne=se(W.object(O),t),rt=se(W.object({id:He(Be(w.id),"technical")}),t);return{create:o,draft:c,update:p,get:n,list:T,listCard:ne,delete:rt}}import"valibot";function xf(t,e){let r=t;return r.metadata=e,r}var Rs={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};var On=function(t){let e=[],r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=i&63|128):(i&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=i&63|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=i&63|128)}return e},xs=function(t){let e=[],r=0,n=0;for(;r<t.length;){let i=t[r++];if(i<128)e[n++]=String.fromCharCode(i);else if(i>191&&i<224){let o=t[r++];e[n++]=String.fromCharCode((i&31)<<6|o&63)}else if(i>239&&i<365){let o=t[r++],s=t[r++],c=t[r++],u=((i&7)<<18|(o&63)<<12|(s&63)<<6|c&63)-65536;e[n++]=String.fromCharCode(55296+(u>>10)),e[n++]=String.fromCharCode(56320+(u&1023))}else{let o=t[r++],s=t[r++];e[n++]=String.fromCharCode((i&15)<<12|(o&63)<<6|s&63)}}return e.join("")},Dn={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();let r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let i=0;i<t.length;i+=3){let o=t[i],s=i+1<t.length,c=s?t[i+1]:0,u=i+2<t.length,p=u?t[i+2]:0,g=o>>2,T=(o&3)<<4|c>>4,O=(c&15)<<2|p>>6,F=p&63;u||(F=64,s||(O=64)),n.push(r[g],r[T],r[O],r[F])}return n.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(On(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):xs(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let r=e?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let i=0;i<t.length;){let o=r[t.charAt(i++)],c=i<t.length?r[t.charAt(i)]:0;++i;let p=i<t.length?r[t.charAt(i)]:64;++i;let T=i<t.length?r[t.charAt(i)]:64;if(++i,o==null||c==null||p==null||T==null)throw new or;let O=o<<2|c>>4;if(n.push(O),p!==64){let F=c<<4&240|p>>2;if(n.push(F),T!==64){let ne=p<<6&192|T;n.push(ne)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},or=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},ks=function(t){let e=On(t);return Dn.encodeByteArray(e,!0)},ar=function(t){return ks(t).replace(/\./g,"")},cr=function(t){try{return Dn.decodeString(t,!0)}catch{}return null};function ur(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}function B(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Nn(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(B())}function Un(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function Ln(){let t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function Mn(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Fn(){try{return typeof indexedDB=="object"}catch{return!1}}function Vn(){return new Promise((t,e)=>{try{let r=!0,n="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(n);i.onsuccess=()=>{i.result.close(),r||self.indexedDB.deleteDatabase(n),t(!0)},i.onupgradeneeded=()=>{r=!1},i.onerror=()=>{e(i.error?.message||"")}}catch(r){e(r)}})}var Os="FirebaseError",q=class t extends Error{constructor(e,r,n){super(r),this.code=e,this.customData=n,this.name=Os,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,J.prototype.create)}},J=class{constructor(e,r,n){this.service=e,this.serviceName=r,this.errors=n}create(e,...r){let n=r[0]||{},i=`${this.service}/${e}`,o=this.errors[e],s=o?Ds(o,n):"Error",c=`${this.serviceName}: ${s} (${i}).`;return new q(i,c,n)}};function Ds(t,e){return t.replace(Ns,(r,n)=>{let i=e[n];return i!=null?String(i):`<${n}?>`})}var Ns=/\{\$([^}]+)}/g;function ct(t){let e=[];for(let[r,n]of Object.entries(t))Array.isArray(n)?n.forEach(i=>{e.push(encodeURIComponent(r)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return e.length?"&"+e.join("&"):""}function ye(t){let e={};return t.replace(/^\?/,"").split("&").forEach(n=>{if(n){let[i,o]=n.split("=");e[decodeURIComponent(i)]=decodeURIComponent(o)}}),e}function Ee(t){let e=t.indexOf("?");if(!e)return"";let r=t.indexOf("#",e);return t.substring(e,r>0?r:void 0)}function Bn(t,e){let r=new sr(t,e);return r.subscribe.bind(r)}var sr=class{constructor(e,r){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=r,this.task.then(()=>{e(this)}).catch(n=>{this.error(n)})}next(e){this.forEachObserver(r=>{r.next(e)})}error(e){this.forEachObserver(r=>{r.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,r,n){let i;if(e===void 0&&r===void 0&&n===void 0)throw new Error("Missing Observer.");Us(e,["next","error","complete"])?i=e:i={next:e,error:r,complete:n},i.next===void 0&&(i.next=ir),i.error===void 0&&(i.error=ir),i.complete===void 0&&(i.complete=ir);let o=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),o}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let r=0;r<this.observers.length;r++)this.sendOne(r,e)}sendOne(e,r){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{r(this.observers[e])}catch{}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}};function Us(t,e){if(typeof t!="object"||t===null)return!1;for(let r of e)if(r in t&&typeof t[r]=="function")return!0;return!1}function ir(){}var Uf=14400*1e3;function $e(t){return t&&t._delegate?t._delegate:t}Rs.NODE_CLIENT=!0;var X=class{constructor(e,r,n){this.name=e,this.instanceFactory=r,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var Ls=[],S;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(S||(S={}));var Ms={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},Fs=S.INFO,Vs={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},Bs=(t,e,...r)=>{if(e<t.logLevel)return;let n=new Date().toISOString(),i=Vs[e];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},be=class{constructor(e){this.name=e,this._logLevel=Fs,this._logHandler=Bs,this._userLogHandler=null,Ls.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in S))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?Ms[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,S.DEBUG,...e),this._logHandler(this,S.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,S.VERBOSE,...e),this._logHandler(this,S.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,S.INFO,...e),this._logHandler(this,S.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,S.WARN,...e),this._logHandler(this,S.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,S.ERROR,...e),this._logHandler(this,S.ERROR,...e)}};var Hs=(t,e)=>e.some(r=>t instanceof r),Hn,$n;function $s(){return Hn||(Hn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ws(){return $n||($n=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Wn=new WeakMap,dr=new WeakMap,qn=new WeakMap,lr=new WeakMap,fr=new WeakMap;function qs(t){let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("success",o),t.removeEventListener("error",s)},o=()=>{r(G(t.result)),i()},s=()=>{n(t.error),i()};t.addEventListener("success",o),t.addEventListener("error",s)});return e.then(r=>{r instanceof IDBCursor&&Wn.set(r,t)}).catch(()=>{}),fr.set(e,t),e}function Gs(t){if(dr.has(t))return;let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("complete",o),t.removeEventListener("error",s),t.removeEventListener("abort",s)},o=()=>{r(),i()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",o),t.addEventListener("error",s),t.addEventListener("abort",s)});dr.set(t,e)}var pr={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return dr.get(t);if(e==="objectStoreNames")return t.objectStoreNames||qn.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return G(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function Gn(t){pr=t(pr)}function js(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(ut(this),e,...r);return qn.set(n,e.sort?e.sort():[e]),G(n)}:Ws().includes(t)?function(...e){return t.apply(ut(this),e),G(Wn.get(this))}:function(...e){return G(t.apply(ut(this),e))}}function Ks(t){return typeof t=="function"?js(t):(t instanceof IDBTransaction&&Gs(t),Hs(t,$s())?new Proxy(t,pr):t)}function G(t){if(t instanceof IDBRequest)return qs(t);if(lr.has(t))return lr.get(t);let e=Ks(t);return e!==t&&(lr.set(t,e),fr.set(e,t)),e}var ut=t=>fr.get(t);function Kn(t,e,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){let s=indexedDB.open(t,e),c=G(s);return n&&s.addEventListener("upgradeneeded",u=>{n(G(s.result),u.oldVersion,u.newVersion,G(s.transaction),u)}),r&&s.addEventListener("blocked",u=>r(u.oldVersion,u.newVersion,u)),c.then(u=>{o&&u.addEventListener("close",()=>o()),i&&u.addEventListener("versionchange",p=>i(p.oldVersion,p.newVersion,p))}).catch(()=>{}),c}var zs=["get","getKey","getAll","getAllKeys","count"],Ys=["put","add","delete","clear"],hr=new Map;function jn(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(hr.get(e))return hr.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,i=Ys.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||zs.includes(r)))return;let o=async function(s,...c){let u=this.transaction(s,i?"readwrite":"readonly"),p=u.store;return n&&(p=p.index(c.shift())),(await Promise.all([p[r](...c),i&&u.done]))[0]};return hr.set(e,o),o}Gn(t=>({...t,get:(e,r,n)=>jn(e,r)||t.get(e,r,n),has:(e,r)=>!!jn(e,r)||t.has(e,r)}));var gr=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(r=>{if(Xs(r)){let n=r.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(r=>r).join(" ")}};function Xs(t){return t.getComponent()?.type==="VERSION"}var vr="@firebase/app",zn="0.14.7";var Z=new be("@firebase/app"),Zs="@firebase/app-compat",Qs="@firebase/analytics-compat",ea="@firebase/analytics",ta="@firebase/app-check-compat",ra="@firebase/app-check",na="@firebase/auth",ia="@firebase/auth-compat",oa="@firebase/database",sa="@firebase/data-connect",aa="@firebase/database-compat",ca="@firebase/functions",ua="@firebase/functions-compat",la="@firebase/installations",da="@firebase/installations-compat",pa="@firebase/messaging",fa="@firebase/messaging-compat",ha="@firebase/performance",ma="@firebase/performance-compat",ga="@firebase/remote-config",va="@firebase/remote-config-compat",ya="@firebase/storage",Ea="@firebase/storage-compat",ba="@firebase/firestore",Ia="@firebase/ai",Ta="@firebase/firestore-compat",Sa="firebase",_a="12.8.0";var Ca={[vr]:"fire-core",[Zs]:"fire-core-compat",[ea]:"fire-analytics",[Qs]:"fire-analytics-compat",[ra]:"fire-app-check",[ta]:"fire-app-check-compat",[na]:"fire-auth",[ia]:"fire-auth-compat",[oa]:"fire-rtdb",[sa]:"fire-data-connect",[aa]:"fire-rtdb-compat",[ca]:"fire-fn",[ua]:"fire-fn-compat",[la]:"fire-iid",[da]:"fire-iid-compat",[pa]:"fire-fcm",[fa]:"fire-fcm-compat",[ha]:"fire-perf",[ma]:"fire-perf-compat",[ga]:"fire-rc",[va]:"fire-rc-compat",[ya]:"fire-gcs",[Ea]:"fire-gcs-compat",[ba]:"fire-fst",[Ta]:"fire-fst-compat",[Ia]:"fire-vertex","fire-js":"fire-js",[Sa]:"fire-js-all"};var Aa=new Map,wa=new Map,Yn=new Map;function Jn(t,e){try{t.container.addComponent(e)}catch(r){Z.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,r)}}function Te(t){let e=t.name;if(Yn.has(e))return Z.debug(`There were multiple attempts to register component ${e}.`),!1;Yn.set(e,t);for(let r of Aa.values())Jn(r,t);for(let r of wa.values())Jn(r,t);return!0}function ae(t){return t==null?!1:t.settings!==void 0}var Pa={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},br=new J("app","Firebase",Pa);var lt=_a;function Ie(t,e,r){let n=Ca[t]??t;r&&(n+=`-${r}`);let i=n.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let s=[`Unable to register library "${n}" with version "${e}":`];i&&s.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&o&&s.push("and"),o&&s.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Z.warn(s.join(" "));return}Te(new X(`${n}-version`,()=>({library:n,version:e}),"VERSION"))}var Ra="firebase-heartbeat-database",xa=1,We="firebase-heartbeat-store",mr=null;function ei(){return mr||(mr=Kn(Ra,xa,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(We)}catch{}}}}).catch(t=>{throw br.create("idb-open",{originalErrorMessage:t.message})})),mr}async function ka(t){try{let r=(await ei()).transaction(We),n=await r.objectStore(We).get(ti(t));return await r.done,n}catch(e){if(e instanceof q)Z.warn(e.message);else{let r=br.create("idb-get",{originalErrorMessage:e?.message});Z.warn(r.message)}}}async function Xn(t,e){try{let n=(await ei()).transaction(We,"readwrite");await n.objectStore(We).put(e,ti(t)),await n.done}catch(r){if(r instanceof q)Z.warn(r.message);else{let n=br.create("idb-set",{originalErrorMessage:r?.message});Z.warn(n.message)}}}function ti(t){return`${t.name}!${t.options.appId}`}var Oa=1024,Da=30,yr=class{constructor(e){this.container=e,this._heartbeatsCache=null;let r=this.container.getProvider("app").getImmediate();this._storage=new Er(r),this._heartbeatsCachePromise=this._storage.read().then(n=>(this._heartbeatsCache=n,n))}async triggerHeartbeat(){try{let r=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),n=Zn();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===n||this._heartbeatsCache.heartbeats.some(i=>i.date===n))return;if(this._heartbeatsCache.heartbeats.push({date:n,agent:r}),this._heartbeatsCache.heartbeats.length>Da){let i=Ua(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){Z.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";let e=Zn(),{heartbeatsToSend:r,unsentEntries:n}=Na(this._heartbeatsCache.heartbeats),i=ar(JSON.stringify({version:2,heartbeats:r}));return this._heartbeatsCache.lastSentHeartbeatDate=e,n.length>0?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Z.warn(e),""}}};function Zn(){return new Date().toISOString().substring(0,10)}function Na(t,e=Oa){let r=[],n=t.slice();for(let i of t){let o=r.find(s=>s.agent===i.agent);if(o){if(o.dates.push(i.date),Qn(r)>e){o.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),Qn(r)>e){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}}var Er=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Fn()?Vn().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let r=await ka(this.app);return r?.heartbeats?r:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let n=await this.read();return Xn(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let n=await this.read();return Xn(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}else return}};function Qn(t){return ar(JSON.stringify({version:2,heartbeats:t})).length}function Ua(t){if(t.length===0)return-1;let e=0,r=t[0].date;for(let n=1;n<t.length;n++)t[n].date<r&&(r=t[n].date,e=n);return e}function La(t){Te(new X("platform-logger",e=>new gr(e),"PRIVATE")),Te(new X("heartbeat",e=>new yr(e),"PRIVATE")),Ie(vr,zn,t),Ie(vr,zn,"esm2020"),Ie("fire-js","")}La("");function li(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}var di=li,pi=new J("auth","Firebase",li());var mt=new be("@firebase/auth");function Ma(t,...e){mt.logLevel<=S.WARN&&mt.warn(`Auth (${lt}): ${t}`,...e)}function ft(t,...e){mt.logLevel<=S.ERROR&&mt.error(`Auth (${lt}): ${t}`,...e)}function Se(t,...e){throw Vr(t,...e)}function Fr(t,...e){return Vr(t,...e)}function fi(t,e,r){let n={...di(),[e]:r};return new J("auth","Firebase",n).create(e,{appName:t.name})}function ht(t){return fi(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Vr(t,...e){if(typeof t!="string"){let r=e[0],n=[...e.slice(1)];return n[0]&&(n[0].appName=t.name),t._errorFactory.create(r,...n)}return pi.create(t,...e)}function I(t,e,...r){if(!t)throw Vr(e,...r)}function j(t){let e="INTERNAL ASSERTION FAILED: "+t;throw ft(e),new Error(e)}function gt(t,e){t||j(e)}function Fa(){return ri()==="http:"||ri()==="https:"}function ri(){return typeof self<"u"&&self.location?.protocol||null}function Va(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(Fa()||Ln()||"connection"in navigator)?navigator.onLine:!0}function Ba(){if(typeof navigator>"u")return null;let t=navigator;return t.languages&&t.languages[0]||t.language||null}var _r=class{constructor(e,r){this.shortDelay=e,this.longDelay=r,gt(r>e,"Short delay should be less than long delay!"),this.isMobile=Nn()||Mn()}get(){return Va()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};function Ha(t,e){gt(t.emulator,"Emulator should always be set here");let{url:r}=t.emulator;return e?`${r}${e.startsWith("/")?e.slice(1):e}`:r}var Ke=class{static initialize(e,r,n){this.fetchImpl=e,r&&(this.headersImpl=r),n&&(this.responseImpl=n)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;j("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;j("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;j("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};var $a={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};var Wa=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],qa=new _r(3e4,6e4);function K(t,e){return t.tenantId&&!e.tenantId?{...e,tenantId:t.tenantId}:e}async function z(t,e,r,n,i={}){return hi(t,i,async()=>{let o={},s={};n&&(e==="GET"?s=n:o={body:JSON.stringify(n)});let c=ct({key:t.config.apiKey,...s}).slice(1),u=await t._getAdditionalHeaders();u["Content-Type"]="application/json",t.languageCode&&(u["X-Firebase-Locale"]=t.languageCode);let p={method:e,headers:u,...o};return Un()||(p.referrerPolicy="no-referrer"),t.emulatorConfig&&ur(t.emulatorConfig.host)&&(p.credentials="include"),Ke.fetch()(await mi(t,t.config.apiHost,r,c),p)})}async function hi(t,e,r){t._canInitEmulator=!1;let n={...$a,...e};try{let i=new Cr(t),o=await Promise.race([r(),i.promise]);i.clearNetworkTimeout();let s=await o.json();if("needConfirmation"in s)throw dt(t,"account-exists-with-different-credential",s);if(o.ok&&!("errorMessage"in s))return s;{let c=o.ok?s.errorMessage:s.error.message,[u,p]=c.split(" : ");if(u==="FEDERATED_USER_ID_ALREADY_LINKED")throw dt(t,"credential-already-in-use",s);if(u==="EMAIL_EXISTS")throw dt(t,"email-already-in-use",s);if(u==="USER_DISABLED")throw dt(t,"user-disabled",s);let g=n[u]||u.toLowerCase().replace(/[_\s]+/g,"-");if(p)throw fi(t,g,p);Se(t,g)}}catch(i){if(i instanceof q)throw i;Se(t,"network-request-failed",{message:String(i)})}}async function wt(t,e,r,n,i={}){let o=await z(t,e,r,n,i);return"mfaPendingCredential"in o&&Se(t,"multi-factor-auth-required",{_serverResponse:o}),o}async function mi(t,e,r,n){let i=`${e}${r}?${n}`,o=t,s=o.config.emulator?Ha(t.config,i):`${t.config.apiScheme}://${i}`;return Wa.includes(r)&&(await o._persistenceManagerAvailable,o._getPersistenceType()==="COOKIE")?o._getPersistence()._getFinalTarget(s).toString():s}function Ga(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}var Cr=class{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((r,n)=>{this.timer=setTimeout(()=>n(Fr(this.auth,"network-request-failed")),qa.get())})}};function dt(t,e,r){let n={appName:t.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);let i=Fr(t,e,n);return i.customData._tokenResponse=r,i}function ni(t){return t!==void 0&&t.enterprise!==void 0}var Ar=class{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(let r of this.recaptchaEnforcementState)if(r.provider&&r.provider===e)return Ga(r.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}};async function ja(t,e){return z(t,"GET","/v2/recaptchaConfig",K(t,e))}async function Ka(t,e){return z(t,"POST","/v1/accounts:delete",e)}async function vt(t,e){return z(t,"POST","/v1/accounts:lookup",e)}function Ge(t){if(t)try{let e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function gi(t,e=!1){let r=$e(t),n=await r.getIdToken(e),i=vi(n);I(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");let o=typeof i.firebase=="object"?i.firebase:void 0,s=o?.sign_in_provider;return{claims:i,token:n,authTime:Ge(Ir(i.auth_time)),issuedAtTime:Ge(Ir(i.iat)),expirationTime:Ge(Ir(i.exp)),signInProvider:s||null,signInSecondFactor:o?.sign_in_second_factor||null}}function Ir(t){return Number(t)*1e3}function vi(t){let[e,r,n]=t.split(".");if(e===void 0||r===void 0||n===void 0)return ft("JWT malformed, contained fewer than 3 sections"),null;try{let i=cr(r);return i?JSON.parse(i):(ft("Failed to decode base64 JWT payload"),null)}catch(i){return ft("Caught error parsing JWT payload as JSON",i?.toString()),null}}function ii(t){let e=vi(t);return I(e,"internal-error"),I(typeof e.exp<"u","internal-error"),I(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function wr(t,e,r=!1){if(r)return e;try{return await e}catch(n){throw n instanceof q&&za(n)&&t.auth.currentUser===t&&await t.auth.signOut(),n}}function za({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}var Pr=class{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){if(e){let r=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),r}else{this.errorBackoff=3e4;let n=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,n)}}schedule(e=!1){if(!this.isRunning)return;let r=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},r)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};var ze=class{constructor(e,r){this.createdAt=e,this.lastLoginAt=r,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ge(this.lastLoginAt),this.creationTime=Ge(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};async function yt(t){let e=t.auth,r=await t.getIdToken(),n=await wr(t,vt(e,{idToken:r}));I(n?.users.length,e,"internal-error");let i=n.users[0];t._notifyReloadListener(i);let o=i.providerUserInfo?.length?Ei(i.providerUserInfo):[],s=Ya(t.providerData,o),c=t.isAnonymous,u=!(t.email&&i.passwordHash)&&!s?.length,p=c?u:!1,g={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:s,metadata:new ze(i.createdAt,i.lastLoginAt),isAnonymous:p};Object.assign(t,g)}async function yi(t){let e=$e(t);await yt(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function Ya(t,e){return[...t.filter(n=>!e.some(i=>i.providerId===n.providerId)),...e]}function Ei(t){return t.map(({providerId:e,...r})=>({providerId:e,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}))}async function Ja(t,e){let r=await hi(t,{},async()=>{let n=ct({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:i,apiKey:o}=t.config,s=await mi(t,i,"/v1/token",`key=${o}`),c=await t._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";let u={method:"POST",headers:c,body:n};return t.emulatorConfig&&ur(t.emulatorConfig.host)&&(u.credentials="include"),Ke.fetch()(s,u)});return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}async function Xa(t,e){return z(t,"POST","/v2/accounts:revokeToken",K(t,e))}var je=class t{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){I(e.idToken,"internal-error"),I(typeof e.idToken<"u","internal-error"),I(typeof e.refreshToken<"u","internal-error");let r="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):ii(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,r)}updateFromIdToken(e){I(e.length!==0,"internal-error");let r=ii(e);this.updateTokensAndExpiration(e,null,r)}async getToken(e,r=!1){return!r&&this.accessToken&&!this.isExpired?this.accessToken:(I(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,r){let{accessToken:n,refreshToken:i,expiresIn:o}=await Ja(e,r);this.updateTokensAndExpiration(n,i,Number(o))}updateTokensAndExpiration(e,r,n){this.refreshToken=r||null,this.accessToken=e||null,this.expirationTime=Date.now()+n*1e3}static fromJSON(e,r){let{refreshToken:n,accessToken:i,expirationTime:o}=r,s=new t;return n&&(I(typeof n=="string","internal-error",{appName:e}),s.refreshToken=n),i&&(I(typeof i=="string","internal-error",{appName:e}),s.accessToken=i),o&&(I(typeof o=="number","internal-error",{appName:e}),s.expirationTime=o),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new t,this.toJSON())}_performRefresh(){return j("not implemented")}};function ee(t,e){I(typeof t=="string"||typeof t>"u","internal-error",{appName:e})}var ce=class t{constructor({uid:e,auth:r,stsTokenManager:n,...i}){this.providerId="firebase",this.proactiveRefresh=new Pr(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=r,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new ze(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){let r=await wr(this,this.stsTokenManager.getToken(this.auth,e));return I(r,this.auth,"internal-error"),this.accessToken!==r&&(this.accessToken=r,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),r}getIdTokenResult(e){return gi(this,e)}reload(){return yi(this)}_assign(e){this!==e&&(I(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(r=>({...r})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let r=new t({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return r.metadata._copy(this.metadata),r}_onReload(e){I(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,r=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),r&&await yt(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(ae(this.auth.app))return Promise.reject(ht(this.auth));let e=await this.getIdToken();return await wr(this,Ka(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,r){let n=r.displayName??void 0,i=r.email??void 0,o=r.phoneNumber??void 0,s=r.photoURL??void 0,c=r.tenantId??void 0,u=r._redirectEventId??void 0,p=r.createdAt??void 0,g=r.lastLoginAt??void 0,{uid:T,emailVerified:O,isAnonymous:F,providerData:ne,stsTokenManager:rt}=r;I(T&&rt,e,"internal-error");let R=je.fromJSON(this.name,rt);I(typeof T=="string",e,"internal-error"),ee(n,e.name),ee(i,e.name),I(typeof O=="boolean",e,"internal-error"),I(typeof F=="boolean",e,"internal-error"),ee(o,e.name),ee(s,e.name),ee(c,e.name),ee(u,e.name),ee(p,e.name),ee(g,e.name);let P=new t({uid:T,auth:e,email:i,emailVerified:O,displayName:n,isAnonymous:F,photoURL:s,phoneNumber:o,tenantId:c,stsTokenManager:R,createdAt:p,lastLoginAt:g});return ne&&Array.isArray(ne)&&(P.providerData=ne.map(Y=>({...Y}))),u&&(P._redirectEventId=u),P}static async _fromIdTokenResponse(e,r,n=!1){let i=new je;i.updateFromServerResponse(r);let o=new t({uid:r.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await yt(o),o}static async _fromGetAccountInfoResponse(e,r,n){let i=r.users[0];I(i.localId!==void 0,"internal-error");let o=i.providerUserInfo!==void 0?Ei(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!o?.length,c=new je;c.updateFromIdToken(n);let u=new t({uid:i.localId,auth:e,stsTokenManager:c,isAnonymous:s}),p={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new ze(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!o?.length};return Object.assign(u,p),u}};var oi=new Map;function ue(t){gt(t instanceof Function,"Expected a class definition");let e=oi.get(t);return e?(gt(e instanceof t,"Instance stored in cache mismatched with class"),e):(e=new t,oi.set(t,e),e)}var Et=class{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,r){this.storage[e]=r}async _get(e){let r=this.storage[e];return r===void 0?null:r}async _remove(e){delete this.storage[e]}_addListener(e,r){}_removeListener(e,r){}};Et.type="NONE";var Rr=Et;function Tr(t,e,r){return`firebase:${t}:${e}:${r}`}var bt=class t{constructor(e,r,n){this.persistence=e,this.auth=r,this.userKey=n;let{config:i,name:o}=this.auth;this.fullUserKey=Tr(this.userKey,i.apiKey,o),this.fullPersistenceKey=Tr("persistence",i.apiKey,o),this.boundEventHandler=r._onStorageEvent.bind(r),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){let e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){let r=await vt(this.auth,{idToken:e}).catch(()=>{});return r?ce._fromGetAccountInfoResponse(this.auth,r,e):null}return ce._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let r=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,r)return this.setCurrentUser(r)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,r,n="authUser"){if(!r.length)return new t(ue(Rr),e,n);let i=(await Promise.all(r.map(async p=>{if(await p._isAvailable())return p}))).filter(p=>p),o=i[0]||ue(Rr),s=Tr(n,e.config.apiKey,e.name),c=null;for(let p of r)try{let g=await p._get(s);if(g){let T;if(typeof g=="string"){let O=await vt(e,{idToken:g}).catch(()=>{});if(!O)break;T=await ce._fromGetAccountInfoResponse(e,O,g)}else T=ce._fromJSON(e,g);p!==o&&(c=T),o=p;break}}catch{}let u=i.filter(p=>p._shouldAllowMigration);return!o._shouldAllowMigration||!u.length?new t(o,e,n):(o=u[0],c&&await o._set(s,c.toJSON()),await Promise.all(r.map(async p=>{if(p!==o)try{await p._remove(s)}catch{}})),new t(o,e,n))}};function si(t){let e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(tc(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Za(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(nc(e))return"Blackberry";if(ic(e))return"Webos";if(Qa(e))return"Safari";if((e.includes("chrome/")||ec(e))&&!e.includes("edge/"))return"Chrome";if(rc(e))return"Android";{let r=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=t.match(r);if(n?.length===2)return n[1]}return"Other"}function Za(t=B()){return/firefox\//i.test(t)}function Qa(t=B()){let e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function ec(t=B()){return/crios\//i.test(t)}function tc(t=B()){return/iemobile/i.test(t)}function rc(t=B()){return/android/i.test(t)}function nc(t=B()){return/blackberry/i.test(t)}function ic(t=B()){return/webos/i.test(t)}function bi(t,e=[]){let r;switch(t){case"Browser":r=si(B());break;case"Worker":r=`${si(B())}-${t}`;break;default:r=t}let n=e.length?e.join(","):"FirebaseCore-web";return`${r}/JsCore/${lt}/${n}`}var xr=class{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,r){let n=o=>new Promise((s,c)=>{try{let u=e(o);s(u)}catch(u){c(u)}});n.onAbort=r,this.queue.push(n);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let r=[];try{for(let n of this.queue)await n(e),n.onAbort&&r.push(n.onAbort)}catch(n){r.reverse();for(let i of r)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:n?.message})}}};async function oc(t,e={}){return z(t,"GET","/v2/passwordPolicy",K(t,e))}var sc=6,kr=class{constructor(e){let r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=r.minPasswordLength??sc,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),r.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),r.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),r.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),r.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){let r={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,r),this.validatePasswordCharacterOptions(e,r),r.isValid&&(r.isValid=r.meetsMinPasswordLength??!0),r.isValid&&(r.isValid=r.meetsMaxPasswordLength??!0),r.isValid&&(r.isValid=r.containsLowercaseLetter??!0),r.isValid&&(r.isValid=r.containsUppercaseLetter??!0),r.isValid&&(r.isValid=r.containsNumericCharacter??!0),r.isValid&&(r.isValid=r.containsNonAlphanumericCharacter??!0),r}validatePasswordLengthOptions(e,r){let n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(r.meetsMinPasswordLength=e.length>=n),i&&(r.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,r){this.updatePasswordCharacterOptionsStatuses(r,!1,!1,!1,!1);let n;for(let i=0;i<e.length;i++)n=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(r,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,r,n,i,o){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=r)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=o))}};var It=class{constructor(e,r,n,i){this.app=e,this.heartbeatServiceProvider=r,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Tt(this),this.idTokenSubscription=new Tt(this),this.beforeStateQueue=new xr(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=pi,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(o=>this._resolvePersistenceManagerAvailable=o)}_initializeWithPersistence(e,r){return r&&(this._popupRedirectResolver=ue(r)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await bt.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(r),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{let r=await vt(this,{idToken:e}),n=await ce._fromGetAccountInfoResponse(this,r,e);await this.directlySetCurrentUser(n)}catch{await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(ae(this.app)){let o=this.app.settings.authIdToken;return o?new Promise(s=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(s,s))}):this.directlySetCurrentUser(null)}let r=await this.assertedPersistence.getCurrentUser(),n=r,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let o=this.redirectUser?._redirectEventId,s=n?._redirectEventId,c=await this.tryRedirectSignIn(e);(!o||o===s)&&c?.user&&(n=c.user,i=!0)}if(!n)return this.directlySetCurrentUser(null);if(!n._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(n)}catch(o){n=r,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(o))}return n?this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}return I(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)}async tryRedirectSignIn(e){let r=null;try{r=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return r}async reloadAndSetCurrentUserOrClear(e){try{await yt(e)}catch(r){if(r?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=Ba()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(ae(this.app))return Promise.reject(ht(this));let r=e?$e(e):null;return r&&I(r.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,r=!1){if(!this._deleted)return e&&I(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),r||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return ae(this.app)?Promise.reject(ht(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return ae(this.app)?Promise.reject(ht(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(ue(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let r=this._getPasswordPolicyInternal();return r.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):r.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=await oc(this),r=new kr(e);this.tenantId===null?this._projectPasswordPolicy=r:this._tenantPasswordPolicies[this.tenantId]=r}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new J("auth","Firebase",e())}onAuthStateChanged(e,r,n){return this.registerStateListener(this.authStateSubscription,e,r,n)}beforeAuthStateChanged(e,r){return this.beforeStateQueue.pushCallback(e,r)}onIdTokenChanged(e,r,n){return this.registerStateListener(this.idTokenSubscription,e,r,n)}authStateReady(){return new Promise((e,r)=>{if(this.currentUser)e();else{let n=this.onAuthStateChanged(()=>{n(),e()},r)}})}async revokeAccessToken(e){if(this.currentUser){let r=await this.currentUser.getIdToken(),n={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:r};this.tenantId!=null&&(n.tenantId=this.tenantId),await Xa(this,n)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,r){let n=await this.getOrInitRedirectPersistenceManager(r);return e===null?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let r=e&&ue(e)||this._popupRedirectResolver;I(r,this,"argument-error"),this.redirectPersistenceManager=await bt.create(this,[ue(r._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,r,n,i){if(this._deleted)return()=>{};let o=typeof r=="function"?r:r.next.bind(r),s=!1,c=this._isInitialized?Promise.resolve():this._initializationPromise;if(I(c,this,"internal-error"),c.then(()=>{s||o(this.currentUser)}),typeof r=="function"){let u=e.addObserver(r,n,i);return()=>{s=!0,u()}}else{let u=e.addObserver(r);return()=>{s=!0,u()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return I(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=bi(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){let e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);let r=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();r&&(e["X-Firebase-Client"]=r);let n=await this._getAppCheckToken();return n&&(e["X-Firebase-AppCheck"]=n),e}async _getAppCheckToken(){if(ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&Ma(`Error while retrieving App Check token: ${e.error}`),e?.token}};function Ii(t){return $e(t)}var Tt=class{constructor(e){this.auth=e,this.observer=null,this.addObserver=Bn(r=>this.observer=r)}get next(){return I(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};var Ti={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function ac(t){return Ti.loadJS(t)}function cc(){return Ti.recaptchaEnterpriseScript}var Or=class{constructor(){this.enterprise=new Dr}ready(e){e()}execute(e,r){return Promise.resolve("token")}render(e,r){return""}},Dr=class{ready(e){e()}execute(e,r){return Promise.resolve("token")}render(e,r){return""}},uc="recaptcha-enterprise",Si="NO_RECAPTCHA",Nr=class{constructor(e){this.type=uc,this.auth=Ii(e)}async verify(e="verify",r=!1){async function n(o){if(!r){if(o.tenantId==null&&o._agentRecaptchaConfig!=null)return o._agentRecaptchaConfig.siteKey;if(o.tenantId!=null&&o._tenantRecaptchaConfigs[o.tenantId]!==void 0)return o._tenantRecaptchaConfigs[o.tenantId].siteKey}return new Promise(async(s,c)=>{ja(o,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(u=>{if(u.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{let p=new Ar(u);return o.tenantId==null?o._agentRecaptchaConfig=p:o._tenantRecaptchaConfigs[o.tenantId]=p,s(p.siteKey)}}).catch(u=>{c(u)})})}function i(o,s,c){let u=window.grecaptcha;ni(u)?u.enterprise.ready(()=>{u.enterprise.execute(o,{action:e}).then(p=>{s(p)}).catch(()=>{s(Si)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new Or().execute("siteKey",{action:"verify"}):new Promise((o,s)=>{n(this.auth).then(c=>{if(!r&&ni(window.grecaptcha))i(c,o,s);else{if(typeof window>"u"){s(new Error("RecaptchaVerifier is only supported in browser"));return}let u=cc();u.length!==0&&(u+=c),ac(u).then(()=>{i(c,o,s)}).catch(p=>{s(p)})}}).catch(c=>{s(c)})})}};async function qe(t,e,r,n=!1,i=!1){let o=new Nr(t),s;if(i)s=Si;else try{s=await o.verify(r)}catch{s=await o.verify(r,!0)}let c={...e};if(r==="mfaSmsEnrollment"||r==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){let u=c.phoneEnrollmentInfo.phoneNumber,p=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:u,recaptchaToken:p,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){let u=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:u,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return n?Object.assign(c,{captchaResp:s}):Object.assign(c,{captchaResponse:s}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function ai(t,e,r,n,i){if(i==="EMAIL_PASSWORD_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){let o=await qe(t,e,r,r==="getOobCode");return n(t,o)}else return n(t,e).catch(async o=>{if(o.code==="auth/missing-recaptcha-token"){let s=await qe(t,e,r,r==="getOobCode");return n(t,s)}else return Promise.reject(o)});else if(i==="PHONE_PROVIDER")if(t._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let o=await qe(t,e,r);return n(t,o).catch(async s=>{if(t._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"&&(s.code==="auth/missing-recaptcha-token"||s.code==="auth/invalid-app-credential")){let c=await qe(t,e,r,!1,!0);return n(t,c)}return Promise.reject(s)})}else{let o=await qe(t,e,r,!1,!0);return n(t,o)}else return Promise.reject(i+" provider is not supported.")}function lc(t,e){let r=e?.persistence||[],n=(Array.isArray(r)?r:[r]).map(ue);e?.errorMap&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(n,e?.popupRedirectResolver)}var Ye=class{constructor(e,r){this.providerId=e,this.signInMethod=r}toJSON(){return j("not implemented")}_getIdTokenResponse(e){return j("not implemented")}_linkToIdToken(e,r){return j("not implemented")}_getReauthenticationResolver(e){return j("not implemented")}};async function dc(t,e){return z(t,"POST","/v1/accounts:signUp",e)}async function pc(t,e){return wt(t,"POST","/v1/accounts:signInWithPassword",K(t,e))}async function fc(t,e){return wt(t,"POST","/v1/accounts:signInWithEmailLink",K(t,e))}async function hc(t,e){return wt(t,"POST","/v1/accounts:signInWithEmailLink",K(t,e))}var Je=class t extends Ye{constructor(e,r,n,i=null){super("password",n),this._email=e,this._password=r,this._tenantId=i}static _fromEmailAndPassword(e,r){return new t(e,r,"password")}static _fromEmailAndCode(e,r,n=null){return new t(e,r,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let r=typeof e=="string"?JSON.parse(e):e;if(r?.email&&r?.password){if(r.signInMethod==="password")return this._fromEmailAndPassword(r.email,r.password);if(r.signInMethod==="emailLink")return this._fromEmailAndCode(r.email,r.password,r.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let r={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return ai(e,r,"signInWithPassword",pc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return fc(e,{email:this._email,oobCode:this._password});default:Se(e,"internal-error")}}async _linkToIdToken(e,r){switch(this.signInMethod){case"password":let n={idToken:r,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return ai(e,n,"signUpPassword",dc,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return hc(e,{idToken:r,email:this._email,oobCode:this._password});default:Se(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};async function Sr(t,e){return wt(t,"POST","/v1/accounts:signInWithIdp",K(t,e))}var mc="http://localhost",le=class t extends Ye{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let r=new t(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(r.idToken=e.idToken),e.accessToken&&(r.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(r.nonce=e.nonce),e.pendingToken&&(r.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(r.accessToken=e.oauthToken,r.secret=e.oauthTokenSecret):Se("argument-error"),r}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let r=typeof e=="string"?JSON.parse(e):e,{providerId:n,signInMethod:i,...o}=r;if(!n||!i)return null;let s=new t(n,i);return s.idToken=o.idToken||void 0,s.accessToken=o.accessToken||void 0,s.secret=o.secret,s.nonce=o.nonce,s.pendingToken=o.pendingToken||null,s}_getIdTokenResponse(e){let r=this.buildRequest();return Sr(e,r)}_linkToIdToken(e,r){let n=this.buildRequest();return n.idToken=r,Sr(e,n)}_getReauthenticationResolver(e){let r=this.buildRequest();return r.autoCreate=!1,Sr(e,r)}buildRequest(){let e={requestUri:mc,returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let r={};this.idToken&&(r.id_token=this.idToken),this.accessToken&&(r.access_token=this.accessToken),this.secret&&(r.oauth_token_secret=this.secret),r.providerId=this.providerId,this.nonce&&!this.pendingToken&&(r.nonce=this.nonce),e.postBody=ct(r)}return e}};function gc(t){switch(t){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}function vc(t){let e=ye(Ee(t)).link,r=e?ye(Ee(e)).deep_link_id:null,n=ye(Ee(t)).deep_link_id;return(n?ye(Ee(n)).link:null)||n||r||e||t}var St=class t{constructor(e){let r=ye(Ee(e)),n=r.apiKey??null,i=r.oobCode??null,o=gc(r.mode??null);I(n&&i&&o,"argument-error"),this.apiKey=n,this.operation=o,this.code=i,this.continueUrl=r.continueUrl??null,this.languageCode=r.lang??null,this.tenantId=r.tenantId??null}static parseLink(e){let r=vc(e);try{return new t(r)}catch{return null}}};var _e=class t{constructor(){this.providerId=t.PROVIDER_ID}static credential(e,r){return Je._fromEmailAndPassword(e,r)}static credentialWithLink(e,r){let n=St.parseLink(r);return I(n,"argument-error"),Je._fromEmailAndCode(e,n.code,n.tenantId)}};_e.PROVIDER_ID="password";_e.EMAIL_PASSWORD_SIGN_IN_METHOD="password";_e.EMAIL_LINK_SIGN_IN_METHOD="emailLink";var Ur=class{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}};var Ce=class extends Ur{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};var Ae=class t extends Ce{constructor(){super("facebook.com")}static credential(e){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Ae.FACEBOOK_SIGN_IN_METHOD="facebook.com";Ae.PROVIDER_ID="facebook.com";var we=class t extends Ce{constructor(){super("google.com"),this.addScope("profile")}static credential(e,r){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:r})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:r,oauthAccessToken:n}=e;if(!r&&!n)return null;try{return t.credential(r,n)}catch{return null}}};we.GOOGLE_SIGN_IN_METHOD="google.com";we.PROVIDER_ID="google.com";var Pe=class t extends Ce{constructor(){super("github.com")}static credential(e){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return t.credential(e.oauthAccessToken)}catch{return null}}};Pe.GITHUB_SIGN_IN_METHOD="github.com";Pe.PROVIDER_ID="github.com";var Re=class t extends Ce{constructor(){super("twitter.com")}static credential(e,r){return le._fromParams({providerId:t.PROVIDER_ID,signInMethod:t.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:r})}static credentialFromResult(e){return t.credentialFromTaggedObject(e)}static credentialFromError(e){return t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:r,oauthTokenSecret:n}=e;if(!r||!n)return null;try{return t.credential(r,n)}catch{return null}}};Re.TWITTER_SIGN_IN_METHOD="twitter.com";Re.PROVIDER_ID="twitter.com";function yc(t,e){return z(t,"POST","/v2/accounts/mfaEnrollment:start",K(t,e))}function Ec(t,e){return z(t,"POST","/v2/accounts/mfaEnrollment:finalize",K(t,e))}var ci="@firebase/auth",ui="1.12.0";var Lr=class{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let r=this.auth.onIdTokenChanged(n=>{e(n?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,r),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let r=this.internalListeners.get(e);r&&(this.internalListeners.delete(e),r(),this.updateProactiveRefresh())}assertAuthConfigured(){I(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};function bc(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function Ic(t){Te(new X("auth",(e,{options:r})=>{let n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:s,authDomain:c}=n.options;I(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});let u={apiKey:s,authDomain:c,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:bi(t)},p=new It(n,i,o,u);return lc(p,r),p},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,r,n)=>{e.getProvider("auth-internal").initialize()})),Te(new X("auth-internal",e=>{let r=Ii(e.getProvider("auth").getImmediate());return(n=>new Lr(n))(r)},"PRIVATE").setInstantiationMode("EXPLICIT")),Ie(ci,ui,bc(t)),Ie(ci,ui,"esm2020")}Ke.initialize(fetch,Headers,Response);Ic("Node");var fh=Fr("operation-not-supported-in-this-environment");It.prototype.setPersistence=async()=>{};function Tc(t,e){return z(t,"POST","/v2/accounts/mfaSignIn:finalize",K(t,e))}var Mr=class{constructor(e){this.factorId=e}_process(e,r,n){switch(r.type){case"enroll":return this._finalizeEnroll(e,r.credential,n);case"signin":return this._finalizeSignIn(e,r.credential);default:return j("unexpected MultiFactorSessionType")}}},_t=class{static assertionForEnrollment(e,r){return Ct._fromSecret(e,r)}static assertionForSignIn(e,r){return Ct._fromEnrollmentId(e,r)}static async generateSecret(e){let r=e;I(typeof r.user?.auth<"u","internal-error");let n=await yc(r.user.auth,{idToken:r.credential,totpEnrollmentInfo:{}});return At._fromStartTotpMfaEnrollmentResponse(n,r.user.auth)}};_t.FACTOR_ID="totp";var Ct=class t extends Mr{constructor(e,r,n){super("totp"),this.otp=e,this.enrollmentId=r,this.secret=n}static _fromSecret(e,r){return new t(r,void 0,e)}static _fromEnrollmentId(e,r){return new t(r,e)}async _finalizeEnroll(e,r,n){return I(typeof this.secret<"u",e,"argument-error"),Ec(e,{idToken:r,displayName:n,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,r){I(this.enrollmentId!==void 0&&this.otp!==void 0,e,"argument-error");let n={verificationCode:this.otp};return Tc(e,{mfaPendingCredential:r,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:n})}},At=class t{constructor(e,r,n,i,o,s,c){this.sessionInfo=s,this.auth=c,this.secretKey=e,this.hashingAlgorithm=r,this.codeLength=n,this.codeIntervalSeconds=i,this.enrollmentCompletionDeadline=o}static _fromStartTotpMfaEnrollmentResponse(e,r){return new t(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,r)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,r){let n=!1;return(pt(e)||pt(r))&&(n=!0),n&&(pt(e)&&(e=this.auth.currentUser?.email||"unknownuser"),pt(r)&&(r=this.auth.name)),`otpauth://totp/${r}:${e}?secret=${this.secretKey}&issuer=${r}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function pt(t){return typeof t>"u"||t?.length===0}import*as y from"valibot";function L(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var te=null;function Qe(){return Ci().platform}function Ci(){if(te)return te;let t=L();if(t?.platform)return te={platform:t.platform,mode:t.mode,context:t.context,version:t.version,metadata:{detectedAt:t.timestamp}},te;let e=[];e.push(..._c()),e.push(...Cc());let r=e.sort((n,i)=>i.confidence-n.confidence)[0];return!r||r.confidence<U.MINIMUM?(te={platform:A.UNKNOWN,mode:_i(),context:Ac(),metadata:{detectedAt:Date.now()}},te):(te={platform:r.platform,mode:_i(),context:r.context,version:wc(r.platform),metadata:{...r.metadata,detectedAt:Date.now()}},te)}var Xe=null,Ze=null;function Ai(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return Ze=!0,!0;if(Ze===!0)return!0;let t=L();if(t?.platform){let r=t.platform===A.NEXTJS;return r&&(Ze=!0),r}let e=Qe()===A.NEXTJS;return e&&(Ze=!0),e}function wi(){if(Xe!==null)return Xe;let t=L();if(t?.platform)return Xe=t.platform===A.VITE,Xe;let e=Qe()===A.VITE;return Xe=e,e}function M(){return typeof window<"u"}function Br(){return typeof process<"u"&&!!process.versions?.node}function _c(){let t=[];if(M()){globalThis.__vite_plugin_react_preamble_installed__&&t.push({platform:A.VITE,confidence:U.HIGH,context:D.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let e=L();e?.platform===A.VITE&&t.push({platform:A.VITE,confidence:U.HIGH,context:D.CLIENT}),e?.i18n?.mapping&&t.push({platform:A.VITE,confidence:U.MEDIUM,context:D.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&t.push({platform:A.VITE,confidence:U.LOW,context:D.CLIENT})}return Br()&&(process.env.VITE&&t.push({platform:A.VITE,confidence:U.MEDIUM,context:D.SERVER}),process.env.npm_lifecycle_event?.includes(A.VITE)&&t.push({platform:A.VITE,confidence:U.LOW,context:D.BUILD})),t}function Cc(){let t=[];return Br()&&(process.env.NEXT_RUNTIME&&t.push({platform:A.NEXTJS,confidence:U.HIGH,context:D.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&t.push({platform:A.NEXTJS,confidence:U.MEDIUM,context:D.SERVER}),process.env._DNDEV_CONFIG_&&t.push({platform:A.NEXTJS,confidence:U.LOW,context:D.SERVER})),M()&&(L()?.platform===A.NEXTJS&&t.push({platform:A.NEXTJS,confidence:U.HIGH,context:D.CLIENT}),globalThis.__NEXT_DATA__&&t.push({platform:A.NEXTJS,confidence:U.LOW,context:D.CLIENT})),t}function _i(){let t;return typeof import.meta<"u"&&import.meta.env?.MODE?t=import.meta.env.MODE:typeof process<"u"&&(t="production"),t===ie.PRODUCTION?ie.PRODUCTION:t===ie.TEST?ie.TEST:ie.DEVELOPMENT}function Ac(){return M()?D.CLIENT:Br()?ie.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?D.BUILD:D.SERVER:D.CLIENT}function wc(t){if(!(typeof process>"u"))return t===A.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:t===A.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function Pi(t){return t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Pc(t){let e,r=L();return r?.env&&typeof r.env=="object"&&(e=r.env[t]),e===void 0&&typeof import.meta<"u"&&import.meta.env&&(e=import.meta.env[t]),Pi(e)}function Rc(t){let e=L(),r;return e?.env&&typeof e.env=="object"&&(r=e.env[t]),r===void 0&&typeof process<"u"&&process.env&&(r=process.env[t]),Pi(r)}function k(t,e){if(t==="NODE_ENV"||t==="VITE_NODE_ENV"||t==="NEXT_PUBLIC_NODE_ENV"||t==="MODE"||t==="DEV"||t==="PROD"){let s=L();if(s?.env?.MODE)return t==="DEV"?s.env.MODE==="development"?"true":"false":t==="PROD"?s.env.MODE==="production"?"true":"false":s.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let c=import.meta.env;if(t==="MODE"&&c.MODE)return c.MODE;if(t==="DEV")return c.DEV?"true":"false";if(t==="PROD")return c.PROD?"true":"false"}if(typeof process<"u"){let c="production";return t==="DEV"?c==="development"?"true":"false":t==="PROD"?c==="production"?"true":"false":c}return t==="DEV"?"true":t==="PROD"?"false":"development"}let r=L()?.platform,n=e||r||(wi()?"vite":Ai()?"nextjs":Qe()),i=["MODE","DEV","PROD","SSR"],o;return n==="vite"?i.includes(t)||t.startsWith("VITE_")?o=t:o=`VITE_${t}`:n==="nextjs"?t.startsWith("NEXT_PUBLIC_")?o=t:o=`NEXT_PUBLIC_${t}`:o=t,n==="vite"?Pc(o):n==="nextjs"?Rc(o):void 0}function Ri(){if(typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production"))return!0;let t=k("APP_ENV"),e=k("NODE_ENV");return(t||e||"development").toLowerCase()!=="production"}var xi=y.object({name:y.string(),color:y.string(),icon:y.string(),button:y.object({backgroundColor:y.string(),textColor:y.string(),borderColor:y.string(),hoverBackgroundColor:y.string(),focusOutlineColor:y.string(),fontWeight:y.optional(y.string(),"500")})}),xc=y.object({...xi.entries,type:y.picklist(["auth","both"]),scopes:y.optional(y.array(y.string())),firebaseProviderId:y.optional(y.string())}),Pt=y.union([y.literal(""),y.pipe(y.string(),y.url())]),kc=y.object({authUrl:Pt,tokenUrl:Pt,profileUrl:Pt,revokeUrl:y.optional(Pt)}),Oc=y.object({authentication:y.optional(y.array(y.string())),"api-access":y.array(y.string())}),Qm=y.object({...xi.entries,type:y.picklist(["oauth","both"]),scopes:Oc,endpoints:kc}),et=null;function Dc(){let t=[];for(let[e,r]of Object.entries(me))y.safeParse(xc,r).success?t.push(e):typeof window<"u"&&Ri();return t}function Rt(){if(et!==null)return et;let t=k("AUTH_PARTNERS");if(!t)return et=[],et;let e=Dc(),r=t.split(",").map(n=>n.trim().toLowerCase()).filter(n=>e.includes(n));return et=r,r}var Nc=12e4,Hr=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(e=null,r={}){this.authInstance=e,this.refreshBuffer=r.refreshBufferMs??Nc,this.maxRefreshAttempts=r.maxRefreshAttempts??3,this.autoRefresh=r.autoRefresh!==!1,this.onTokenExpired=r.onTokenExpired,this.onFatalError=r.onFatalError}initialize(e){this.clearRefreshTimer(),this.refreshAttempts=0;let r=this.calculateTokenStatus(e.expiresAt);this.tokenInfo={...e,status:r},this.autoRefresh&&e.expiresAt&&this.scheduleRefresh(e.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(e){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(e&&typeof e.getIdToken=="function"){let r=await e.getIdToken(!0),n=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:r,expiresAt:n}),r}else if(e&&typeof e.getIdTokenResult=="function"){let r=await e.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),r.token}if(this.authInstance?.currentUser){let r=await this.authInstance.currentUser.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),r.token}throw v(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(r){return this.handleError(r instanceof Error?r:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:e,token:r}=this.tokenInfo;if(e==="valid")return r;if((e==="expiring-soon"||e==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(this.authInstance?.currentUser)return await this.forceRefresh(this.authInstance.currentUser)}catch(n){this.handleError(n instanceof Error?n:new Error("Failed to refresh token"))}return e==="expired"||e==="not-initialized"||e==="error"?null:r}onRefreshNeeded(e){return this.refreshCallback=e,()=>{this.refreshCallback=void 0}}updateTokenInfo(e){let r={token:e.token??this.tokenInfo.token,expiresAt:e.expiresAt??this.tokenInfo.expiresAt,refreshToken:e.refreshToken??this.tokenInfo.refreshToken,idToken:e.idToken??this.tokenInfo.idToken},n=this.calculateTokenStatus(r.expiresAt);this.tokenInfo={...r,status:n},this.autoRefresh&&r.expiresAt&&this.scheduleRefresh(r.expiresAt)}calculateTokenStatus(e){if(!e)return this.tokenInfo.token?"valid":"not-initialized";let r=new Date;if(r>=e)return"expired";let n=new Date(e.getTime()-this.refreshBuffer);return r>=n?"expiring-soon":"valid"}scheduleRefresh(e){this.clearRefreshTimer();let r=new Date,n=e.getTime()-r.getTime()-this.refreshBuffer;if(n<=0){this.authInstance?.currentUser&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{this.authInstance?.currentUser?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},n)}handleRefreshError(e){if(this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let r=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);setTimeout(()=>{this.authInstance?.currentUser?this.forceRefresh(this.authInstance.currentUser).catch(n=>{this.handleRefreshError(n)}):this.refreshCallback&&this.refreshCallback().catch(n=>{this.handleRefreshError(n)})},r)}else this.tokenInfo={...this.tokenInfo,status:"error",error:e instanceof Error?e:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(e instanceof Error?e:new Error("Max token refresh attempts reached"))}handleError(e){this.tokenInfo={...this.tokenInfo,status:"error",error:e}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},vg=Le(Hr,null,{});var xt=class{buildKey(e,r,n,i=!1){let o="dndev";switch(r){case"user":if(!n){if(i)return null;throw v(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:r}})}return`${o}:user:${n}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}};var de=null;async function Uc(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(t){throw v(t,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function Lc(t){try{let e=await window.crypto.subtle.exportKey("raw",t);return btoa(String.fromCharCode(...new Uint8Array(e)))}catch(e){throw v(e,{userMessage:"Failed to export encryption key"})}}async function Mc(t){try{let e=Uint8Array.from(atob(t),r=>r.charCodeAt(0));return await window.crypto.subtle.importKey("raw",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}catch(e){throw v(e,{userMessage:"Failed to import encryption key"})}}async function ki(){if(de)return de;try{let t=localStorage.getItem("dndev:encryptionKey");if(t)return de=await Mc(t),de;de=await Uc();let e=await Lc(de);return localStorage.setItem("dndev:encryptionKey",e),de}catch(t){throw v(t,{userMessage:"Failed to get or create encryption key"})}}async function Oi(t){try{let e=await ki(),r=window.crypto.getRandomValues(new Uint8Array(12)),n=typeof t=="string"?t:JSON.stringify(t),o=new TextEncoder().encode(n),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,o),c=new Uint8Array(r.length+s.byteLength);return c.set(r,0),c.set(new Uint8Array(s),r.length),btoa(String.fromCharCode(...c))}catch(e){throw v(e,{userMessage:"Failed to encrypt data"})}}async function Di(t){try{let e=await ki(),r=Uint8Array.from(atob(t),u=>u.charCodeAt(0)),n=r.slice(0,12),i=r.slice(12),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i),c=new TextDecoder().decode(o);try{return JSON.parse(c)}catch{return c}}catch(e){throw v(e,{userMessage:"Failed to decrypt data"})}}var re=class extends xt{userId=null;constructor(e=null){super(),this.userId=e}setUserId(e){this.userId=e}async get(e,r={}){let{scope:n="user",encryption:i=!1}=r,o=this.buildKey(e,n,this.userId,!0);if(!o)return null;try{if(!M())return null;let s=localStorage.getItem(o);if(!s)return null;let c=JSON.parse(s);if(c.expiresAt&&new Date(c.expiresAt)<new Date)return await this.remove(e),null;let u=c.value;return i&&typeof u=="string"&&(u=await Di(u)),u}catch(s){throw v(s,{userMessage:"Failed to retrieve data from local storage",context:{key:e,options:r}})}}async set(e,r,n={}){let{scope:i="user",encryption:o=!1,expiry:s=0}=n,c=this.buildKey(e,i,this.userId,!0);if(c)try{let u=r;o&&(u=await Oi(r));let p=s>0?new Date(Date.now()+s*1e3).toISOString():null,g=JSON.stringify({value:u,expiresAt:p,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(c,g)}catch(u){let p=u?.name==="QuotaExceededError"||u?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":u?.name==="SecurityError"||u?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw v(u,{userMessage:p,context:{key:e,options:n}})}}async remove(e){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(e,n,this.userId,!0);if(!i)continue;typeof window<"u"&&localStorage.removeItem(i)}catch{}}async clear(e){if(!e){let s=(typeof window<"u"?Object.keys(localStorage):[]).filter(c=>c.startsWith("dndev:"));for(let c of s)typeof window<"u"&&localStorage.removeItem(c);return}let r=e==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${e}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(o=>o.startsWith(r));for(let o of i)typeof window<"u"&&localStorage.removeItem(o)}};var tt=class{localStrategy;userId;apiEndpoint;constructor(e,r="/api/storage"){if(!e)throw v("User ID is required for HybridStorageStrategy");this.userId=e,this.localStrategy=new re(e),this.apiEndpoint=r}async get(e,r={}){try{let n=await this.localStrategy.get(e,r);return n!==null?n:await this.getFromCloud(e,r)}catch(n){try{return await this.localStrategy.get(e,r)}catch(i){throw v(n,{userMessage:"Failed to retrieve data from storage",context:{key:e,options:r,fallbackError:i}})}}}async set(e,r,n={}){try{await this.localStrategy.set(e,r,n),this.setToCloud(e,r,n).catch(i=>{})}catch(i){throw v(i,{userMessage:"Failed to store data",context:{key:e,options:n}})}}async remove(e){try{await this.localStrategy.remove(e),this.removeFromCloud(e).catch(r=>{})}catch(r){throw v(r,{userMessage:"Failed to remove data",context:{key:e}})}}async clear(e){try{await this.localStrategy.clear(e),this.clearFromCloud(e).catch(r=>{})}catch(r){throw v(r,{userMessage:"Failed to clear storage",context:{scope:e}})}}buildKey(e,r,n,i=!1){let o="dndev";switch(r){case"user":if(!n){if(i)return null;throw v(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:e,scope:r}})}return`${o}:user:${n}:${e}`;case"global":return`${o}:global:${e}`;case"session":return`${o}:session:${e}`;default:return`${o}:${e}`}}async getFromCloud(e,r){try{let{scope:n="user"}=r,i=this.buildKey(e,n,this.userId,!0);if(!i)return null;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`);if(!o.ok){if(o.status===404)return null;throw v(new Error(`Cloud storage API error: ${o.status} ${o.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:e,status:o.status}})}let s=await o.json();return s.expiresAt&&new Date(s.expiresAt)<new Date?(this.removeFromCloud(e).catch(console.warn),null):(this.localStrategy.set(e,s.value,r).catch(console.warn),s.value)}catch{return null}}async setToCloud(e,r,n){let{scope:i="user",expiry:o=0}=n,s=this.buildKey(e,i,this.userId,!0);if(!s)return;let c=o>0?new Date(Date.now()+o*1e3).toISOString():null,u={value:r,expiresAt:c,createdAt:new Date().toISOString()},p=await fetch(`${this.apiEndpoint}/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw v(new Error(`Cloud storage API error: ${p.status} ${p.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:e,status:p.status}})}async removeFromCloud(e){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(e,n,this.userId,!0);if(!i)continue;let o=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE"});!o.ok&&o.status}catch{}}async clearFromCloud(e){try{let r=new URLSearchParams;e&&r.append("scope",e),e==="user"&&r.append("userId",this.userId);let n=r.toString(),i=n?`${this.apiEndpoint}/clear?${n}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE"})).ok}catch{}}};var kt=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(e=new re){this.strategy=e}initialize(){if(!this.initialized)try{this.initialized=!0}catch{}}setStrategy(e){this.initialize(),this.strategy=e}updateUser(e,r){this.initialize(),r&&e?this.strategy=new tt(e):this.strategy=new re(e)}updateStrategy(){this.isPro&&this.userId?this.strategy=new tt(this.userId):this.strategy=new re(this.userId)}async get(e,r={}){return this.initialize(),this.strategy.get(e,r)}async set(e,r,n={}){return this.initialize(),this.strategy.set(e,r,n)}async remove(e){return this.initialize(),this.strategy.remove(e)}async clear(e){return this.initialize(),this.strategy.clear(e)}async setSecure(e,r,n={}){return this.initialize(),this.set(e,r,{...n,encryption:!0})}async getSecure(e,r={}){return this.initialize(),this.get(e,{...r,encryption:!0})}},Fc=Le(kt);var H={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage"};function pe(t){return!!t&&t.trim()!==""}var Jg={[H.AUTH]:()=>Rt().length>0,[H.OAUTH]:()=>["VITE_OAUTH_GOOGLE_CLIENT_ID","VITE_OAUTH_GITHUB_CLIENT_ID","VITE_OAUTH_FACEBOOK_CLIENT_ID","VITE_OAUTH_TWITTER_CLIENT_ID","VITE_OAUTH_LINKEDIN_CLIENT_ID","VITE_OAUTH_DISCORD_CLIENT_ID","VITE_OAUTH_SLACK_CLIENT_ID","VITE_OAUTH_MICROSOFT_CLIENT_ID","VITE_OAUTH_APPLE_CLIENT_ID"].some(e=>pe(k(e))),[H.I18N]:()=>!0,[H.BILLING]:()=>!!(pe(k("STRIPE_PUBLISHABLE_KEY"))||pe(k("BILLING_ENABLED"))&&k("BILLING_ENABLED")==="true"),[H.ROUTES]:()=>!0,[H.THEMES]:()=>!0,[H.COMPONENTS]:()=>!0,[H.CRUD]:()=>!0,[H.FORMS]:()=>!0,[H.REALTIME]:()=>!!(pe(k("REALTIME_ENABLED"))&&k("REALTIME_ENABLED")==="true"||pe(k("FIREBASE_CONFIG"))),[H.STORAGE]:()=>!!(pe(k("STORAGE_ENABLED"))&&k("STORAGE_ENABLED")==="true"||pe(k("FIREBASE_CONFIG")))};var tu=Qr(Yr(),1);var ru=Qr(Yr(),1);var Jr=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(e,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:r,once:!1,context:n};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,r)}}once(e,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(e),o={handler:r,once:!0,context:n};return i.push(o),this.checkListenerCount(e),()=>{this.off(e,r)}}off(e,r){let n=this.events.get(e);if(!n||n.length===0)return!1;let i=n.findIndex(o=>o.handler===r);return i===-1?!1:(n.splice(i,1),n.length===0&&this.events.delete(e),!0)}emit(e,...r){this.cacheEvent(e,r);let n=this.events.get(e);if(!n||n.length===0)return!1;let i=[...n],o=[];for(let s of i)try{s.context?s.handler.apply(s.context,r):s.handler(...r),s.once&&o.push(s)}catch(c){v(c,{userMessage:`Error in event handler for ${e}`,context:{eventName:e,args:r},severity:"warning"})}if(o.length>0){let s=this.events.get(e);if(s){let c=s.filter(u=>!o.includes(u));c.length===0?this.events.delete(e):this.events.set(e,c)}}return!0}hasListeners(e){let r=this.events.get(e);return!!r&&r.length>0}listenerCount(e){return this.events.get(e)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(e){let r=this.events.get(e);return r?r.map(n=>n.handler):[]}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}setMaxListeners(e){return this.maxListeners=e>0?e:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(e){let r=this.events.get(e);return r||(r=[],this.events.set(e,r)),r}checkListenerCount(e){let r=this.listenerCount(e);this.maxListeners!==1/0&&r>this.maxListeners}cacheEvent(e,r){let n=this.eventCache.get(e);n||(n=[],this.eventCache.set(e,n)),n.push({data:r,timestamp:Date.now()}),this.cleanupCache(e)}getCachedEvents(e){let r=this.eventCache.get(e);return!r||r.length===0?[]:(this.cleanupCache(e),(this.eventCache.get(e)||[]).map(i=>i.data))}clearCachedEvents(e){this.eventCache.delete(e)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let e=0,r=null,n=null;for(let[o,s]of this.eventCache.entries()){e+=s.length;for(let c of s)(r===null||c.timestamp<r)&&(r=c.timestamp),(n===null||c.timestamp>n)&&(n=c.timestamp)}let i=`${Math.round(e*200/1024)}KB`;return{totalEvents:e,eventTypes:this.eventCache.size,oldestEvent:r,newestEvent:n,memoryEstimate:i}}cleanupCache(e){let r=Date.now()-this.cacheTTL;if(e){let n=this.eventCache.get(e);if(n){let i=n.filter(o=>o.timestamp>r);i.length===0?this.eventCache.delete(e):this.eventCache.set(e,i)}}else for(let[n,i]of this.eventCache.entries()){let o=i.filter(s=>s.timestamp>r);o.length===0?this.eventCache.delete(n):this.eventCache.set(n,o)}}},Nv=new Jr;var Bv={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},error:null,emailVerification:{status:"pending"},getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:Ne.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:V.GUEST,userTier:De.FREE,can:{navigate:t=>t===!1||typeof t=="object"&&!t.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Hv={status:Ne.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1},$v={status:Ne.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},Wv={status:Ne.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var ji=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function Ki(t){return typeof t=="string"&&t.length>=19&&t.includes("-")&&t.includes(":")}function Dt(t,e=""){if(Array.isArray(t))t.forEach((r,n)=>{let i=`${e}[${n}]`;if(typeof r=="string"&&Ki(r)){if(!ji.test(r))throw v({userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&Dt(r,i)});else if(typeof t=="object"&&t!==null)for(let[r,n]of Object.entries(t)){let i=e?`${e}.${r}`:r;if(typeof n=="string"&&Ki(n)){if(!ji.test(n))throw v({userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&Dt(n,i)}}import*as Yi from"valibot";var Xr={};function Sy(t){Xr.uniqueConstraintValidator=t}async function zi(t,e,r){let{uniqueFields:n=[],collection:i}=t.metadata;n.length!==0&&Xr.uniqueConstraintValidator&&await Promise.all(n.map(async({field:o,errorMessage:s})=>{let c=e[o];if(c==null)return;if(await Xr.uniqueConstraintValidator.checkDuplicate(i,o,c,r))throw v({userMessage:s||`${o} must be unique`,code:"already-exists",context:{field:o}})}))}async function wy(t,e,r,n){Yi.parse(t,e),Dt(e),await zi(t,e,n),t.metadata.customValidate&&await t.metadata.customValidate(e,r)}function nu(t){return t!=null&&typeof t=="object"&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null}function Ly(t){if(!nu(t)){let e=t,r=e&&typeof e=="object"&&"constructor"in e&&e.constructor&&e.constructor.name||"unknown";throw v(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return t.metadata.collection}function iu(t){let e=t.collection||(t.field.endsWith("Id")?t.field.slice(0,-2)+"ies":t.field+"s");return{name:t.field,label:`crud:fields.${t.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:e}}}function ou(t,e){if(!e||e.length===0)return t.map(i=>({value:i.value,label:i.label}));let r=t.map(i=>({value:i.value,label:i.label})),n=new Set(t.map(i=>i.value));for(let i of e)n.has(i.value)||r.push(i);return r}function su(t,e){if(!(!t.uniqueKeys||t.uniqueKeys.length===0))for(let r=0;r<t.uniqueKeys.length;r++){let n=t.uniqueKeys[r];if(!n)continue;if(!n.fields||n.fields.length===0)throw v(new Error(`uniqueKeys[${r}] for entity '${t.name}' must have at least one field`),{userMessage:`uniqueKeys[${r}] for entity '${t.name}' must have at least one field`,context:{entityName:t.name,uniqueKeyIndex:r},severity:"error"});let i=n.fields.filter(o=>!e.has(o));if(i.length>0)throw v(new Error(`uniqueKeys[${r}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${r}] for entity '${t.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:t.name,uniqueKeyIndex:r,invalidFields:i},severity:"error"})}}function au(t){let{form:e,fields:r}=t,n=Object.keys(r);if(e){if(e.type==="multi-step"||e.type==="wizard"){if(!e.steps||e.steps.length===0)throw v(new Error(`Multi-step form for entity '${t.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${t.name}' must have at least one step`,context:{entityName:t.name,operation:"validateFormConfig"},severity:"error"});let i=e.steps.flatMap(u=>u.fields),o=i.filter(u=>!n.includes(u));if(o.length>0)throw v(new Error(`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`Multi-step form for entity '${t.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:t.name,invalidFields:o,operation:"validateFormConfig"},severity:"error"});let s=new Set(i);n.filter(u=>!s.has(u)).length>0}e.rules&&e.rules.forEach((i,o)=>{let c=(Array.isArray(i.condition)?i.condition.map(g=>g.field):[i.condition.field]).filter(g=>!n.includes(g));if(c.length>0)throw v(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let p=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(g=>!n.includes(g));if(p.length>0)throw v(new Error(`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`),{userMessage:`Dynamic form rule ${o} for entity '${t.name}' references non-existent affected fields: ${p.join(", ")}`,context:{entityName:t.name,ruleIndex:o,invalidFields:p,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([i,o])=>{if(o.dependsOn&&!n.includes(o.dependsOn.field))throw v(new Error(`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${t.name}' depends on non-existent field: ${o.dependsOn.field}`,context:{entityName:t.name,fieldName:i,dependsOnField:o.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function cu(t){return t.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...t.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Hy(t){try{au(t);let e=cu(t),r={...t.fields,...w,...t.fields.createdAt&&{createdAt:{...w.createdAt,...t.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...w.updatedAt,...t.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...w.createdById,...t.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...w.updatedById,...t.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...t.fields.status&&{status:{...w.status,...t.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:t.fields.status.validation?.nullable,options:ou(nr,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:iu(t.scope)}};if(t.listFields){let o=new Set(Object.keys(r)),s=t.listFields.filter(c=>!o.has(c));if(s.length>0)throw v(new Error(`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let o=new Set(Object.keys(r)),s=t.listCardFields.filter(c=>!o.has(c));if(s.length>0)throw v(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${s.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${s.join(", ")}`,context:{entityName:t.name,invalidFields:s,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let o=new Set(Object.keys(r));su(t,o)}let n={...$t,...t.access||{}},i=t.namespace||`entity-${t.name.toLowerCase()}`;return{...t,form:e,fields:r,access:n,namespace:i}}catch(e){throw v(e,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}function Wy(t,e,r=1,n=!1){let i=[];if(n)for(let o=e;o>=t;o-=r)i.push({value:String(o),label:String(o)});else for(let o=t;o<=e;o+=r)i.push({value:String(o),label:String(o)});return i}var fe=new Map;function Gy(t,e){fe.has(t),fe.set(t,e)}function jy(t){fe.delete(t)}function Ky(t){let e=fe.get(t);return e?e():null}function zy(t){return fe.has(t)}function Yy(){return Array.from(fe.keys())}function Jy(){fe.clear()}export{Al as AUTH_EVENTS,me as AUTH_PARTNERS,zu as AUTH_PARTNER_STATE,ln as AuthUserSchema,ve as BACKEND_GENERATED_FIELD_NAMES,Pl as BILLING_EVENTS,Ao as BREAKPOINT_RANGES,qt as BREAKPOINT_THRESHOLDS,rn as COMMON_TIER_CONFIGS,U as CONFIDENCE_LEVELS,mn as CONSENT_CATEGORY,D as CONTEXTS,Ut as CURRENCY_MAP,un as CheckoutSessionMetadataSchema,nn as CreateCheckoutSessionRequestSchema,on as CreateCheckoutSessionResponseSchema,dn as CustomClaimsSchema,$t as DEFAULT_ENTITY_ACCESS,oe as DEFAULT_ERROR_MESSAGES,Jl as DEFAULT_LAYOUT_PRESET,nr as DEFAULT_STATUS_OPTIONS,yf as DEFAULT_STATUS_VALUE,Su as DEFAULT_SUBSCRIPTION,Rd as DENSITY,x as DoNotDevError,ie as ENVIRONMENTS,pn as EntityHookError,Vt as FEATURES,xd as FEATURE_CONSENT_MATRIX,Ne as FEATURE_STATUS,Wt as FIREBASE_ERROR_MAP,it as FIRESTORE_ID_PATTERN,fn as GITHUB_PERMISSION_LEVELS,Ef as HIDDEN_STATUSES,Xl as LAYOUT_PRESET,xl as OAUTH_EVENTS,jt as OAUTH_PARTNERS,Ed as PARTNER_ICONS,Ol as PAYLOAD_EVENTS,Bt as PERMISSIONS,A as PLATFORMS,il as PWA_ASSET_TYPES,nl as PWA_DISPLAY_MODES,So as ProductDeclarationSchema,Ou as ProductDeclarationsSchema,ol as ROUTE_SOURCES,rl as STORAGE_SCOPES,tl as STORAGE_TYPES,Nl as STRIPE_EVENTS,nt as STRIPE_MODES,Iu as SUBSCRIPTION_DURATIONS,he as SUBSCRIPTION_STATUS,De as SUBSCRIPTION_TIERS,Sn as ServerUtils,Zt as SingletonManager,Co as StripeBackConfigSchema,_o as StripeFrontConfigSchema,Io as StripePaymentSchema,To as StripeSubscriptionSchema,an as SubscriptionClaimsSchema,sn as SubscriptionDataSchema,ws as TECHNICAL_FIELD_NAMES,V as USER_ROLES,Ht as UserSubscriptionSchema,cn as WebhookEventSchema,Me as addMonths,er as addYears,vs as addressSchema,Es as arraySchema,w as baseFields,_n as booleanSchema,os as calculateSubscriptionEndDate,Jt as captureErrorToSentry,ud as checkGitHubAccessSchema,mf as clearSchemaGenerators,Jy as clearScopeProviders,Ue as commonErrorCodeMappings,Lt as compactToISOString,Qo as createAsyncSingleton,Tu as createDefaultSubscriptionClaims,Yu as createDefaultUserProfile,pl as createEntitySchema,$ as createErrorHandler,ao as createMetadata,es as createMethodProxy,Ps as createSchemas,Le as createSingleton,Zo as createSingletonWithParams,ge as dateSchema,Hy as defineEntity,ml as deleteEntitySchema,Kt as detectErrorSource,pd as disconnectOAuthSchema,ds as emailSchema,xf as enhanceSchema,ld as exchangeTokenSchema,Cn as fileSchema,An as filesSchema,is as filterVisibleFields,uo as formatCurrency,tn as formatDate,vo as formatRelativeTime,_s as gdprConsentSchema,En as generateCodeChallenge,yn as generateCodeVerifier,Go as generatePKCEPair,gs as geopointSchema,wo as getBreakpointFromWidth,zl as getBreakpointUtils,Ly as getCollectionName,fd as getConnectionsSchema,en as getCurrencyLocale,co as getCurrencySymbol,fo as getCurrentTimestamp,fl as getEntitySchema,hf as getRegisteredSchemaTypes,Yy as getRegisteredScopeProviders,Be as getSchemaType,Ky as getScopeValue,Qt as getVisibleFields,go as getWeekFromISOString,Po as githubPermissionSchema,Gt as githubRepoConfigSchema,ad as grantGitHubAccessSchema,v as handleError,ff as hasCustomSchemaGenerator,nu as hasMetadata,st as hasRoleAccess,zy as hasScopeProvider,Xo as hasTierAccess,Lo as isAuthPartnerId,If as isBackendGeneratedField,Kl as isBreakpoint,Mt as isCompactDateString,Tn as isFieldVisible,bf as isFrameworkField,Mo as isOAuthPartnerId,jo as isPKCESupported,lo as isoToCompactString,Jo as lazyImport,gl as listEntitiesSchema,ys as mapSchema,Yt as mapToDoNotDevError,qo as maybeTranslate,bs as multiselectSchema,wn as neverSchema,po as normalizeToISOString,Fe as numberSchema,gu as overrideFeatures,bu as overridePaymentModes,vu as overridePermissions,Eu as overrideSubscriptionStatus,mu as overrideSubscriptionTiers,hu as overrideUserRoles,Ft as parseDate,Eo as parseDateToNoonUTC,ss as parseISODate,ls as parseServerCookie,ps as passwordSchema,hs as pictureSchema,ms as picturesSchema,Cs as priceSchema,Wy as rangeOptions,Is as referenceSchema,dd as refreshTokenSchema,E as registerSchemaGenerator,Gy as registerScopeProvider,Sy as registerUniqueConstraintValidator,cd as revokeGitHubAccessSchema,tr as selectSchema,Wo as showNotification,rr as stringSchema,Ss as switchSchema,Ts as telSchema,at as textSchema,mo as timestampToISOString,bo as toDateOnly,ho as toISOString,no as translateArray,oo as translateArrayRange,so as translateArrayWithIndices,io as translateObjectArray,jy as unregisterScopeProvider,hl as updateEntitySchema,ts as updateMetadata,fs as urlSchema,Id as validateAuthPartners,ju as validateAuthSchemas,Wu as validateAuthUser,Uu as validateBillingSchemas,ku as validateCheckoutSessionMetadata,zo as validateCodeChallenge,Ko as validateCodeVerifier,Au as validateCreateCheckoutSessionRequest,wu as validateCreateCheckoutSessionResponse,Gu as validateCustomClaims,Dt as validateDates,wy as validateDocument,us as validateEnvVar,cs as validateMetadata,Td as validateOAuthPartners,Nu as validateStripeBackConfig,Du as validateStripeFrontConfig,Ru as validateSubscriptionClaims,Pu as validateSubscriptionData,zi as validateUniqueFields,as as validateUrl,qu as validateUserSubscription,xu as validateWebhookEvent,$o as withErrorHandling,Yo as withGracefulDegradation};
2
+ /*! Bundled license information:
3
+
4
+ react/cjs/react.production.js:
5
+ (**
6
+ * @license React
7
+ * react.production.js
8
+ *
9
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
10
+ *
11
+ * This source code is licensed under the MIT license found in the
12
+ * LICENSE file in the root directory of this source tree.
13
+ *)
14
+
15
+ @firebase/util/dist/postinstall.mjs:
16
+ @firebase/util/dist/node-esm/index.node.esm.js:
17
+ (**
18
+ * @license
19
+ * Copyright 2025 Google LLC
20
+ *
21
+ * Licensed under the Apache License, Version 2.0 (the "License");
22
+ * you may not use this file except in compliance with the License.
23
+ * You may obtain a copy of the License at
24
+ *
25
+ * http://www.apache.org/licenses/LICENSE-2.0
26
+ *
27
+ * Unless required by applicable law or agreed to in writing, software
28
+ * distributed under the License is distributed on an "AS IS" BASIS,
29
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30
+ * See the License for the specific language governing permissions and
31
+ * limitations under the License.
32
+ *)
33
+
34
+ @firebase/util/dist/node-esm/index.node.esm.js:
35
+ @firebase/util/dist/node-esm/index.node.esm.js:
36
+ @firebase/util/dist/node-esm/index.node.esm.js:
37
+ @firebase/util/dist/node-esm/index.node.esm.js:
38
+ @firebase/util/dist/node-esm/index.node.esm.js:
39
+ @firebase/util/dist/node-esm/index.node.esm.js:
40
+ @firebase/util/dist/node-esm/index.node.esm.js:
41
+ @firebase/util/dist/node-esm/index.node.esm.js:
42
+ @firebase/util/dist/node-esm/index.node.esm.js:
43
+ @firebase/util/dist/node-esm/index.node.esm.js:
44
+ @firebase/logger/dist/esm/index.esm.js:
45
+ (**
46
+ * @license
47
+ * Copyright 2017 Google LLC
48
+ *
49
+ * Licensed under the Apache License, Version 2.0 (the "License");
50
+ * you may not use this file except in compliance with the License.
51
+ * You may obtain a copy of the License at
52
+ *
53
+ * http://www.apache.org/licenses/LICENSE-2.0
54
+ *
55
+ * Unless required by applicable law or agreed to in writing, software
56
+ * distributed under the License is distributed on an "AS IS" BASIS,
57
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
58
+ * See the License for the specific language governing permissions and
59
+ * limitations under the License.
60
+ *)
61
+
62
+ @firebase/util/dist/node-esm/index.node.esm.js:
63
+ @firebase/util/dist/node-esm/index.node.esm.js:
64
+ @firebase/util/dist/node-esm/index.node.esm.js:
65
+ (**
66
+ * @license
67
+ * Copyright 2022 Google LLC
68
+ *
69
+ * Licensed under the Apache License, Version 2.0 (the "License");
70
+ * you may not use this file except in compliance with the License.
71
+ * You may obtain a copy of the License at
72
+ *
73
+ * http://www.apache.org/licenses/LICENSE-2.0
74
+ *
75
+ * Unless required by applicable law or agreed to in writing, software
76
+ * distributed under the License is distributed on an "AS IS" BASIS,
77
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
78
+ * See the License for the specific language governing permissions and
79
+ * limitations under the License.
80
+ *)
81
+
82
+ @firebase/util/dist/node-esm/index.node.esm.js:
83
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
84
+ (**
85
+ * @license
86
+ * Copyright 2021 Google LLC
87
+ *
88
+ * Licensed under the Apache License, Version 2.0 (the "License");
89
+ * you may not use this file except in compliance with the License.
90
+ * You may obtain a copy of the License at
91
+ *
92
+ * http://www.apache.org/licenses/LICENSE-2.0
93
+ *
94
+ * Unless required by applicable law or agreed to in writing, software
95
+ * distributed under the License is distributed on an "AS IS" BASIS,
96
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
97
+ * See the License for the specific language governing permissions and
98
+ * limitations under the License.
99
+ *)
100
+
101
+ @firebase/util/dist/node-esm/index.node.esm.js:
102
+ @firebase/component/dist/esm/index.esm.js:
103
+ @firebase/component/dist/esm/index.esm.js:
104
+ @firebase/component/dist/esm/index.esm.js:
105
+ @firebase/app/dist/esm/index.esm.js:
106
+ @firebase/app/dist/esm/index.esm.js:
107
+ @firebase/app/dist/esm/index.esm.js:
108
+ @firebase/app/dist/esm/index.esm.js:
109
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
110
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
111
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
112
+ (**
113
+ * @license
114
+ * Copyright 2019 Google LLC
115
+ *
116
+ * Licensed under the Apache License, Version 2.0 (the "License");
117
+ * you may not use this file except in compliance with the License.
118
+ * You may obtain a copy of the License at
119
+ *
120
+ * http://www.apache.org/licenses/LICENSE-2.0
121
+ *
122
+ * Unless required by applicable law or agreed to in writing, software
123
+ * distributed under the License is distributed on an "AS IS" BASIS,
124
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
125
+ * See the License for the specific language governing permissions and
126
+ * limitations under the License.
127
+ *)
128
+
129
+ @firebase/util/dist/node-esm/index.node.esm.js:
130
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
131
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
132
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
133
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
134
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
135
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
136
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
137
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
138
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
139
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
140
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
141
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
142
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
143
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
144
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
145
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
146
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
147
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
148
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
149
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
150
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
151
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
152
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
153
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
154
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
155
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
156
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
157
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
158
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
159
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
160
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
161
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
162
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
163
+ (**
164
+ * @license
165
+ * Copyright 2020 Google LLC
166
+ *
167
+ * Licensed under the Apache License, Version 2.0 (the "License");
168
+ * you may not use this file except in compliance with the License.
169
+ * You may obtain a copy of the License at
170
+ *
171
+ * http://www.apache.org/licenses/LICENSE-2.0
172
+ *
173
+ * Unless required by applicable law or agreed to in writing, software
174
+ * distributed under the License is distributed on an "AS IS" BASIS,
175
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
176
+ * See the License for the specific language governing permissions and
177
+ * limitations under the License.
178
+ *)
179
+
180
+ @firebase/util/dist/node-esm/index.node.esm.js:
181
+ (**
182
+ * @license
183
+ * Copyright 2021 Google LLC
184
+ *
185
+ * Licensed under the Apache License, Version 2.0 (the "License");
186
+ * you may not use this file except in compliance with the License.
187
+ * You may obtain a copy of the License at
188
+ *
189
+ * http://www.apache.org/licenses/LICENSE-2.0
190
+ *
191
+ * Unless required by applicable law or agreed to in writing, software
192
+ * distributed under the License is distributed on an "AS IS" BASIS,
193
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
194
+ * See the License for the specific language governing permissions and
195
+ * limitations under the License.
196
+ *)
197
+ (**
198
+ * @license
199
+ * Copyright 2017 Google LLC
200
+ *
201
+ * Licensed under the Apache License, Version 2.0 (the "License");
202
+ * you may not use this file except in compliance with the License.
203
+ * You may obtain a copy of the License at
204
+ *
205
+ * http://www.apache.org/licenses/LICENSE-2.0
206
+ *
207
+ * Unless required by applicable law or agreed to in writing, software
208
+ * distributed under the License is distributed on an "AS IS" BASIS,
209
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
+ * See the License for the specific language governing permissions and
211
+ * limitations under the License.
212
+ *)
213
+
214
+ @firebase/app/dist/esm/index.esm.js:
215
+ (**
216
+ * @license
217
+ * Copyright 2023 Google LLC
218
+ *
219
+ * Licensed under the Apache License, Version 2.0 (the "License");
220
+ * you may not use this file except in compliance with the License.
221
+ * You may obtain a copy of the License at
222
+ *
223
+ * http://www.apache.org/licenses/LICENSE-2.0
224
+ *
225
+ * Unless required by applicable law or agreed to in writing, software
226
+ * distributed under the License is distributed on an "AS IS" BASIS,
227
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
228
+ * See the License for the specific language governing permissions and
229
+ * limitations under the License.
230
+ *)
231
+
232
+ @firebase/app/dist/esm/index.esm.js:
233
+ (**
234
+ * @license
235
+ * Copyright 2021 Google LLC
236
+ *
237
+ * Licensed under the Apache License, Version 2.0 (the "License");
238
+ * you may not use this file except in compliance with the License.
239
+ * You may obtain a copy of the License at
240
+ *
241
+ * http://www.apache.org/licenses/LICENSE-2.0
242
+ *
243
+ * Unless required by applicable law or agreed to in writing, software
244
+ * distributed under the License is distributed on an "AS IS" BASIS,
245
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
246
+ * See the License for the specific language governing permissions and
247
+ * limitations under the License.
248
+ *)
249
+ (**
250
+ * @license
251
+ * Copyright 2019 Google LLC
252
+ *
253
+ * Licensed under the Apache License, Version 2.0 (the "License");
254
+ * you may not use this file except in compliance with the License.
255
+ * You may obtain a copy of the License at
256
+ *
257
+ * http://www.apache.org/licenses/LICENSE-2.0
258
+ *
259
+ * Unless required by applicable law or agreed to in writing, software
260
+ * distributed under the License is distributed on an "AS IS" BASIS,
261
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
262
+ * See the License for the specific language governing permissions and
263
+ * limitations under the License.
264
+ *)
265
+
266
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
267
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
268
+ (**
269
+ * @license
270
+ * Copyright 2020 Google LLC
271
+ *
272
+ * Licensed under the Apache License, Version 2.0 (the "License");
273
+ * you may not use this file except in compliance with the License.
274
+ * You may obtain a copy of the License at
275
+ *
276
+ * http://www.apache.org/licenses/LICENSE-2.0
277
+ *
278
+ * Unless required by applicable law or agreed to in writing, software
279
+ * distributed under the License is distributed on an "AS IS" BASIS,
280
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
281
+ * See the License for the specific language governing permissions and
282
+ * limitations under the License.
283
+ *)
284
+ (**
285
+ * @license
286
+ * Copyright 2019 Google LLC
287
+ *
288
+ * Licensed under the Apache License, Version 2.0 (the "License");
289
+ * you may not use this file except in compliance with the License.
290
+ * You may obtain a copy of the License at
291
+ *
292
+ * http://www.apache.org/licenses/LICENSE-2.0
293
+ *
294
+ * Unless required by applicable law or agreed to in writing, software
295
+ * distributed under the License is distributed on an "AS IS" BASIS,
296
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
297
+ * See the License for the specific language governing permissions and
298
+ * limitations under the License.
299
+ *)
300
+
301
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
302
+ (**
303
+ * @license
304
+ * Copyright 2020 Google LLC
305
+ *
306
+ * Licensed under the Apache License, Version 2.0 (the "License");
307
+ * you may not use this file except in compliance with the License.
308
+ * You may obtain a copy of the License at
309
+ *
310
+ * http://www.apache.org/licenses/LICENSE-2.0
311
+ *
312
+ * Unless required by applicable law or agreed to in writing, software
313
+ * distributed under the License is distributed on an "AS IS" BASIS,
314
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
315
+ * See the License for the specific language governing permissions and
316
+ * limitations under the License.
317
+ *)
318
+ (**
319
+ * @license
320
+ * Copyright 2022 Google LLC
321
+ *
322
+ * Licensed under the Apache License, Version 2.0 (the "License");
323
+ * you may not use this file except in compliance with the License.
324
+ * You may obtain a copy of the License at
325
+ *
326
+ * http://www.apache.org/licenses/LICENSE-2.0
327
+ *
328
+ * Unless required by applicable law or agreed to in writing, software
329
+ * distributed under the License is distributed on an "AS IS" BASIS,
330
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
331
+ * See the License for the specific language governing permissions and
332
+ * limitations under the License.
333
+ *)
334
+ (**
335
+ * @license
336
+ * Copyright 2023 Google LLC
337
+ *
338
+ * Licensed under the Apache License, Version 2.0 (the "License");
339
+ * you may not use this file except in compliance with the License.
340
+ * You may obtain a copy of the License at
341
+ *
342
+ * http://www.apache.org/licenses/LICENSE-2.0
343
+ *
344
+ * Unless required by applicable law or agreed to in writing, software
345
+ * distributed under the License is distributed on an "AS IS" BASIS,
346
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
347
+ * See the License for the specific language governing permissions and
348
+ * limitations under the License.
349
+ *)
350
+
351
+ @firebase/auth/dist/node-esm/totp-05d844a5.js:
352
+ (**
353
+ * @license
354
+ * Copyright 2020 Google LLC
355
+ *
356
+ * Licensed under the Apache License, Version 2.0 (the "License");
357
+ * you may not use this file except in compliance with the License.
358
+ * You may obtain a copy of the License at
359
+ *
360
+ * http://www.apache.org/licenses/LICENSE-2.0
361
+ *
362
+ * Unless required by applicable law or agreed to in writing, software
363
+ * distributed under the License is distributed on an "AS IS" BASIS,
364
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
365
+ * See the License for the specific language governing permissions and
366
+ * limitations under the License.
367
+ *)
368
+ (**
369
+ * @license
370
+ * Copyright 2021 Google LLC
371
+ *
372
+ * Licensed under the Apache License, Version 2.0 (the "License");
373
+ * you may not use this file except in compliance with the License.
374
+ * You may obtain a copy of the License at
375
+ *
376
+ * http://www.apache.org/licenses/LICENSE-2.0
377
+ *
378
+ * Unless required by applicable law or agreed to in writing, software
379
+ * distributed under the License is distributed on an "AS IS" BASIS,
380
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
381
+ * See the License for the specific language governing permissions and
382
+ * limitations under the License.
383
+ *)
384
+ */