@donotdev/core 0.0.14 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.js +8 -8
- package/package.json +2 -2
- package/server.d.ts +462 -4
- package/server.js +1 -1
- package/vite/index.js +17 -17
package/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 Xr}from"node:path";import l from"node:process";import{fileURLToPath as Et}from"node:url";var xt,d,m,o=vt(()=>{"use strict";xt=bt(import.meta.url),d=Et(import.meta.url),m=St(d);typeof globalThis<"u"&&(globalThis.require=xt,globalThis.__filename=d,globalThis.__dirname=m,globalThis.Buffer=p,globalThis.process=l,typeof global>"u"&&(globalThis.global=globalThis))});o();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:()=>oe,hasTierAccess:()=>pr,isCompactDateString:()=>le,isFieldVisible:()=>Je,isPKCESupported:()=>sr,isoToCompactString:()=>Rt,lazyImport:()=>dr,mapToDoNotDevError:()=>Ee,maybeTranslate:()=>ir,normalizeToISOString:()=>Pt,parseDate:()=>ue,parseDateToNoonUTC:()=>Ut,parseISODate:()=>xr,parseServerCookie:()=>Ar,showNotification:()=>or,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});o();o();o();function Tt(e,t,r,i={}){let{minLength:s=0,excludeEmpty:u=!0,customFilter:C}=i;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return e(R)}).filter((A,P)=>{let R=`${t}.${P}`;return!(A===R||u&&A.trim()===""||A.length<s||C&&!C(A,P))})}function Ct(e,t,r,i){return Array.from({length:r},(s,u)=>{let C=`${t}.${u}.${String(i[0])}`;if(e(C)===C)return null;let P={};for(let R of i){let I=`${t}.${u}.${String(R)}`;P[R]=e(I)}return P}).filter(s=>s!==null)}function It(e,t,r,i,s={}){let{minLength:u=0,excludeEmpty:C=!0,customFilter:A}=s;return Array.from({length:i-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<u||A&&!A(P,I))})}function At(e,t,r,i={}){let{minLength:s=0,excludeEmpty:u=!0,customFilter:C}=i;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||u&&A.trim()===""||A.length<s||C&&!C(A,P))})}o();function kt(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}o();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],i=t[2],s=t[3],u=t[4],C=t[5],A=new Date(parseInt(r,10),parseInt(i,10)-1,parseInt(s,10),parseInt(u,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(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),u=String(t.getUTCHours()).padStart(2,"0"),C=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${i}${s}:${u}${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),i=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((i+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:i="long",numeric:s="auto",fallbackThreshold:u=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>u)return we(C.toISOString(),t);let U=new Intl.RelativeTimeFormat(t,{style:i,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 i;if(e instanceof Date)i=e;else if(typeof e=="string")i=new Date(e);else if(typeof e=="number")i=new Date(e);else if(typeof e=="object"&&"toDate"in e)i=e.toDate();else return"";if(isNaN(i.getTime()))return"";let s=typeof r=="string"?Ft(r):r;return new Intl.DateTimeFormat(t,s).format(i)}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,i=new Date(r);return isNaN(i.getTime())?void 0:i.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]||""}o();o();o();o();o();var q={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function sn(e){Object.assign(q,e)}var de={FREE:"free",PRO:"pro",PREMIUM:"premium"};function cn(e){Object.assign(de,e)}var pe={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function ln(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 un(e){Object.assign(me,e)}o();import*as a from"valibot";o();o();var G={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function mn(e){Object.assign(G,e)}var te={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function gn(e){Object.assign(te,e)}var fn={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function hn(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}},vn={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};o();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 En(e){return n.safeParse(De,e)}function xn(e){return n.safeParse(Ne,e)}function Tn(e){return n.safeParse(Fe,e)}function Cn(e){return n.safeParse(Ue,e)}function In(e){return n.safeParse(Me,e)}function An(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]),kn=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 Rn(e){return n.parse(Vt,e)}function Pn(e){return n.parse(jt,e)}function _n(){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}}o();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 Vn(e){return a.safeParse(Be,e)}function jn(e){return a.safeParse(ge,e)}function Hn(e){return a.safeParse(qe,e)}function $n(){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}}o();var zn={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Yn(e){return{userId:e,role:"user",preferences:{},metadata:{}}}o();var ro={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},no={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},oo={CLIENT:"client",SERVER:"server",BUILD:"build"},io={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},ao={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},so={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},co={USER:"user",GLOBAL:"global",SESSION:"session"},lo={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},uo={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},po={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};o();o();o();import*as x from"valibot";o();var fe={create:"admin",read:"guest",update:"admin",delete:"admin"};var re=/^[0-9a-zA-Z]+$/,xo=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())}),To=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"))}),Co=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)}),Io=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"))}),Ao=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()})))});o();o();o();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,i){super(r),this.name="EntityHookError",this.type=t,this.originalError=i}},D=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r="internal",i){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=i?.details,this.source=i?.source,this.originalError=i?.originalError,this.context=i?.context,this.displayable=i?.displayable??!0,this.userMessageProvided=i?.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}}};o();o();var qo={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"};o();var Ho={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"};o();var Wo={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"};o();var Ko={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"};o();var Qo={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"};o();o();o();o();import"valibot";o();o();o();o();o();o();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 Ei(e,t){let r=Ht[t];return e>=r.min&&e<=r.max}function xi(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"}}o();var Ii="landing";o();o();o();o();o();var je=["pull","push","admin","maintain","triage"];o();import"valibot";o();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]),ji=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()))}),Hi=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}),$i=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}),Gi=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()))}),Wi=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"))}),zi=E.object({provider:E.string()}),Yi=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required"))});o();o();var ra={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"};o();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 ia(){return T.safeParse(Zt,$e)}function aa(){return T.safeParse(Qt,Ge)}function sa(e){return e in $e}function ca(e){return e in Ge}o();o();o();o();o();var We={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Sa={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"},Ea={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},xa={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:We.ANALYTICS},marketing:{requiresConsent:We.MARKETING}};o();o();o();o();o();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"}o();import*as Ye from"valibot";o();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 i;e.extractErrorCode?i=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(i=t.code);let s=e.defaultErrorCode;i&&e.errorCodeMapping&&i in e.errorCodeMapping&&(s=e.errorCodeMapping[i]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),i&&e.friendlyMessageMapping&&i in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[i]),u||(u=e.defaultErrorMessage);let C;return e.processMetadata?C=e.processMetadata(t):(C={originalError:t},i&&(C.originalCode=i)),"originalError"in C||(C.originalError=t),new D(r||u,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 i=Se[r.type]||"unknown";return new D(r.message||H[i],i,{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)}o();function xe(e,t,r={}){let i=globalThis.Sentry;i&&i.withScope(s=>{s.setTag("errorSource",t),s.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,C])=>{if(typeof C!="function"&&u!=="originalError")try{s.setExtra(u,C)}catch{s.setExtra(u,`[${typeof C}]`)}}),Object.entries(r).forEach(([u,C])=>{if(typeof C!="function")try{s.setExtra(`context.${u}`,C)}catch{s.setExtra(`context.${u}`,`[${typeof C}]`)}}),(e.details?.userId||r.userId)&&s.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),i.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:i,context:s={},log:u=!0,reportToSentry:C=!0,showNotification:A=!1,severity:P="error"}=r,R=be(e),I=e instanceof D?e:Ee(e,R,i);if(i&&!I.userMessageProvided&&(I.message.includes("Error")||I.message.includes("Failed")||I.message.length<10?I=new D(i,I.code,{details:{...I.details,originalMessage:I.message},source:R,userMessageProvided:!0}):I=new D(I.message,I.code,{details:{...I.details,userMessage:i},source:R,userMessageProvided:!0})),u){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(i){throw O(i,t)}}}function or(e,t="info",r){let i=Date.now().toString();return i}o();function ir(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}o();function Ke(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ze(e)}async function Xe(e){let r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return Ze(new Uint8Array(i))}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)}o();async function ur(e,t,r){try{return await e()}catch{return t(),!1}}o();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}o();var Qe={[q.GUEST]:0,[q.USER]:1,[q.ADMIN]:2,[q.SUPER]:3};function oe(e,t){if(!e)return!1;let r=Qe[e]??-1,i=Qe[t]??1/0;return r>=i}o();function pr(e,t,r){if(!e)return!1;let i=r??Oe,s=i[e]?.level??-1,u=i[t]?.level??1/0;return s>=u}o();function mr(e,...t){let r=null,i=!1;return function(){if(r!==null)return r;if(i)throw new Error("Circular dependency detected in singleton initialization");i=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{i=!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,i=null;return async function(){if(t!==null)return t;if(r&&i)return i;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return i=e(),t=await i,t}finally{r=!1,i=null}}}function hr(e,t){return new Proxy({},{get(r,i){if(t.includes(i)){let u=e(),C=u[i];return typeof C=="function"?C.bind(u):C}return e()[i]}})}var Ce=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,i={}){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(i.ssrSafe===!1&&typeof window>"u"){if(i.fallbackFactory){let s=i.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(i.cacheFailures&&this.initialized.add(t),i.fallbackFactory){let u=i.fallbackFactory();return this.instances.set(t,u),this.initialized.add(t),u}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()}};o();function vr(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}o();o();import"valibot";o();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"?oe(t,"admin"):oe(t,r)}function Ie(e,t){let r=e;if(!r||typeof r!="object"||!r.entries)return[];let i=r.entries,s=[];for(let[u,C]of Object.entries(i)){let A=br(C);Je(A,t)&&s.push(u)}return s}function Sr(e,t,r){if(!e)return{};let i=Ie(t,r),s={};for(let u of i)Object.prototype.hasOwnProperty.call(e,u)&&(s[u]=e[u]);return s}o();function Z(e,t){let r=new Date(e),i=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==i&&r.setDate(0),r}function Ae(e,t){let r=new Date(e),i=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==i&&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}o();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,i]of Object.entries(e)){if(typeof i!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof i}`);let s=i.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||""}o();function Ar(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,i=e.split(";");for(let s=0;s<i.length;s++){let u=i[s];if(u){for(;u.charAt(0)===" ";)u=u.substring(1,u.length);if(u.indexOf(r)===0)return decodeURIComponent(u.substring(r.length,u.length))}}return null}o();o();o();o();import"valibot";function Oc(e,t){let r=e;return r.metadata=t,r}o();import*as c from"valibot";var Q=new Map;function k(e,t){Q.set(e,t)}function Uc(e){return Q.has(e)}function Mc(){return Array.from(Q.keys())}function Lc(){Q.clear()}function _(e,t){return t?e:c.nullish(e)}var ie=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)},ot=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 i=t.map(u=>u.value),s=c.picklist(i);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 i=t.map(u=>u.value),s=c.array(c.picklist(i));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)},it=()=>c.never(),Br=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let i=[t.checkedValue,t.uncheckedValue],s=c.picklist(i);return _(s,e.validation?.required)}let r=c.boolean();return _(r,e.validation?.required)};function qr(){k("text",ie),k("textarea",ie),k("richtext",ie),k("color",ie),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",ot),k("document",nt),k("documents",ot),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",it),k("reset",it)}qr();function J(e){if(e.validation?.schema){let i=e.validation.schema;return _(i,e.validation?.required)}let t=Q.get(e.type);if(t){let i=t(e);if(i!==null)return i}let r=c.unknown();return _(r,e.validation?.required)}o();var ct=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function lt(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function ae(e,t=""){if(Array.isArray(e))e.forEach((r,i)=>{let s=`${t}[${i}]`;if(typeof r=="string"&<(r)){if(!ct.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,i]of Object.entries(e)){let s=t?`${t}.${r}`:r;if(typeof i=="string"&<(i)){if(!ct.test(i))throw O({userMessage:`Invalid date format for field "${s}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${i}"`,context:{field:s,value:i},severity:"error"})}else typeof i=="object"&&i!==null&&ae(i,s)}}o();import*as dt from"valibot";o();var Pe={};function Gc(e){Pe.uniqueConstraintValidator=e}async function ut(e,t,r){let{uniqueFields:i=[],collection:s}=e.metadata;i.length!==0&&Pe.uniqueConstraintValidator&&await Promise.all(i.map(async({field:u,errorMessage:C})=>{let A=t[u];if(A==null)return;if(await Pe.uniqueConstraintValidator.checkDuplicate(s,u,A,r))throw O({userMessage:C||`${u} must be unique`,code:"already-exists",context:{field:u}})}))}async function Xc(e,t,r,i){dt.parse(e,t),ae(t),await ut(e,t,i),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}o();function Vr(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function sl(e){if(!Vr(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}o();var _e=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],dl="available",pl=["draft","deleted"],z=["id","createdAt","updatedAt","createdById","updatedById"],jr=[...z,"status"];function ml(e){return jr.includes(e)}function gl(e){return z.includes(e)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[..._e]}},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}}};o();function Hr(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})),i=new Set(e.map(s=>s.value));for(let s of t)i.has(s.value)||r.push(s);return r}function $r(e){let{form:t,fields:r}=e,i=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),u=s.filter(P=>!i.includes(P));if(u.length>0)throw O(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${u.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${u.join(", ")}`,context:{entityName:e.name,invalidFields:u,operation:"validateFormConfig"},severity:"error"});let C=new Set(s);i.filter(P=>!C.has(P)).length>0}t.rules&&t.rules.forEach((s,u)=>{let A=(Array.isArray(s.condition)?s.condition.map(I=>I.field):[s.condition.field]).filter(I=>!i.includes(I));if(A.length>0)throw O(new Error(`Dynamic form rule ${u} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`),{userMessage:`Dynamic form rule ${u} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`,context:{entityName:e.name,ruleIndex:u,invalidFields:A,operation:"validateFormConfig"},severity:"error"});let R=[...s.showFields||[],...s.hideFields||[],...s.disableFields||[],...s.enableFields||[]].filter(I=>!i.includes(I));if(R.length>0)throw O(new Error(`Dynamic form rule ${u} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`),{userMessage:`Dynamic form rule ${u} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`,context:{entityName:e.name,ruleIndex:u,invalidFields:R,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([s,u])=>{if(u.dependsOn&&!i.includes(u.dependsOn.field))throw O(new Error(`Field '${s}' in entity '${e.name}' depends on non-existent field: ${u.dependsOn.field}`),{userMessage:`Field '${s}' in entity '${e.name}' depends on non-existent field: ${u.dependsOn.field}`,context:{entityName:e.name,fieldName:s,dependsOnField:u.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Gr(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 Sl(e){try{$r(e);let t=Gr(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:Hr(_e,e.fields.status.validation?.options)}}}};if(e.listFields){let s=new Set(Object.keys(r)),u=e.listFields.filter(C=>!s.has(C));if(u.length>0)throw O(new Error(`Entity '${e.name}' defines listFields that do not exist: ${u.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${u.join(", ")}`,context:{entityName:e.name,invalidFields:u,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),u=e.listCardFields.filter(C=>!s.has(C));if(u.length>0)throw O(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${u.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${u.join(", ")}`,context:{entityName:e.name,invalidFields:u,operation:"defineEntity"},severity:"error"})}let i={...fe,...e.access||{}};return{...e,form:t,fields:r,access:i}}catch(t){throw O(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}o();import*as B from"valibot";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 pt(e){let t=J(e);return ee(t,e.visibility)}function mt(e){let t=J({...e,validation:{...e.validation,required:!1}});return ee(t,e.visibility)}function Al(e){let t=e.fields,r={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(r[N]=pt(F));let i=$(B.object(r),e),s={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(s[N]=pt(F)));let u=$(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]=mt(F);let A=$(B.object(C),e),P={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(P[N]=mt(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:u,draft:A,update:R,get:i,list:U,listCard:gt,delete:ft}}export{qo as AUTH_EVENTS,$e as AUTH_PARTNERS,zn as AUTH_PARTNER_STATE,Be as AuthUserSchema,z as BACKEND_GENERATED_FIELD_NAMES,Ho as BILLING_EVENTS,Ht as BREAKPOINT_RANGES,ve as BREAKPOINT_THRESHOLDS,Oe as COMMON_TIER_CONFIGS,io as CONFIDENCE_LEVELS,We as CONSENT_CATEGORY,oo as CONTEXTS,Le as CheckoutSessionMetadataSchema,De as CreateCheckoutSessionRequestSchema,Ne as CreateCheckoutSessionResponseSchema,qe as CustomClaimsSchema,fe as DEFAULT_ENTITY_ACCESS,H as DEFAULT_ERROR_MESSAGES,Ii as DEFAULT_LAYOUT_PRESET,_e as DEFAULT_STATUS_OPTIONS,dl as DEFAULT_STATUS_VALUE,vn as DEFAULT_SUBSCRIPTION,Ea as DENSITY,D as DoNotDevError,no as ENVIRONMENTS,Ve as EntityHookError,pe as FEATURES,xa as FEATURE_CONSENT_MATRIX,ao as FEATURE_STATUS,he as FIREBASE_ERROR_MAP,re as FIRESTORE_ID_PATTERN,je as GITHUB_PERMISSION_LEVELS,pl as HIDDEN_STATUSES,Sa as LAYOUT_PRESET,Wo as OAUTH_EVENTS,Ge as OAUTH_PARTNERS,ra as PARTNER_ICONS,Ko as PAYLOAD_EVENTS,me as PERMISSIONS,ro as PLATFORMS,uo as PWA_ASSET_TYPES,lo as PWA_DISPLAY_MODES,qt as ProductDeclarationSchema,kn as ProductDeclarationsSchema,po as ROUTE_SOURCES,co as STORAGE_SCOPES,so as STORAGE_TYPES,Qo as STRIPE_EVENTS,te as STRIPE_MODES,fn 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,jr 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,$i as checkGitHubAccessSchema,Lc as clearSchemaGenerators,X as commonErrorCodeMappings,ce as compactToISOString,fr as createAsyncSingleton,hn as createDefaultSubscriptionClaims,Yn as createDefaultUserProfile,xo as createEntitySchema,L as createErrorHandler,kt as createMetadata,hr as createMethodProxy,Al as createSchemas,mr as createSingleton,gr as createSingletonWithParams,Sl as defineEntity,Io as deleteEntitySchema,be as detectErrorSource,zi as disconnectOAuthSchema,Oc as enhanceSchema,Gi as exchangeTokenSchema,Sr as filterVisibleFields,we as formatDate,Nt as formatRelativeTime,Xe as generateCodeChallenge,Ke as generateCodeVerifier,ar as generatePKCEPair,$t as getBreakpointFromWidth,xi as getBreakpointUtils,sl as getCollectionName,Yi as getConnectionsSchema,_t as getCurrentTimestamp,To as getEntitySchema,Mc as getRegisteredSchemaTypes,J as getSchemaType,Ie as getVisibleFields,Dt as getWeekFromISOString,Gt as githubPermissionSchema,ye as githubRepoConfigSchema,ji as grantGitHubAccessSchema,O as handleError,Uc as hasCustomSchemaGenerator,Vr as hasMetadata,oe as hasRoleAccess,pr as hasTierAccess,sa as isAuthPartnerId,gl as isBackendGeneratedField,Ei as isBreakpoint,le as isCompactDateString,Je as isFieldVisible,ml as isFrameworkField,ca as isOAuthPartnerId,sr as isPKCESupported,Rt as isoToCompactString,dr as lazyImport,Ao as listEntitiesSchema,Ee as mapToDoNotDevError,ir as maybeTranslate,Pt as normalizeToISOString,ln as overrideFeatures,gn as overridePaymentModes,un as overridePermissions,mn as overrideSubscriptionStatus,cn as overrideSubscriptionTiers,sn as overrideUserRoles,ue as parseDate,Ut as parseDateToNoonUTC,xr as parseISODate,Ar as parseServerCookie,Wi as refreshTokenSchema,k as registerSchemaGenerator,Gc as registerUniqueConstraintValidator,Hi as revokeGitHubAccessSchema,or as showNotification,Ot as timestampToISOString,Mt as toDateOnly,wt as toISOString,Tt as translateArray,It as translateArrayRange,At as translateArrayWithIndices,Ct as translateObjectArray,Co as updateEntitySchema,vr as updateMetadata,ia as validateAuthPartners,$n as validateAuthSchemas,Vn as validateAuthUser,_n as validateBillingSchemas,An as validateCheckoutSessionMetadata,lr as validateCodeChallenge,cr as validateCodeVerifier,En as validateCreateCheckoutSessionRequest,xn as validateCreateCheckoutSessionResponse,Hn as validateCustomClaims,ae as validateDates,Xc as validateDocument,Ir as validateEnvVar,Cr as validateMetadata,aa as validateOAuthPartners,Pn as validateStripeBackConfig,Rn as validateStripeFrontConfig,Cn as validateSubscriptionClaims,Tn as validateSubscriptionData,ut as validateUniqueFields,Tr as validateUrl,jn as validateUserSubscription,In as validateWebhookEvent,nr as withErrorHandling,ur as withGracefulDegradation};
|
|
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};
|