@donotdev/functions 0.3.0 → 0.3.1
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/guidelines/VERCEL.md +2 -2
- package/lib/chunks/{chunk-HZM5X5A7.js → chunk-2N73OZFE.js} +2 -2
- package/lib/chunks/{chunk-OAZ2JYSD.js → chunk-472JD6X7.js} +2 -2
- package/lib/chunks/{chunk-OKRR7ST5.js → chunk-BTWJEJCV.js} +2 -2
- package/lib/chunks/{chunk-CP3NNKO5.js → chunk-CN6WXKYF.js} +2 -2
- package/lib/chunks/{chunk-CVYSXC27.js → chunk-DGBZDD6D.js} +2 -2
- package/lib/chunks/{chunk-7ODXXXES.js → chunk-GBZQPOX4.js} +2 -2
- package/lib/chunks/chunk-ORBGTVJI.js +22 -0
- package/lib/chunks/{chunk-TJPJXJEK.js.map → chunk-ORBGTVJI.js.map} +1 -1
- package/lib/chunks/chunk-R3I7U5QT.js +22 -0
- package/lib/chunks/{chunk-PDBNKSBQ.js.map → chunk-R3I7U5QT.js.map} +1 -1
- package/lib/chunks/{chunk-522YXGDA.js → chunk-XWMG2FWZ.js} +2 -2
- package/lib/chunks/{chunk-522YXGDA.js.map → chunk-XWMG2FWZ.js.map} +1 -1
- package/lib/chunks/chunk-ZCY6GTIC.js +22 -0
- package/lib/chunks/{chunk-ICNQCRLV.js.map → chunk-ZCY6GTIC.js.map} +4 -4
- package/lib/chunks/{monitoring-UCBNPPW2.js → monitoring-KF7FRUQ6.js} +2 -2
- package/lib/chunks/{rateLimiter-XKECWM33.js → rateLimiter-S7TITXOD.js} +2 -2
- package/lib/chunks/{server-24XGDDO3.js → server-SU4BVPPF.js} +2 -2
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +1 -1
- package/lib/shared/index.js +1 -1
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/index.js +1 -1
- package/package.json +3 -3
- package/lib/chunks/chunk-ICNQCRLV.js +0 -22
- package/lib/chunks/chunk-PDBNKSBQ.js +0 -22
- package/lib/chunks/chunk-TJPJXJEK.js +0 -22
- /package/lib/chunks/{chunk-HZM5X5A7.js.map → chunk-2N73OZFE.js.map} +0 -0
- /package/lib/chunks/{chunk-OAZ2JYSD.js.map → chunk-472JD6X7.js.map} +0 -0
- /package/lib/chunks/{chunk-OKRR7ST5.js.map → chunk-BTWJEJCV.js.map} +0 -0
- /package/lib/chunks/{chunk-CP3NNKO5.js.map → chunk-CN6WXKYF.js.map} +0 -0
- /package/lib/chunks/{chunk-CVYSXC27.js.map → chunk-DGBZDD6D.js.map} +0 -0
- /package/lib/chunks/{chunk-7ODXXXES.js.map → chunk-GBZQPOX4.js.map} +0 -0
- /package/lib/chunks/{monitoring-UCBNPPW2.js.map → monitoring-KF7FRUQ6.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-XKECWM33.js.map → rateLimiter-S7TITXOD.js.map} +0 -0
- /package/lib/chunks/{server-24XGDDO3.js.map → server-SU4BVPPF.js.map} +0 -0
package/lib/vercel/api/index.js
CHANGED
|
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{b as B,e as M,f as P,g as z}from"../../chunks/chunk-TJPJXJEK.js";import{a as Q,c as ee}from"../../chunks/chunk-HLNYUAZH.js";import{a as X,b as d,c as A,d as Z}from"../../chunks/chunk-OKRR7ST5.js";import{A as J,a as m,d as $,r as G,s as k,x as H,y as Y}from"../../chunks/chunk-7ODXXXES.js";import{C as E,D as I,E as F,J as V,S as K,h as j,l as L,t as y,u as q,x as l}from"../../chunks/chunk-ICNQCRLV.js";import{a as O}from"../../chunks/chunk-CVYSXC27.js";import{b as W,f as U}from"../../chunks/chunk-HZM5X5A7.js";import{a as D}from"../../chunks/chunk-W6W4L44F.js";import{a as o}from"../../chunks/chunk-AYY7UXNI.js";function se(s){return async t=>{let e=t.headers.get("authorization");if(!e?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let i=e.slice(7),n;try{n=(await M(i)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),c=I(F,a);if(!c.success){let u=c.issues.map(r=>r.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${u}`}),{status:400,headers:{"Content-Type":"application/json"}})}return $(c.output,s,{userId:n,requestId:crypto.randomUUID()})}}o(se,"createAIChatRoute");var oe=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function je(s){let t=new Set(s.allowedClaimKeys);for(let e of t)if(oe.has(e))throw new Error(`Claim key "${e}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return o(async function(i,n){if(i.method!=="POST")return n.status(405).json({error:"Method not allowed"});try{let a=await P(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw m(new Error("customClaims must be an object"));let u=Object.keys(c).filter(C=>!t.has(C));if(u.length>0)throw m(new Error(`Claim keys not allowed: ${u.join(", ")}`));let{getFirebaseAdminAuth:r}=await import("../../chunks/server-24XGDDO3.js"),S={...(await r().getUser(a)).customClaims||{},...c};return await r().setCustomUserClaims(a,S),n.status(200).json({success:!0,customClaims:S})}catch(a){throw m(a)}},"handler")}o(je,"createSetCustomClaimsHandler");var _=null;async function T(){if(_)return _;let s=process.env.SUPABASE_URL,t=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!t)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:e}=await import("@supabase/supabase-js");return _=e(s,t,{auth:{autoRefreshToken:!1,persistSession:!1}}),_}o(T,"getSupabaseAdmin");async function N(s){if(B(s)==="supabase"){let e=await T();return{authProvider:Q(e),idempotencyStore:J(e)}}let{getFirebaseAdminAuth:t}=await import("../../chunks/server-24XGDDO3.js");return{authProvider:{async getUser(e){return{customClaims:(await t().getUser(e)).customClaims}},async setCustomUserClaims(e,i){await t().setCustomUserClaims(e,i)}},idempotencyStore:z()}}o(N,"resolveBillingBackend");function f(s,t,e,i,n,a){return a!==void 0&&B(a),async(c,u)=>{try{if(c.method!==s)return u.status(405).json({error:"Method not allowed"});let r=I(t,c.body);if(!r.success)return u.status(400).json({error:`Validation failed: ${r.issues.map(b=>b.message).join(", ")}`});let p=r.output,g=await P(c,a),S=`${e}_${g}`,h=U[e]||U.api,x=a==="supabase"?await ee(await T(),S,h):await W(S,h);if(!x.allowed)return n?.audit({type:"rate_limit.exceeded",userId:g,metadata:{operation:e,remaining:0}}),u.status(429).json({error:`Rate limit exceeded. Try again in ${x.blockRemainingSeconds} seconds.`,retryAfter:x.blockRemainingSeconds});let w=await i(c,u,p,{uid:g});return w==null&&console.warn(`[${e}] businessLogic returned ${w} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:g,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),w}catch(r){process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:r instanceof Error?r.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{m(r)}catch(p){let g=ie(p);return u.status(g.status).json({error:g.message})}return u.status(500).json({error:"Internal server error"})}}}o(f,"createVercelBaseFunction");function ie(s){return s instanceof K?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[s.code]??500,message:s.message}:{status:500,message:"Internal server error"}}o(ie,"classifiedToHttp");async function ne(s,t,e,i,n){X(process.env.STRIPE_SECRET_KEY||""),A();let a={async createStripeSession(r){let p=await d.checkout.sessions.create(r);return{id:p.id,url:p.url}},async retrieveTaxRate(r){let p=await d.taxRates.retrieve(r);return{id:p.id,inclusive:p.inclusive}}},{authProvider:c}=await N(n.backend),u=await G(t,e.uid,a,c,i);return s.status(200).json(u)}o(ne,"createCheckoutSessionLogic");function ae(s,t){return f("POST",V,"create_checkout_session",(e,i,n,a)=>ne(i,n,a,s,t),void 0,t.backend)}o(ae,"createCheckoutSession");function ce(s,t){return async(e,i)=>{if(e.method!=="POST"){i.status(405).json({error:"Method not allowed"});return}try{let n=e.headers["stripe-signature"];if(!n||Array.isArray(n))throw new Error("No Stripe signature found");let a=process.env.STRIPE_WEBHOOK_SECRET;if(!a)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(e.headers["content-length"]||"0",10)>te){i.status(413).json({error:"Payload too large"});return}let u=await ue(e),{authProvider:r,idempotencyStore:p}=await N(t.backend);await Y(u,n,a,d,s,k,r,p),i.status(200).json({received:!0})}catch(n){D.error("[Vercel Webhook] Error",{error:n instanceof Error?n:new Error(String(n)),operation:"webhook_processing"}),i.status(400).json({error:"Webhook processing failed"})}}}o(ce,"createStripeWebhook");var te=1*1024*1024;async function ue(s){let t=[],e=0;for await(let i of s){let n=typeof i=="string"?Buffer.from(i):i;if(e+=n.length,e>te)throw new Error("Request body too large");t.push(n)}return Buffer.concat(t)}o(ue,"getRawBody");var pe=y({userId:E(l(),j(1,"User ID is required"))});function me(s){return{}[s||""]||"free"}o(me,"getTierFromPriceId");async function de(s,t,e,i){A();let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-24XGDDO3.js"),u=(await a().getUser(n)).customClaims||{};if(!u.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let r=await d.subscriptions.retrieve(u.subscriptionId),p={tier:me(r.items.data[0]?.price.id),subscriptionId:r.id,customerId:r.customer,status:r.status,currentPeriodEnd:new Date(r.current_period_end*1e3).toISOString()};return await a().setCustomUserClaims(n,{...u,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}o(de,"refreshSubscriptionStatusLogic");var le=o(s=>f("POST",s||pe,"refresh_subscription_status",de),"refreshSubscriptionStatus"),fe=le;var ge=y({userId:l()});async function Se(s,t,e,i){let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-24XGDDO3.js"),u=await Z(n,{async getUser(r){return a().getUser(r)},async setCustomUserClaims(r,p){await a().setCustomUserClaims(r,p)}});return t.status(200).json({success:u.success,cancelAtPeriodEnd:!0,endsAt:u.endsAt})}o(Se,"cancelSubscriptionLogic");var he=o(()=>f("POST",ge,"cancel_subscription",Se),"cancelSubscription"),ye=he;var Ae=y({userId:l(),newPriceId:l(),billingConfigKey:l()});async function we(s,t,e,i,n){A();let a=i.uid,{newPriceId:c,billingConfigKey:u}=e,r=n[u];if(!r||r.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(r.priceId!==c)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-24XGDDO3.js"),S=(await p().getUser(a)).customClaims?.subscription?.subscriptionId;if(!S)throw m(new Error("No active subscription"));let C=await d.subscriptions.retrieve(S),h=await d.subscriptions.update(S,{items:[{id:C.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),w=H(["active","canceled","past_due","trialing","incomplete"],h.status)?h.status:"incomplete";return await k(a,{tier:r.tier,status:w,subscriptionEnd:new Date(h.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:h.cancel_at_period_end,subscriptionId:h.id,customerId:h.customer},{async getUser(b){return p().getUser(b)},async setCustomUserClaims(b,re){await p().setCustomUserClaims(b,re)}}),t.status(200).json({success:!0,newTier:r.tier,newPrice:r.price})}o(we,"changePlanLogic");var be=o(s=>f("POST",Ae,"change_plan",(t,e,i,n)=>we(t,e,i,n,s)),"changePlan"),Re=be;var ve=y({userId:l(),returnUrl:q(E(l(),L()))});async function Ce(s,t,e,i){A();let n=i.uid,{returnUrl:a}=e,{getFirebaseAdminAuth:c}=await import("../../chunks/server-24XGDDO3.js"),r=(await c().getUser(n)).customClaims?.subscription?.customerId;if(!r)throw m(new Error("No customer found"));let p=await d.billingPortal.sessions.create({customer:r,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}o(Ce,"createCustomerPortalLogic");var xe=o(()=>f("POST",ve,"create_customer_portal",Ce),"createCustomerPortal"),Ee=xe;var v=process.env.FIREBASE_REGION||"europe-west1",Wt={region:v,memory:"1GiB",timeoutSeconds:60},$t={region:v,memory:"512MiB",timeoutSeconds:30},Gt={region:v,memory:"256MiB",timeoutSeconds:20},Ht={region:v,memory:"256MiB",timeoutSeconds:15},Yt={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},zt=o(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${v}`)},"validateEnvironment");async function Zt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-24XGDDO3.js");return await s()}o(Zt,"initializeFirebaseAdmin");async function Qt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-24XGDDO3.js");return await s()}o(Qt,"getFirebaseAdmin");export{Gt as AUTH_CONFIG,Yt as AVAILABLE_REGIONS,Ht as CRUD_CONFIG,v as FIREBASE_REGION,Wt as FUNCTION_CONFIG,$t as STRIPE_CONFIG,ye as cancelSubscription,Re as changePlan,se as createAIChatRoute,ae as createCheckoutSession,Ee as createCustomerPortal,je as createSetCustomClaimsHandler,ce as createStripeWebhook,Qt as getFirebaseAdmin,Zt as initializeFirebaseAdmin,fe as refreshSubscriptionStatus,k as updateUserSubscription,zt as validateEnvironment};
|
|
21
|
+
import{b as B,e as M,f as P,g as z}from"../../chunks/chunk-ORBGTVJI.js";import{a as Q,c as ee}from"../../chunks/chunk-HLNYUAZH.js";import{a as X,b as d,c as A,d as Z}from"../../chunks/chunk-BTWJEJCV.js";import{A as J,a as m,d as $,r as G,s as k,x as H,y as Y}from"../../chunks/chunk-GBZQPOX4.js";import{F as E,G as I,H as F,M as V,V as K,h as j,l as L,v as y,w as q,z as l}from"../../chunks/chunk-ZCY6GTIC.js";import{a as O}from"../../chunks/chunk-DGBZDD6D.js";import{b as W,f as U}from"../../chunks/chunk-2N73OZFE.js";import{a as D}from"../../chunks/chunk-W6W4L44F.js";import{a as o}from"../../chunks/chunk-AYY7UXNI.js";function se(s){return async t=>{let e=t.headers.get("authorization");if(!e?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let i=e.slice(7),n;try{n=(await M(i)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),c=I(F,a);if(!c.success){let u=c.issues.map(r=>r.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${u}`}),{status:400,headers:{"Content-Type":"application/json"}})}return $(c.output,s,{userId:n,requestId:crypto.randomUUID()})}}o(se,"createAIChatRoute");var oe=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function je(s){let t=new Set(s.allowedClaimKeys);for(let e of t)if(oe.has(e))throw new Error(`Claim key "${e}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return o(async function(i,n){if(i.method!=="POST")return n.status(405).json({error:"Method not allowed"});try{let a=await P(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw m(new Error("customClaims must be an object"));let u=Object.keys(c).filter(C=>!t.has(C));if(u.length>0)throw m(new Error(`Claim keys not allowed: ${u.join(", ")}`));let{getFirebaseAdminAuth:r}=await import("../../chunks/server-SU4BVPPF.js"),S={...(await r().getUser(a)).customClaims||{},...c};return await r().setCustomUserClaims(a,S),n.status(200).json({success:!0,customClaims:S})}catch(a){throw m(a)}},"handler")}o(je,"createSetCustomClaimsHandler");var _=null;async function T(){if(_)return _;let s=process.env.SUPABASE_URL,t=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!t)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:e}=await import("@supabase/supabase-js");return _=e(s,t,{auth:{autoRefreshToken:!1,persistSession:!1}}),_}o(T,"getSupabaseAdmin");async function N(s){if(B(s)==="supabase"){let e=await T();return{authProvider:Q(e),idempotencyStore:J(e)}}let{getFirebaseAdminAuth:t}=await import("../../chunks/server-SU4BVPPF.js");return{authProvider:{async getUser(e){return{customClaims:(await t().getUser(e)).customClaims}},async setCustomUserClaims(e,i){await t().setCustomUserClaims(e,i)}},idempotencyStore:z()}}o(N,"resolveBillingBackend");function f(s,t,e,i,n,a){return a!==void 0&&B(a),async(c,u)=>{try{if(c.method!==s)return u.status(405).json({error:"Method not allowed"});let r=I(t,c.body);if(!r.success)return u.status(400).json({error:`Validation failed: ${r.issues.map(b=>b.message).join(", ")}`});let p=r.output,g=await P(c,a),S=`${e}_${g}`,h=U[e]||U.api,x=a==="supabase"?await ee(await T(),S,h):await W(S,h);if(!x.allowed)return n?.audit({type:"rate_limit.exceeded",userId:g,metadata:{operation:e,remaining:0}}),u.status(429).json({error:`Rate limit exceeded. Try again in ${x.blockRemainingSeconds} seconds.`,retryAfter:x.blockRemainingSeconds});let w=await i(c,u,p,{uid:g});return w==null&&console.warn(`[${e}] businessLogic returned ${w} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:g,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),w}catch(r){process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:r instanceof Error?r.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{m(r)}catch(p){let g=ie(p);return u.status(g.status).json({error:g.message})}return u.status(500).json({error:"Internal server error"})}}}o(f,"createVercelBaseFunction");function ie(s){return s instanceof K?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[s.code]??500,message:s.message}:{status:500,message:"Internal server error"}}o(ie,"classifiedToHttp");async function ne(s,t,e,i,n){X(process.env.STRIPE_SECRET_KEY||""),A();let a={async createStripeSession(r){let p=await d.checkout.sessions.create(r);return{id:p.id,url:p.url}},async retrieveTaxRate(r){let p=await d.taxRates.retrieve(r);return{id:p.id,inclusive:p.inclusive}}},{authProvider:c}=await N(n.backend),u=await G(t,e.uid,a,c,i);return s.status(200).json(u)}o(ne,"createCheckoutSessionLogic");function ae(s,t){return f("POST",V,"create_checkout_session",(e,i,n,a)=>ne(i,n,a,s,t),void 0,t.backend)}o(ae,"createCheckoutSession");function ce(s,t){return async(e,i)=>{if(e.method!=="POST"){i.status(405).json({error:"Method not allowed"});return}try{let n=e.headers["stripe-signature"];if(!n||Array.isArray(n))throw new Error("No Stripe signature found");let a=process.env.STRIPE_WEBHOOK_SECRET;if(!a)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(e.headers["content-length"]||"0",10)>te){i.status(413).json({error:"Payload too large"});return}let u=await ue(e),{authProvider:r,idempotencyStore:p}=await N(t.backend);await Y(u,n,a,d,s,k,r,p),i.status(200).json({received:!0})}catch(n){D.error("[Vercel Webhook] Error",{error:n instanceof Error?n:new Error(String(n)),operation:"webhook_processing"}),i.status(400).json({error:"Webhook processing failed"})}}}o(ce,"createStripeWebhook");var te=1*1024*1024;async function ue(s){let t=[],e=0;for await(let i of s){let n=typeof i=="string"?Buffer.from(i):i;if(e+=n.length,e>te)throw new Error("Request body too large");t.push(n)}return Buffer.concat(t)}o(ue,"getRawBody");var pe=y({userId:E(l(),j(1,"User ID is required"))});function me(s){return{}[s||""]||"free"}o(me,"getTierFromPriceId");async function de(s,t,e,i){A();let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-SU4BVPPF.js"),u=(await a().getUser(n)).customClaims||{};if(!u.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let r=await d.subscriptions.retrieve(u.subscriptionId),p={tier:me(r.items.data[0]?.price.id),subscriptionId:r.id,customerId:r.customer,status:r.status,currentPeriodEnd:new Date(r.current_period_end*1e3).toISOString()};return await a().setCustomUserClaims(n,{...u,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}o(de,"refreshSubscriptionStatusLogic");var le=o(s=>f("POST",s||pe,"refresh_subscription_status",de),"refreshSubscriptionStatus"),fe=le;var ge=y({userId:l()});async function Se(s,t,e,i){let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-SU4BVPPF.js"),u=await Z(n,{async getUser(r){return a().getUser(r)},async setCustomUserClaims(r,p){await a().setCustomUserClaims(r,p)}});return t.status(200).json({success:u.success,cancelAtPeriodEnd:!0,endsAt:u.endsAt})}o(Se,"cancelSubscriptionLogic");var he=o(()=>f("POST",ge,"cancel_subscription",Se),"cancelSubscription"),ye=he;var Ae=y({userId:l(),newPriceId:l(),billingConfigKey:l()});async function we(s,t,e,i,n){A();let a=i.uid,{newPriceId:c,billingConfigKey:u}=e,r=n[u];if(!r||r.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(r.priceId!==c)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-SU4BVPPF.js"),S=(await p().getUser(a)).customClaims?.subscription?.subscriptionId;if(!S)throw m(new Error("No active subscription"));let C=await d.subscriptions.retrieve(S),h=await d.subscriptions.update(S,{items:[{id:C.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),w=H(["active","canceled","past_due","trialing","incomplete"],h.status)?h.status:"incomplete";return await k(a,{tier:r.tier,status:w,subscriptionEnd:new Date(h.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:h.cancel_at_period_end,subscriptionId:h.id,customerId:h.customer},{async getUser(b){return p().getUser(b)},async setCustomUserClaims(b,re){await p().setCustomUserClaims(b,re)}}),t.status(200).json({success:!0,newTier:r.tier,newPrice:r.price})}o(we,"changePlanLogic");var be=o(s=>f("POST",Ae,"change_plan",(t,e,i,n)=>we(t,e,i,n,s)),"changePlan"),Re=be;var ve=y({userId:l(),returnUrl:q(E(l(),L()))});async function Ce(s,t,e,i){A();let n=i.uid,{returnUrl:a}=e,{getFirebaseAdminAuth:c}=await import("../../chunks/server-SU4BVPPF.js"),r=(await c().getUser(n)).customClaims?.subscription?.customerId;if(!r)throw m(new Error("No customer found"));let p=await d.billingPortal.sessions.create({customer:r,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}o(Ce,"createCustomerPortalLogic");var xe=o(()=>f("POST",ve,"create_customer_portal",Ce),"createCustomerPortal"),Ee=xe;var v=process.env.FIREBASE_REGION||"europe-west1",Wt={region:v,memory:"1GiB",timeoutSeconds:60},$t={region:v,memory:"512MiB",timeoutSeconds:30},Gt={region:v,memory:"256MiB",timeoutSeconds:20},Ht={region:v,memory:"256MiB",timeoutSeconds:15},Yt={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},zt=o(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${v}`)},"validateEnvironment");async function Zt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-SU4BVPPF.js");return await s()}o(Zt,"initializeFirebaseAdmin");async function Qt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-SU4BVPPF.js");return await s()}o(Qt,"getFirebaseAdmin");export{Gt as AUTH_CONFIG,Yt as AVAILABLE_REGIONS,Ht as CRUD_CONFIG,v as FIREBASE_REGION,Wt as FUNCTION_CONFIG,$t as STRIPE_CONFIG,ye as cancelSubscription,Re as changePlan,se as createAIChatRoute,ae as createCheckoutSession,Ee as createCustomerPortal,je as createSetCustomClaimsHandler,ce as createStripeWebhook,Qt as getFirebaseAdmin,Zt as initializeFirebaseAdmin,fe as refreshSubscriptionStatus,k as updateUserSubscription,zt as validateEnvironment};
|
|
22
22
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/functions",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
|
|
6
6
|
"main": "./lib/firebase/index.js",
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"serve": "firebase emulators:start --only functions"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@donotdev/core": "^0.3.
|
|
57
|
-
"@donotdev/supabase": "^0.3.
|
|
56
|
+
"@donotdev/core": "^0.3.1",
|
|
57
|
+
"@donotdev/supabase": "^0.3.1"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
60
|
"@ai-sdk/anthropic": "^4.0.102",
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
4
|
-
import { Buffer } from 'node:buffer';
|
|
5
|
-
import process from 'node:process';
|
|
6
|
-
|
|
7
|
-
const require = __createRequire(import.meta.url);
|
|
8
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
-
const __dirname = dirname(__filename);
|
|
10
|
-
|
|
11
|
-
if (typeof globalThis !== 'undefined') {
|
|
12
|
-
globalThis.require = require;
|
|
13
|
-
globalThis.__filename = __filename;
|
|
14
|
-
globalThis.__dirname = __dirname;
|
|
15
|
-
globalThis.Buffer = Buffer;
|
|
16
|
-
globalThis.process = process;
|
|
17
|
-
if (typeof global === 'undefined') {
|
|
18
|
-
globalThis.global = globalThis;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
import{a as r}from"./chunk-AYY7UXNI.js";var Ee={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"};var Ie={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},We={[Ee.PERMISSION_DENIED]:{type:Ie.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[Ee.NOT_FOUND]:{type:Ie.NOT_FOUND,message:"The requested resource was not found"},[Ee.ALREADY_EXISTS]:{type:Ie.ALREADY_EXISTS,message:"The resource already exists"},[Ee.INVALID_ARGUMENT]:{type:Ie.VALIDATION_ERROR,message:"Invalid argument provided"}};function ln(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}r(ln,"hasCaptureStackTrace");var k=class e extends Error{static{r(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=Ee.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,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,ln(Error)&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var $={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Ce={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},oi={[$.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[$.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[$.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}};var si={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},ai=4,ui={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};var we,cn={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Ge(e){return!e&&!we?cn:{lang:e?.lang??we?.lang,message:e?.message,abortEarly:e?.abortEarly??we?.abortEarly,abortPipeEarly:e?.abortPipeEarly??we?.abortPipeEarly}}r(Ge,"getGlobalConfig");var pn;function dn(e){return pn?.get(e)}r(dn,"getGlobalMessage");var fn;function mn(e){return fn?.get(e)}r(mn,"getSchemaMessage");var yn;function gn(e,t){return yn?.get(e)?.get(t)}r(gn,"getSpecificMessage");function te(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}r(te,"_stringify");function x(e,t,n,o,a){let u=a&&"input"in a?a.input:n.value,l=a?.expected??e.expects??null,m=a?.received??te(u),d={kind:e.kind,type:e.type,input:u,expected:l,received:m,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",f=a?.message??e.message??gn(e.reference,d.lang)??(h?mn(d.lang):null)??o.message??dn(d.lang);f!==void 0&&(d.message=typeof f=="function"?f(d):f),h&&(n.typed=!1),n.issues?n.issues.push(d):n.issues=[d]}r(x,"_addIssue");function hn(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}r(hn,"_isSameValueZero");function mt(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}r(mt,"_isValidObjectKey");function Ke(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}r(Ke,"_joinExpects");function A(e){return e["~standard"]={version:1,vendor:"valibot",validate:r(t=>e["~run"]({value:t},Ge()),"validate")},e}r(A,"_standardSchema");var Oe=class extends Error{static{r(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function ci(e){return e instanceof Oe}r(ci,"isValiError");var vn=/^[\w+-]+(?:\.[\w+-]+)*@[\da-zA-Z]+(?:[.-][\da-zA-Z]+)*\.[a-zA-Z]{2,}$/u,pi=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u");var bn=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;function ne(e,t){return{kind:"validation",type:"check",reference:ne,async:!1,expects:null,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement(n.value)&&x(this,"input",n,o),n}}}r(ne,"check");function B(e){return{kind:"validation",type:"email",reference:B,expects:null,async:!1,requirement:vn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&x(this,"email",t,n),t}}}r(B,"email");function q(e){return{kind:"validation",type:"integer",reference:q,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&x(this,"integer",t,n),t}}}r(q,"integer");function de(e){return{kind:"validation",type:"iso_timestamp",reference:de,async:!1,expects:null,requirement:bn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&x(this,"timestamp",t,n),t}}}r(de,"isoTimestamp");function fe(e,t){return{kind:"validation",type:"length",reference:fe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length!==this.requirement&&x(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(fe,"length");function W(e,t){return{kind:"validation",type:"max_length",reference:W,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length>this.requirement&&x(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(W,"maxLength");function V(e,t){return{kind:"validation",type:"max_value",reference:V,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value<=this.requirement)&&x(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(V,"maxValue");function y(e,t){return{kind:"validation",type:"min_length",reference:y,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length<this.requirement&&x(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(y,"minLength");function R(e,t){return{kind:"validation",type:"min_value",reference:R,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value>=this.requirement)&&x(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(R,"minValue");function He(e){return{kind:"transformation",type:"raw_transform",reference:He,async:!1,"~run"(t,n){let o=e({dataset:t,config:n,addIssue:r(a=>x(this,a?.label??"input",t,n,a),"addIssue"),NEVER:null});return t.issues?t.typed=!1:t.value=o,t}}}r(He,"rawTransform");function j(e,t){return{kind:"validation",type:"regex",reference:j,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement.test(n.value)&&x(this,"format",n,o),n}}}r(j,"regex");function En(e){return{kind:"transformation",type:"transform",reference:En,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}r(En,"transform");function D(e){return{kind:"validation",type:"url",reference:D,async:!1,expects:null,requirement(t){try{return URL.canParse?URL.canParse(t):(new URL(t),!0)}catch{return!1}},message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&x(this,"URL",t,n),t}}}r(D,"url");var xn={abortEarly:!0};function yt(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}r(yt,"getFallback");function xe(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}r(xe,"getDefault");function re(){return A({kind:"schema",type:"any",reference:re,expects:"any",async:!1,"~run"(e){return e.typed=!0,e}})}r(re,"any");function g(e,t){return A({kind:"schema",type:"array",reference:g,expects:"Array",async:!1,item:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<a.length;u++){let l=a[u],m=this.item["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,value:l};for(let h of m.issues)h.path?h.path.unshift(d):h.path=[d],n.issues?.push(h);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else x(this,"type",n,o);return n}})}r(g,"array");function S(e){return A({kind:"schema",type:"boolean",reference:S,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:x(this,"type",t,n),t}})}r(S,"boolean");function Sn(e,t){return A({kind:"schema",type:"custom",reference:Sn,expects:"unknown",async:!1,check:e,message:t,"~run"(n,o){return this.check(n.value)?n.typed=!0:x(this,"type",n,o),n}})}r(Sn,"custom");function ze(e){return A({kind:"schema",type:"lazy",reference:ze,expects:"unknown",async:!1,getter:e,"~run"(t,n){return this.getter(t.value)["~run"](t,n)}})}r(ze,"lazy");function I(e,t){return A({kind:"schema",type:"literal",reference:I,expects:te(e),async:!1,literal:e,message:t,"~run"(n,o){return hn(n.value,this.literal)?n.typed=!0:x(this,"type",n,o),n}})}r(I,"literal");function Se(e,t){return A({kind:"schema",type:"loose_object",reference:Se,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=yt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(x(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}if(!n.issues||!o.abortEarly)for(let u in a)mt(a,u)&&!Object.prototype.hasOwnProperty.call(this.entries,u)&&(n.value[u]=a[u])}else x(this,"type",n,o);return n}})}r(Se,"looseObject");function Ye(e){return A({kind:"schema",type:"never",reference:Ye,expects:"never",async:!1,message:e,"~run"(t,n){return x(this,"type",t,n),t}})}r(Ye,"never");function O(e,t){return A({kind:"schema",type:"nullable",reference:O,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===null&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(O,"nullable");function N(e,t){return A({kind:"schema",type:"nullish",reference:N,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(N,"nullish");function E(e){return A({kind:"schema",type:"number",reference:E,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:x(this,"type",t,n),t}})}r(E,"number");function p(e,t){return A({kind:"schema",type:"object",reference:p,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=yt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(x(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}}else x(this,"type",n,o);return n}})}r(p,"object");function s(e,t){return A({kind:"schema",type:"optional",reference:s,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===void 0&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(s,"optional");function v(e,t){return A({kind:"schema",type:"picklist",reference:v,expects:Ke(e.map(te),"|"),async:!1,options:e,message:t,"~run"(n,o){return this.options.includes(n.value)?n.typed=!0:x(this,"type",n,o),n}})}r(v,"picklist");function b(e,t,n){return A({kind:"schema",type:"record",reference:b,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){o.typed=!0,o.value={};for(let l in u)if(mt(u,l)){let m=u[l],d=this.key["~run"]({value:l},a);if(d.issues){let f={type:"object",origin:"key",input:u,key:l,value:m};for(let T of d.issues)T.path=[f],o.issues?.push(T);if(o.issues||(o.issues=d.issues),a.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let f={type:"object",origin:"value",input:u,key:l,value:m};for(let T of h.issues)T.path?T.path.unshift(f):T.path=[f],o.issues?.push(T);if(o.issues||(o.issues=h.issues),a.abortEarly){o.typed=!1;break}}(!d.typed||!h.typed)&&(o.typed=!1),d.typed&&(o.value[d.value]=h.value)}}else x(this,"type",o,a);return o}})}r(b,"record");function i(e){return A({kind:"schema",type:"string",reference:i,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:x(this,"type",t,n),t}})}r(i,"string");function kn(e,t){return A({kind:"schema",type:"tuple",reference:kn,expects:"Array",async:!1,items:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<this.items.length;u++){let l=a[u],m=this.items[u]["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,value:l};for(let h of m.issues)h.path?h.path.unshift(d):h.path=[d],n.issues?.push(h);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else x(this,"type",n,o);return n}})}r(kn,"tuple");function ft(e){let t;if(e)for(let n of e)if(t)for(let o of n.issues)t.push(o);else t=n.issues;return t}r(ft,"_subIssues");function Y(e,t){return A({kind:"schema",type:"union",reference:Y,expects:Ke(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,o){let a,u,l;for(let m of this.options){let d=m["~run"]({value:n.value},o);if(d.typed)if(d.issues)u?u.push(d):u=[d];else{a=d;break}else l?l.push(d):l=[d]}if(a)return a;if(u){if(u.length===1)return u[0];x(this,"type",n,o,{issues:ft(u)}),n.typed=!0}else{if(l?.length===1)return l[0];x(this,"type",n,o,{issues:ft(l)})}return n}})}r(Y,"union");function w(){return A({kind:"schema",type:"unknown",reference:w,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}r(w,"unknown");function ie(e,t,n){return A({kind:"schema",type:"variant",reference:ie,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){let l,m=0,d=this.key,h=[],f=r((T,P)=>{for(let z of T.options){if(z.type==="variant")f(z,new Set(P).add(z.key));else{let J=!0,Q=0;for(let F of P){let pe=z.entries[F];if(F in u?pe["~run"]({typed:!1,value:u[F]},xn).issues:pe.type!=="exact_optional"&&pe.type!=="optional"&&pe.type!=="nullish"){J=!1,d!==F&&(m<Q||m===Q&&F in u&&!(d in u))&&(m=Q,d=F,h=[]),d===F&&h.push(z.entries[F].expects);break}Q++}if(J){let F=z["~run"]({value:u},a);(!l||!l.typed&&F.typed)&&(l=F)}}if(l&&!l.issues)break}},"parseOptions");if(f(this,new Set([this.key])),l)return l;x(this,"type",o,a,{input:u[d],expected:Ke(h,"|"),path:[{type:"object",origin:"value",input:u,key:d,value:u[d]}]})}else x(this,"type",o,a);return o}})}r(ie,"variant");function Xe(e,t,n){let o=e["~run"]({value:t},Ge(n));if(o.issues)throw new Oe(o.issues);return o.value}r(Xe,"parse");function c(...e){return A({...e[0],pipe:e,"~run"(t,n){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=o["~run"](t,n))}return t}})}r(c,"pipe");function M(e,t,n){let o=e["~run"]({value:t},Ge(n));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}r(M,"safeParse");var gt=p({role:v([Ce.USER,Ce.ASSISTANT,Ce.SYSTEM]),content:c(i(),y(1)),id:s(i()),createdAt:s(i())}),Ze=ze(()=>p({type:v(["string","number","boolean","array","object"]),description:s(i()),enum:s(g(i())),items:s(Ze),properties:s(b(i(),Ze)),required:s(g(i()))})),An=p({description:c(i(),y(1)),parameters:p({type:I("object"),properties:b(i(),Ze),required:s(g(i()))})}),Tn=p({id:i(),name:i(),args:b(i(),w())}),Rn=p({messages:c(g(gt),y(1)),provider:s(v([$.ANTHROPIC,$.OPENAI,$.GOOGLE])),model:s(i()),maxTokens:s(c(E(),q(),R(1))),temperature:s(c(E(),R(0),V(2))),systemPrompt:s(i()),stream:s(S()),tools:s(b(i(),An))}),In=p({promptTokens:E(),completionTokens:E(),totalTokens:E()}),yi=p({message:gt,usage:s(In),finishReason:s(i()),toolCalls:s(g(Tn))}),gi=p({provider:v([$.ANTHROPIC,$.OPENAI,$.GOOGLE]),model:s(i()),maxTokens:s(c(E(),q(),R(1))),temperature:s(c(E(),R(0),V(2))),systemPrompt:s(i())});function hi(e){return M(Rn,e)}r(hi,"validateAIChatRequest");var ht={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};var X={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};var Ai={FREE:"free",PRO:"pro",PREMIUM:"premium"};var vt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};var bt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function ke(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}r(ke,"picklistOptions");var Pi=p({id:i(),email:s(O(c(i(),B()))),displayName:s(O(i())),photoURL:s(O(c(i(),D()))),emailVerified:s(S()),lastLoginAt:s(i()),providerData:s(g(p({providerId:i(),uid:i(),email:s(O(c(i(),B()))),displayName:s(O(i())),photoURL:s(O(c(i(),D()))),phoneNumber:s(O(i()))}))),role:s(v(ke(X))),customClaims:s(b(i(),re()))}),me=p({tier:i(),status:i(),subscriptionEnd:O(c(i(),de())),updatedAt:c(i(),de()),isDefault:s(S()),features:s(g(i())),subscriptionId:s(O(i())),customerId:s(O(i())),cancelAtPeriodEnd:s(S())}),Di=p({...me.entries,userId:i(),isActive:s(S())}),_i=p({role:s(v(ke(X))),subscription:s(me),features:s(g(v(ke(vt)))),permissions:s(g(v(ke(bt)))),githubAccess:s(p({username:s(i()),teamAccess:s(g(i())),repoAccess:s(g(i()))}))});var Je={PAYMENT:"payment",SUBSCRIPTION:"subscription"};var Et=100,On=p({productId:c(i(),y(1),W(200)),quantity:c(E(),q(),R(1),V(1e4))}),eo=c(p({billingConfigKey:s(c(i(),y(1))),lineItems:s(c(g(On),y(1,"At least one line item is required"),W(Et,`At most ${Et} line items`))),successUrl:c(i(),D()),cancelUrl:c(i(),D()),customerEmail:s(c(i(),B())),metadata:s(b(i(),i())),allowPromotionCodes:s(S()),userId:s(i()),productId:s(i()),priceId:s(i()),currency:s(c(i(),fe(3,"Currency must be 3-letter ISO code"))),userEmail:s(c(i(),B())),mode:s(v([Je.PAYMENT,Je.SUBSCRIPTION]))}),He(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,a=o.billingConfigKey||o.metadata?.billingConfigKey;return a?{...o,billingConfigKey:a,lineItems:o.lineItems??[{productId:a,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),to=p({sessionId:i(),sessionUrl:O(c(i(),D()))}),Ae=c(i(),y(1),j(/\S/)),Pn=p({sessionId:Ae,billingConfigKey:Ae}),Dn=p({sessionId:Ae,orderId:Ae,billingConfigKey:Ae,sessionStatus:v(["open","complete","expired"]),paymentStatus:v(["paid","unpaid","no_payment_required"])});function no(e){return M(Pn,e)}r(no,"validateVerifyOrderCheckoutRequest");function ro(e){return M(Dn,e)}r(ro,"validateVerifyOrderCheckoutResult");var io=p({...me.entries,userId:i(),subscriptionId:O(i()),customerId:i(),cancelAtPeriodEnd:S()}),oo=p({id:i(),type:i(),data:p({object:re()}),created:c(i(),de())}),so=Se({userId:s(i()),firebaseUid:s(i()),productType:s(i())});var _n=p({type:I("StripePayment"),name:c(i(),y(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),fe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:s(c(i(),y(1,"Stripe price ID is required"))),tier:c(i(),y(1,"Tier is required")),duration:c(i(),y(1,"Duration is required")),allowPromotionCodes:s(S()),metadata:s(b(i(),i()))}),Fn=p({type:I("StripeSubscription"),name:c(i(),y(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),fe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:c(i(),y(1,"Stripe price ID is required")),tier:c(i(),y(1,"Tier is required")),duration:v(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:s(S()),metadata:s(b(i(),i()))}),Nn=ie("type",[_n,Fn]),ao=b(i(),Nn),uo=b(i(),p({name:i(),price:i(),currency:i(),description:s(i()),features:s(g(i())),priceId:s(i()),allowPromotionCodes:s(S())})),xt={name:i(),price:E(),currency:i(),priceId:s(i()),tier:i(),duration:i(),description:s(i()),metadata:s(b(i(),i())),allowPromotionCodes:s(S())},Un=ie("mode",[p({mode:I("manual"),taxRateIds:c(g(c(i(),y(1))),y(1))}),p({mode:I("automatic")})]),St=5,Mn=p({allowedCountries:c(g(c(i(),j(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),y(1)),shippingRateIds:s(c(g(c(i(),y(1))),W(St,`shippingRateIds: at most ${St} (Stripe limit)`)))}),Ln=p({type:I("StripeOrder"),name:i(),currency:c(i(),fe(3)),description:s(i()),metadata:s(b(i(),i())),allowPromotionCodes:s(S()),tax:Un,taxIdCollection:v(["disabled","optional","required"]),billingAddressCollection:v(["auto","required"]),shipping:s(Mn),customerCreation:v(["always","if_required"]),invoiceCreation:S(),paymentMethodConfiguration:s(c(i(),y(1)))}),Bn=b(i(),ie("type",[p({type:I("StripePayment"),...xt}),p({type:I("StripeSubscription"),...xt}),Ln]));function lo(e){return Xe(Bn,e)}r(lo,"validateStripeBackConfig");var bo={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},oe={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"};var G={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},kt=G.available,ye=Object.keys(G);function At(e){let t=ye.filter(n=>G[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}r(At,"onlyStatusThat");var Qe=At("isDefault"),et=At("isRemoved"),Vn=ye.filter(e=>G[e].read!=="guest"),Te=["id","createdAt","updatedAt","createdById","updatedById"],se={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"};var Tt=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var ko={EQ:se.EQ,NEQ:se.NEQ,LT:se.LT,LTE:se.LTE,GT:se.GT,GTE:se.GTE};var Rt=class extends Error{static{r(this,"BulkCollisionError")}collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}};var Po=p({collection:c(i(),y(1,"Collection name is required")),data:b(i(),w()),idempotencyKey:s(i())}),Do=p({collection:c(i(),y(1,"Collection name is required")),id:c(i(),y(1,"Entity ID is required"))}),_o=p({collection:c(i(),y(1,"Collection name is required")),id:c(i(),y(1,"Entity ID is required")),data:b(i(),w()),merge:s(S(),!1)}),Fo=p({collection:c(i(),y(1,"Collection name is required")),id:c(i(),y(1,"Entity ID is required"))}),No=p({collection:c(i(),y(1,"Collection name is required")),limit:s(c(E(),R(1),V(1e3)),1e3),offset:s(c(E(),R(0)),0),orderBy:s(i()),orderDirection:s(v(["asc","desc"]),"desc"),where:s(g(p({field:i(),operator:v(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:w()})))});var $n=p({templateId:c(i(),y(1)),to:c(i(),B()),data:b(i(),w()),locale:s(c(i(),y(2),W(5)),"fr"),from:s(i()),replyTo:s(i())}),zo=p({success:S(),messageId:s(i()),error:s(i())});function Yo(e){return M($n,e)}r(Yo,"validateSendEmailRequest");var It=["pull","push","admin","maintain","triage"];var tt=p({owner:c(i(),y(1,"Repository owner is required")),repo:c(i(),y(1,"Repository name is required"))}),qn=v([...It]),Fs=p({userId:c(i(),y(1,"User ID is required")),githubUsername:c(i(),y(1,"GitHub username is required")),repoConfig:tt,permission:s(qn,"push"),customClaims:s(b(i(),re()))}),Ns=p({userId:c(i(),y(1,"User ID is required")),githubUsername:c(i(),y(1,"GitHub username is required")),repoConfig:tt}),Us=p({userId:c(i(),y(1,"User ID is required")),githubUsername:c(i(),y(1,"GitHub username is required")),repoConfig:tt}),Ms=p({provider:i(),purpose:v(["authentication","api-access"]),code:c(i(),y(1,"Authorization code is required")),redirectUri:c(i(),D("Valid redirect URI is required")),codeVerifier:s(i()),state:s(i()),instance:s(c(i(),D()))}),Ls=p({provider:i(),refreshToken:c(i(),y(1,"Refresh token is required")),redirectUri:c(i(),D("Valid redirect URI is required"))}),Bs=p({provider:i()}),Vs=p({userId:c(i(),y(1,"User ID is required"))});var Ct=p({name:i(),color:i(),icon:i(),customParameters:s(b(i(),i())),button:p({backgroundColor:i(),textColor:i(),borderColor:i(),hoverBackgroundColor:i(),focusOutlineColor:i(),fontWeight:s(i(),"500"),textKey:s(i())})}),Wn=p({...Ct.entries,type:v(["auth","both"]),scopes:s(g(i())),firebaseProviderId:s(i())}),Pe=Y([I(""),c(i(),D())]),Gn=p({authUrl:Pe,tokenUrl:Pe,profileUrl:Pe,revokeUrl:s(Pe)}),Kn=p({authentication:s(g(i())),"api-access":g(i())}),Hn=s(p({pkce:s(S(),!1),codeChallengeMethod:s(v(["S256","plain"]),"S256")})),zn=p({...Ct.entries,type:v(["oauth","both"]),scopes:Kn,endpoints:Gn,capabilities:Hn});var Hs={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"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},zs=b(i(),Wn),Ys=b(i(),zn);var wt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"};var sa={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:wt.ANALYTICS},marketing:{requiresConsent:wt.MARKETING}};function Ot(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"}r(Ot,"detectErrorSource");function K(e){return(t,n)=>{if(t instanceof k)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new k(n||m,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 a=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(a=e.errorCodeMapping[o]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[o]),u||(u=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new k(n||u,a,{details:l,source:e.errorSource})}}r(K,"createErrorHandler");var De={"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 ge={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Yn={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"},nt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function Xn(e){return e in nt}r(Xn,"isEntityHookErrorType");var Z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...De},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",...De},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(Yn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:r(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()},"extractErrorCode"),processMetadata:r(e=>{let t={originalError:e};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:De,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ge.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:r(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ge["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ge.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:r(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},Zn=r(e=>e instanceof Oe?new k(ge["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):K(Z.validation)(e),"handleValidationError"),Jn=r(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&Xn(e.type)){let t=nt[e.type]||"unknown";return new k(e.message||ge[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&We[e.code]){let t=We[e.code];if(t){let n=nt[t.type]||"unknown";return new k(t.message||ge[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return K(Z.entity)(e)},"handleEntityError"),Pt={auth:K(Z.auth),oauth:K(Z.oauth),api:K(Z.api),firebase:K(Z.firebase),ui:K(Z.ui),validation:Zn,entity:Jn,unknown:K(Z.unknown)};function _e(e,t,n){return e instanceof k?e:(Pt[t]||Pt.unknown)(e,n)}r(_e,"mapToDoNotDevError");function Dt(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,l])=>{if(typeof l!="function"&&u!=="originalError")try{a.setExtra(u,l)}catch{a.setExtra(u,`[${typeof l}]`)}}),Object.entries(n).forEach(([u,l])=>{if(typeof l!="function")try{a.setExtra(`context.${u}`,l)}catch{a.setExtra(`context.${u}`,`[${typeof l}]`)}}),(e.details?.userId||n.userId)&&a.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}r(Dt,"captureErrorToSentry");function Qn(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}r(Qn,"isDev");function Fe(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:a={},log:u=!0,reportToSentry:l=!0,showNotification:m=!1,severity:d="error"}=n,h=Ot(e),f=e instanceof k?e:_e(e,h,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new k(o,f.code,{details:{...f.details,originalMessage:f.message},source:h,userMessageProvided:!0}):f=new k(f.message,f.code,{details:{...f.details,userMessage:o},source:h,userMessageProvided:!0})),u){let T=Qn()||typeof window<"u"&&window.__DNDEV_DEBUG,P={code:f.code,message:f.message,source:h};switch(d){case"warning":console.warn(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details}:P);break;case"info":console.info(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details}:P);break;case"success":console.log(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details}:P);break;default:console.error(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details,stack:f.stack}:P)}}return l&&Dt(f,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),f}r(Fe,"handleError");function cu(e,t,n,o){let a=o?` ${JSON.stringify(o)}`:"",u=`${t}.${n}(${a})`,l=_e(e,"auth",`${u}: ${er(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&l.code==="unknown"&&e.code!=="unknown"?new k(l.message,l.code,{details:{...l.details,originalCode:e.code},source:l.source}):l}r(cu,"wrapAuthError");function er(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}r(er,"getErrorMessage");var _t={[X.GUEST]:0,[X.USER]:1,[X.ADMIN]:2,[X.SUPER]:3};function ae(e,t){if(!e)return!1;let n=_t[e]??-1,o=_t[t]??1/0;return n>=o}r(ae,"hasRoleAccess");var Ft="__DNDEV_SINGLETONS__";function tr(){if(typeof globalThis<"u"){let e=globalThis,t=e[Ft];if(t)return t;let n=new Map;return e[Ft]=n,n}return new Map}r(tr,"getSingletonRegistry");function rt(e,t){let n=tr();return n.has(e)||n.set(e,t()),n.get(e)}r(rt,"getGlobalSingleton");function gu(e,...t){let n=null,o=!1;return r(function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}},"getInstance")}r(gu,"createSingleton");function Nt(){return rt("providers",()=>({providers:null}))}r(Nt,"getProviderState");function Eu(e){let{providers:t}=Nt();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}r(Eu,"getProvider");function xu(e){return!!Nt().providers?.[e]}r(xu,"hasProvider");function nr(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}r(nr,"hasVisibility");function rr(e){if(nr(e))return e.visibility}r(rr,"getFieldVisibility");function ir(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?ae(t,"admin"):n==="owner"?!1:ae(t,n)}r(ir,"isFieldVisible");function or(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}r(or,"isOwnerVisible");function Ut(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let o=e.entries,a=[],{documentData:u,uid:l,ownership:m}=n??{},d=m&&l!=null&&u&&or(u,l,m);for(let[h,f]of Object.entries(o)){let T=rr(f);if(T==="owner"){d&&a.push(h);continue}ir(T,t)&&a.push(h)}return a}r(Ut,"getVisibleFields");function Cu(e,t,n,o){if(!e)return{};let a=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,u=Ut(t,n,a),l={};for(let m of u)Object.prototype.hasOwnProperty.call(e,m)&&(l[m]=e[m]);return l}r(Cu,"filterVisibleFields");function it(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}r(it,"getListCardFieldNames");var sr=new Set(["http:","https:","mailto:","tel:","blob:"]);function _u(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(sr.has(n.protocol))return t}catch{return t}return""}r(_u,"sanitizeHref");var Mt=ye.map(e=>({value:e,label:`crud:status.${e}`}));var Mu=[...Te,"status"];function Lt(e){return Te.some(t=>t===e)}r(Lt,"isBackendGeneratedField");var Ne={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Mt]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var ot=["text","textarea","richtext","field-array"];function Ue(e){return`${e}I18n`}r(Ue,"i18nFieldName");function Me(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}r(Me,"addMonths");function Bt(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}r(Bt,"addYears");function wc(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=Me(t,1):e==="3months"?n=Me(t,3):e==="6months"?n=Me(t,6):e==="1year"?n=Bt(t,1):e==="2years"?n=Bt(t,2):n=Me(t,1),n.toISOString()}r(wc,"calculateSubscriptionEndDate");function L(e){let t=e?.status;return typeof t=="string"?t:null}r(L,"statusOf");function Be({op:e,status:t,storedStatus:n}){return Le(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}r(Be,"writeSchemaFor");function Vt({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let o=t??n;return o==null||o===n?!1:Le(n,"holdIncomplete")&&!Le(o,"holdIncomplete")}r(Vt,"entersVisibleStatus");function jt(e){return e!=null&&Object.hasOwn(G,e)?G[e]:kt}r(jt,"statusRow");function Le(e,t){return jt(e)[t]}r(Le,"statusCan");function Ve(e,t){let n=jt(e).read;return n==="guest"||ae(t,n)}r(Ve,"statusReadableBy");function st(e){return Object.keys(G).filter(t=>G[t][e])}r(st,"statusesThat");var je=r(e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(y(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(W(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(j(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?c(i(),...t):i()},"textValue"),ur=r(()=>c(i(),B("Invalid email address")),"emailValue"),lr=r(e=>e.validation?.minLength!==void 0?c(i(),y(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):i(),"passwordValue"),cr=r(()=>c(i(),D("Invalid URL")),"urlValue"),he=r(e=>{let t=[];return e.validation?.min!==void 0&&t.push(R(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(V(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?c(E(),...t):E()},"numberValue"),$t=r(()=>S(),"booleanValue"),at=r(()=>c(i(),ne(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),"dateValue"),pr=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,dr=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,fr=/^\d{4}-(?:0[1-9]|1[0-2])$/,mr=r(()=>c(i(),j(pr,"Invalid time format")),"timeValue"),yr=r(()=>c(i(),j(dr,"Invalid week format")),"weekValue"),gr=r(()=>c(i(),j(fr,"Invalid month format")),"monthValue"),Zt=p({url:i(),filename:i(),size:E(),mimeType:N(i()),uploadedAt:N(i())}),qt=r(()=>Zt,"fileValue"),Wt=r(()=>g(Zt),"filesValue"),Jt=p({fullUrl:i(),thumbUrl:i()}),hr=r(()=>Y([i(),Jt]),"pictureValue"),vr=r(()=>g(Y([i(),Jt])),"picturesValue"),br=r(()=>p({lat:E(),lng:E()}),"geopointValue"),Er=r(()=>p({formatted_address:i(),latitude:E(),longitude:E(),street_number:N(i()),route:N(i()),locality:N(i()),administrative_area_level_1:N(i()),administrative_area_level_2:N(i()),country:N(i()),postal_code:N(i())}),"addressValue"),xr=r(()=>b(i(),w()),"mapValue"),Sr=r(()=>g(w()),"arrayValue"),kr=r(()=>g(b(i(),w())),"fieldArrayValue"),ut=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?v(t.map(n=>n.value)):Y([i(),E()])},"selectValue"),Ar=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?g(v(t.map(n=>n.value))):g(i())},"multiselectValue"),Qt=r(()=>c(i(),y(1,"Invalid ID format")),"referenceValue"),lt=r(()=>i(),"stringValue"),Tr=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,Rr=r(e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Tr;return c(i(),j(t,"Invalid phone number"))},"telValue"),Ir=r(e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return c(i(),y(t,`IBAN must be at least ${t} characters`),W(n,`IBAN must not exceed ${n} characters`),j(new RegExp(o),"Invalid IBAN format"))},"ibanValue"),Gt=r(()=>Ye(),"neverValue");function en(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}r(en,"stringSwitchValues");var Cr=r(e=>{let t=en(e);return t?v(t):S()},"switchValue"),Kt=Se({gdprConsent:I(!0),gdprConsentDate:s(i()),gdprConsentVersion:s(i())},"GDPR consent must be given"),wr=r(e=>e.validation?.required?Kt:Y([I(!1),Kt]),"gdprConsentValue"),Or=r(()=>p({amount:E(),currency:s(i()),vatIncluded:s(S()),discountPercent:s(c(E(),R(0),V(100)))}),"priceValue"),tn={text:{schema:je,kind:"text"},textarea:{schema:je,kind:"text"},richtext:{schema:je,kind:"text"},color:{schema:je,kind:"text"},email:{schema:ur,kind:"text"},password:{schema:lr,kind:"text"},url:{schema:cr,kind:"text"},tel:{schema:Rr,kind:"text"},iban:{schema:Ir,kind:"text"},number:{schema:he,kind:"number"},currency:{schema:he,kind:"number"},range:{schema:he,kind:"number"},year:{schema:he,kind:"number"},rating:{schema:he,kind:"number"},duration:{schema:he,kind:"number"},price:{schema:Or,kind:"json"},boolean:{schema:$t,kind:"boolean"},checkbox:{schema:$t,kind:"boolean"},switch:{schema:Cr,kind:r(e=>en(e)?"text":"boolean","kind")},gdprConsent:{schema:wr,kind:"json"},date:{schema:at,kind:"date"},"datetime-local":{schema:at,kind:"timestamp"},timestamp:{schema:at,kind:"timestamp"},time:{schema:mr,kind:"time"},week:{schema:yr,kind:"text"},month:{schema:gr,kind:"text"},file:{schema:qt,kind:"json"},files:{schema:Wt,kind:"json"},document:{schema:qt,kind:"json"},documents:{schema:Wt,kind:"json"},image:{schema:hr,kind:"json"},images:{schema:vr,kind:"json"},geopoint:{schema:br,kind:"json"},address:{schema:Er,kind:"json"},map:{schema:xr,kind:"json"},array:{schema:Sr,kind:"json"},"field-array":{schema:kr,kind:"json"},select:{schema:ut,kind:"text"},radio:{schema:ut,kind:"text"},combobox:{schema:ut,kind:"text"},multiselect:{schema:Ar,kind:"json"},reference:{schema:Qt,kind:"ref"},hidden:{schema:lt,kind:"text"},avatar:{schema:lt,kind:"text"},badge:{schema:lt,kind:"text"},submit:{schema:Gt,kind:"text"},reset:{schema:Gt,kind:"text"}},Pr=new Set(Tt);function Dr(e){return Pr.has(e)}r(Dr,"isBuiltInFieldType");var _r=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),Fr=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),Nr=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),Ur={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function H(e,t){return t in e?Reflect.get(e,t):void 0}r(H,"prop");function Ht(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}r(Ht,"kindOfScalar");function zt(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}r(zt,"commonKind");function $e(e){if(typeof e!="object"||e===null)return;let t=H(e,"type");if(typeof t!="string")return;let n=Mr(e,t),o=H(e,"pipe");if(Array.isArray(o))for(let a of o.slice(1)){if(typeof a!="object"||a===null)continue;let u=H(a,"kind"),l=H(a,"type");if(typeof l=="string"){if(u==="schema")n=$e(a);else if(u==="transformation")Nr.has(l)||(n=void 0);else if(u==="validation"){l==="integer"&&n==="number"&&(n="integer");let m=Ur[l];m&&n==="text"&&(n=m)}}}return n}r($e,"kindOfSchema");function Mr(e,t){if(_r.has(t))return $e(H(e,"wrapped"));if(Fr.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return Ht(H(e,"literal"));case"picklist":case"enum":{let n=H(e,"options");return Array.isArray(n)?zt(n.map(Ht)):void 0}case"union":case"variant":{let n=H(e,"options");if(!Array.isArray(n))return;let o=n.filter(a=>{let u=typeof a=="object"&&a!==null?H(a,"type"):void 0;return u!=="null"&&u!=="undefined"});return zt(o.map($e))}default:return}}r(Mr,"kindOfRoot");function Yt(e,t){let{kind:n}=tn[e];return typeof n=="function"?n(t):n}r(Yt,"builtinKind");function ct(e,t=e.name){let n=e.validation?.reference,o=n?{ref:n}:{},a=e.type,u=Dr(a)?a:void 0,l=e.validation?.schema;if(l){let m=(n?"ref":void 0)??$e(l)??(u?Yt(u,e):void 0);if(!m)throw new Error(`Field '${t}' (custom type '${a}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:l,kind:m,...o}}if(n)return{schema:Qt(),kind:"ref",...o};if(u)return{schema:tn[u].schema(e),kind:Yt(u,e)};throw new Error(`Field '${t}' has custom type '${a}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}r(ct,"resolveFieldValue");function Lr(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}r(Lr,"requirementOf");function Br(e,t){return t.visibility==="hidden"||t.editable===oe.GENERATED||Lt(e)?"never":t.editable===oe.FALSE?"program":t.editable===oe.COMPUTED?"derived":"user"}r(Br,"writeClassOf");function Vr(e,t){return(n,o)=>{if(t!=="user")return!1;let a=e.editable;return a===void 0||a===oe.TRUE?e.visibility!=="technical":a===oe.CREATE_ONLY?o==="create":typeof a=="string"?ae(n,a):!1}}r(Vr,"editableForOf");function jr(e,t,n){let o=Br(e,t);return{value:ct(t,`${n}.${e}`),required:Lr(t),write:o,editableFor:Vr(t,o),visibleAt:t.visibility,...t.i18n===!0&&{companion:Ue(e)}}}r(jr,"describeField");var Xt=new WeakMap;function pt(e){let t=Xt.get(e);if(t)return t;let n={};for(let[a,u]of Object.entries(e.fields))n[a]=jr(a,u,e.name);let o={name:e.name,collection:e.collection,fields:n};return Xt.set(e,o),o}r(pt,"describeEntity");function $r(e,t){return t?c(e,ne(n=>n!=="","Required")):N(e)}r($r,"applyRequired");function ue(e){return $r(ct(e).schema,e.validation?.required)}r(ue,"getSchemaType");function ce(e,t){return Object.assign(e,{visibility:t})}r(ce,"withVisibility");function le(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}r(le,"withMetadata");function qr(e){let t=ue(e);return ce(t,e.visibility)}r(qr,"createFieldSchema");function Wr(e,t){if(!ot.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${ot.join(", ")}.`);let n=ue({...t,validation:{...t.validation,required:!1}});return ce(s(O(b(i(),n))),t.visibility)}r(Wr,"createTranslationsSchema");function ve(e,t){for(let n of Object.keys(e)){let o=t[n];o?.i18n===!0&&(e[Ue(n)]=Wr(n,o))}return e}r(ve,"withTranslations");function dt(e){let t=ue({...e,validation:{...e.validation,required:!1}});return ce(t,e.visibility)}r(dt,"createOptionalFieldSchema");function Gr(e){return e.validation?.required?ce(s(ue(e)),e.visibility):dt(e)}r(Gr,"createUpdateFieldSchema");function rp(e){let t=e.fields,n=pt(e).fields,o=r(C=>n[C]?.write==="never","isWriteExcluded"),a={};for(let[C,U]of Object.entries(t))n[C]?.visibleAt!=="hidden"&&(a[C]=dt(U));let u=le(p(ve({...a},t)),e),l={};for(let[C,U]of Object.entries(t))o(C)||(l[C]=qr(U));let m=le(p(ve({...l},t)),e),d={};for(let[C,U]of Object.entries(t))if(!o(C))if(C==="status"){let ee=v(st("saveIncomplete"));d[C]=ce(ee,U.visibility)}else d[C]=dt(U);let h=le(p(ve({...d},t)),e),f={};for(let[C,U]of Object.entries(t))o(C)||(f[C]=Gr(U));f.id=ce(ue(Ne.id),"technical");let T=le(p(ve({...f},t)),e),P;if(e.listFields&&e.listFields.length>0){let C=["id","status"],U=[...new Set([...C,...e.listFields])];P={};for(let ee of U){let be=a[ee];be&&(P[ee]=be)}}else P=a;let z=le(p(ve({...P},t)),e),J,Q=it(e);if(Q.length>0){let C=["id","status"],U=[...new Set([...C,...Q])];J={};for(let ee of U){let be=a[ee];be&&(J[ee]=be)}}else J=a;let F=le(p(ve({...J},t)),e),pe=le(p({id:ce(ue(Ne.id),"technical")}),e);return{create:m,draft:h,update:T,get:u,list:z,listCard:F,delete:pe}}r(rp,"createSchemas");var Kr=b(i(),w()),Hr=p({id:i(),patch:b(i(),w())}),zr=i(),sp=p({inserts:s(g(Kr)),updates:s(g(Hr)),deletes:s(g(zr))}),Yr=p({insertedIds:g(i()),updatedIds:g(i()),deletedIds:g(i())}),Xr=ie("op",[p({op:I("insert"),index:c(E(),q(),R(0)),id:s(i()),error:i()}),p({op:I("update"),id:i(),index:s(c(E(),q(),R(0))),error:i()}),p({op:I("delete"),id:i(),index:s(c(E(),q(),R(0))),error:i()})]),ap=p({...Yr.entries,failed:s(g(Xr),()=>[])});function up(e){let t=new Set((e.updates??[]).map(l=>l.id)),n=e.deletes??[],o=[];for(let l of n)t.has(l)&&o.push(l);if(o.length>0)return{collisions:o,where:"updates-deletes"};let a=e.inserts??[],u=[];for(let l of a)typeof l.id=="string"&&t.has(l.id)&&u.push(l.id);return u.length>0?{collisions:u,where:"inserts-updates"}:{collisions:[],where:null}}r(up,"detectBulkCollisions");function nn(e){let t=e.entries;if(!t||typeof t!="object")throw new k("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}r(nn,"schemaKeys");function qe(e,t){let n=[e.create,e.draft,e.update].filter(a=>a!==void 0);if(n.some(a=>a.type==="loose_object"))return[];let o=new Set([...n.flatMap(nn),...Te]);return Object.keys(t).filter(a=>!o.has(a))}r(qe,"unknownKeysOf");function rn(e,t){let n={};for(let o of nn(t))n[o]=null;for(let[o,a]of Object.entries(e))a!==void 0&&(n[o]=a);return n}r(rn,"wholeRecord");function Re(e,t,n,o,a){let u=M(t,n);if(!u.success)return{ok:!1,schemaKey:e,issues:[...u.issues],unknownKeys:a};let l=u.output,m={};for(let d of Object.keys(o))d!=="id"&&Object.hasOwn(l,d)&&(m[d]=l[d]);return{ok:!0,schemaKey:e,written:m,unknownKeys:a}}r(Re,"parseWritten");function on(e){return L(e)??Qe}r(on,"createStatus");function Zr(e,t){let n=on(t),o=Be({op:"create",status:n}),a={...t,status:n},u=Re(o,o==="draft"?e.draft:e.create,a,a,qe(e,t));return u.ok?{...u,written:{...u.written,status:n}}:u}r(Zr,"prepareCreate");function sn(e){return L(e)!==et}r(sn,"updateNeedsStored");function an(e,t){let n={op:"update",status:L(e),storedStatus:L(t)};return{schemaKey:Be(n)==="draft"?"draft":"update",whole:Vt(n)}}r(an,"updateCheck");function un(e,{id:t,patch:n,stored:o}){let a=L(n);if(!o&&sn(n))throw new k(`CRUD update rules: row "${t}" needs its stored row (the row's status${a===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:u,whole:l}=an(n,o),m=qe(e,n);if(o&&l)return Re(u,e.update,rn({...o,...n,id:t},e.update),n,m);let d=u==="draft"?{...n,status:L(n)??L(o),id:t}:{...n,id:t};return Re(u,u==="draft"?e.draft:e.update,d,n,m)}r(un,"prepareUpdate");function Jr(e,t){return un(e,{id:t,patch:{status:et}})}r(Jr,"prepareRemove");function Qr(e){return ye.filter(t=>!Ve(t,e))}r(Qr,"hiddenStatusesFor");function ei(e,t){return Ve(L(e),t)}r(ei,"isReadableBy");var Ed=c(i(),ne(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),ti=v(["ephemeral","session","persistent"]),ni=p({title:s(i()),pinnable:s(S()),preferredHeight:s(c(E(),R(0)))}),xd=p({id:c(i(),y(1)),kind:c(i(),y(1)),lifetime:s(ti,"ephemeral"),metadata:s(ni),payload:w()}),Sd=p({widgetId:c(i(),y(1)),action:c(i(),y(1)),payload:w()});export{oi as a,si as b,ai as c,ui as d,ci as e,fe as f,V as g,y as h,R as i,j,En as k,D as l,re as m,g as n,S as o,Sn as p,Se as q,O as r,E as s,p as t,s as u,v,b as w,i as x,kn as y,Y as z,w as A,Xe as B,c as C,M as D,Rn as E,hi as F,ht as G,Ai as H,me as I,eo as J,no as K,ro as L,lo as M,bo as N,Vn as O,Rt as P,$n as Q,Yo as R,k as S,Fs as T,Ns as U,Us as V,Ms as W,Hs as X,Fe as Y,cu as Z,ae as _,gu as $,Eu as aa,xu as ba,ir as ca,Cu as da,it as ea,_u as fa,wc as ga,L as ha,Le as ia,rp as ja,sp as ka,Yr as la,up as ma,on as na,Zr as oa,an as pa,un as qa,Jr as ra,Qr as sa,ei as ta};
|
|
22
|
-
//# sourceMappingURL=chunk-ICNQCRLV.js.map
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
4
|
-
import { Buffer } from 'node:buffer';
|
|
5
|
-
import process from 'node:process';
|
|
6
|
-
|
|
7
|
-
const require = __createRequire(import.meta.url);
|
|
8
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
-
const __dirname = dirname(__filename);
|
|
10
|
-
|
|
11
|
-
if (typeof globalThis !== 'undefined') {
|
|
12
|
-
globalThis.require = require;
|
|
13
|
-
globalThis.__filename = __filename;
|
|
14
|
-
globalThis.__dirname = __dirname;
|
|
15
|
-
globalThis.Buffer = Buffer;
|
|
16
|
-
globalThis.process = process;
|
|
17
|
-
if (typeof global === 'undefined') {
|
|
18
|
-
globalThis.global = globalThis;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
import{k as Q}from"./chunk-7ODXXXES.js";import{D as $,K as U,L as M,P as V,R as _,S as p,_ as S,ia as N,ka as L,la as z,ma as F,na as W,oa as Y,pa as J,qa as G}from"./chunk-ICNQCRLV.js";import{a as H}from"./chunk-W6W4L44F.js";import{a as l}from"./chunk-AYY7UXNI.js";function oe(t){let e=new Date().toISOString();return{createdAt:e,updatedAt:e,createdById:t,updatedById:t}}l(oe,"createMetadata");function se(t){return{updatedAt:new Date().toISOString(),updatedById:t}}l(se,"updateMetadata");function P(t,e,d){if(t.unknownKeys.length>0&&console.warn(`[dndev] ${e} ${d}: fields the entity does not have, not written: ${t.unknownKeys.join(", ")}`),t.ok)return t.written;let s=t.issues.map(u=>`${u.path?.map(o=>String(o.key)).join(".")||"root"}: ${u.message}`).join("; ");throw new p(`Validation failed on ${e} ${d}: ${s}`,"invalid-argument",{details:{validationErrors:t.issues}})}l(P,"writtenOf");var ee=Object.freeze({insertedIds:[],updatedIds:[],deletedIds:[]});async function fe(t){let{collection:e,ops:d,createSchema:s,draftCreateSchema:u,updateSchema:o,access:n,uid:m,userRole:a,transact:c,readStored:w,mintInsertId:B,stampInsertMetadata:b,stampUpdateMetadata:O,audit:x}=t,y=$(L,d);if(!y.success){let r=y.issues.map(i=>`${i.path?.map(g=>g.key).join(".")||"root"}: ${i.message}`).join("; ");throw new p(`Bulk payload validation failed: ${r}`,"invalid-argument",{details:{validationErrors:y.issues}})}let R=y.output,v=R.inserts??[],f=R.updates??[],I=R.deletes??[],E=F(R);if(E.where!==null)throw new V(E.collisions,E.where);if(v.length===0&&f.length===0&&I.length===0)return ee;if(v.length>0){if(!n.create)throw new p(`Bulk insert requested on ${e} but no create role is configured`,"permission-denied");if(!S(a,n.create))throw new p(`Access denied for bulk insert on ${e}. Required: ${n.create}, your role: ${a}`,"permission-denied")}if(f.length>0){if(!n.update)throw new p(`Bulk update requested on ${e} but no update role is configured`,"permission-denied");if(!S(a,n.update))throw new p(`Access denied for bulk update on ${e}. Required: ${n.update}, your role: ${a}`,"permission-denied")}if(I.length>0){if(!n.delete)throw new p(`Bulk delete requested on ${e} but no delete role is configured`,"permission-denied");if(!S(a,n.delete))throw new p(`Access denied for bulk delete on ${e}. Required: ${n.delete}, your role: ${a}`,"permission-denied")}let A=l(r=>{throw new p(`Validation failed on ${r}: draft row sent to ${e} but no draft schema is configured`,"invalid-argument")},"noDraftSchema"),j={create:s,draft:u??s,update:o},q=[];for(let r=0;r<v.length;r++){let i=v[r];!u&&N(W(i),"saveIncomplete")&&A(`inserts[${r}]`);let g=P(Y(j,i),e,`inserts[${r}]`);q.push({row:g,id:typeof i.id=="string"?i.id:null})}if(f.length>0&&!w)throw new p(`Bulk update requested on ${e} but no readStored is configured: the stored row decides each patch's rules`,"internal");let X=f.length>0&&w?await w(f.map(r=>r.id)):new Map,C=[];for(let r=0;r<f.length;r++){let{id:i,patch:g}=f[r],h=`updates[${r}]`,k=X.get(i);if(!k)throw new p(`Document not found on ${h}: ${e}/${i}`,"not-found");!u&&J(g,k).schemaKey==="draft"&&A(h),C.push(P(G(j,{id:i,patch:g,stored:k}),e,h))}let D=q.map(({row:r,id:i})=>{let g=B?B():i??"",h=!B&&i!==null?{...r,id:i}:r,k=b?b(h,m):h;return{id:g,row:k}}),K=f.map((r,i)=>({id:r.id,patch:O?O(C[i],m):C[i]})),Z=await c({inserts:D,updates:K,deletes:[...I]}),T=$(z,Z);if(!T.success)throw new p(`Bulk transact() returned an unexpected shape for ${e}`,"internal");return x&&x(`crud.bulk.${e}`,{counts:{inserts:D.length,updates:K.length,deletes:I.length}}),T.output}l(fe,"executeBulk");async function Re(t,e){let d="validation",s="invalid";try{let u=U(t);if(!u.success)throw new Error;let o=u.output,{userId:n,billingConfig:m}=e;if(d="auth",s="rejected",typeof n!="string"||!n.trim())throw new Error;if(d="config",s="invalid",!Object.hasOwn(m,o.billingConfigKey)||m[o.billingConfigKey]?.type!=="StripeOrder")throw new Error;d="binding",s="unavailable";let a=await e.resolveOrderBinding({...o,userId:n});if(s="rejected",!a||a.userId!==n||a.sessionId!==o.sessionId||a.billingConfigKey!==o.billingConfigKey||typeof a.orderId!="string"||!a.orderId.trim())throw new Error;d="provider",s="unavailable";let c=await e.retrieveStripeSession(o.sessionId);if(d="response",s="rejected",c.id!==o.sessionId||c.mode!=="payment"||c.metadata?.userId!==n||c.metadata?.billingConfigKey!==o.billingConfigKey||c.metadata?.[Q]!==a.orderId)throw new Error;s="invalid";let w=M({sessionId:c.id,orderId:a.orderId,billingConfigKey:o.billingConfigKey,sessionStatus:c.status,paymentStatus:c.payment_status});if(!w.success)throw new Error;return w.output}catch{try{await H.warn("[Checkout verification] Failed",{stage:d,category:s})}catch{}throw new Error("Checkout verification denied")}}l(Re,"verifyOrderCheckoutAlgorithm");async function te(t,e,d){let s=_(t);if(!s.success)return{success:!1,error:`Invalid email request: ${s.issues?.map(c=>c.message).join(", ")}`};let u=e.templates[t.templateId];if(!u)return{success:!1,error:`Template not found: ${t.templateId}`};let o=t.locale||"fr",n=u.subject(t.data,o),m=u.html(t.data,o);return{success:!0,messageId:(await d.send({from:t.from||e.defaultFrom,to:t.to,subject:n,html:m,replyTo:t.replyTo||e.replyTo})).messageId}}l(te,"handleEmailRequest");var re="https://api.resend.com/emails";function ne(t){if(!t)throw new Error("Resend API key is required");return{async send({from:e,to:d,subject:s,html:u,replyTo:o}){let n={from:e,to:d,subject:s,html:u};o&&(n.reply_to=o);let m=await fetch(re,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!m.ok){let c=await m.text().catch(()=>"Unknown error");throw new Error(`Resend API error (${m.status}): ${c}`)}return{messageId:(await m.json()).id}}}}l(ne,"createResendProvider");export{oe as a,se as b,P as c,fe as d,Re as e,te as f,ne as g};
|
|
22
|
-
//# sourceMappingURL=chunk-PDBNKSBQ.js.map
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
4
|
-
import { Buffer } from 'node:buffer';
|
|
5
|
-
import process from 'node:process';
|
|
6
|
-
|
|
7
|
-
const require = __createRequire(import.meta.url);
|
|
8
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
-
const __dirname = dirname(__filename);
|
|
10
|
-
|
|
11
|
-
if (typeof globalThis !== 'undefined') {
|
|
12
|
-
globalThis.require = require;
|
|
13
|
-
globalThis.__filename = __filename;
|
|
14
|
-
globalThis.__dirname = __dirname;
|
|
15
|
-
globalThis.Buffer = Buffer;
|
|
16
|
-
globalThis.process = process;
|
|
17
|
-
if (typeof global === 'undefined') {
|
|
18
|
-
globalThis.global = globalThis;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
import{a as h,t as w,u as E,v as A,w as g}from"./chunk-7ODXXXES.js";import{C as B,D as y,S as I,aa as T,ba as R,k as x,p as b,s as S,t as O,u as l,v,x as P,z as M}from"./chunk-ICNQCRLV.js";import{a as n}from"./chunk-AYY7UXNI.js";var N=v(["firebase","supabase"]);function Y(e){let t=y(N,e);if(!t.success){let s=N.options.map(r=>`'${r}'`).join(", ");throw new I(`Invalid backend ${JSON.stringify(e)}: expected one of ${s}`,"invalid-argument")}return t.output}n(Y,"parseAuthBackend");async function k(){let{getFirebaseAdminAuth:e}=await import("./server-24XGDDO3.js");return e()}n(k,"getFirebaseAuth");function C(e){if(!e||typeof e!="string")throw new Error("Authentication required");return e}n(C,"assertAuthenticated");async function z(e){C(e);try{let t={};R("serverAuth")?t=(await T("serverAuth").getUser(e))?.customClaims??{}:t=(await(await k()).getUser(e)).customClaims??{};let s=t.role;if(!(s==="admin"||s==="super"||t.isAdmin===!0||t.isSuper===!0))throw new Error("Admin privileges required");return e}catch(t){throw t instanceof Error&&t.message==="Admin privileges required"?t:new Error("Failed to verify admin status")}}n(z,"assertAdmin");function F(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}n(F,"extractBearerToken");async function D(e,t){try{return t==="supabase"?await K(e):t==="firebase"?{uid:(await(await k()).verifyIdToken(e)).uid}:R("serverAuth")?{uid:(await T("serverAuth").verifyToken(e)).uid}:{uid:(await(await k()).verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}n(D,"verifyToken");async function K(e){let{createClient:t}=await import("@supabase/supabase-js"),s=process.env.SUPABASE_URL,r=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!r)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let o=t(s,r,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:a},error:f}=await o.auth.getUser(e);if(f||!a)throw new Error("Invalid or expired token");return{uid:a.id}}n(K,"verifySupabaseToken");async function H(e,t){let s=F(e.headers.authorization),{uid:r}=await D(s,t);return r}n(H,"verifyAuthToken");var L="webhook_idempotency",V=M([S(),B(b(e=>typeof e=="object"&&e!==null&&typeof e.toMillis=="function","expiresAt must be a Firestore Timestamp or a number"),x(e=>e.toMillis()))]),j=O({status:l(v(["processing","processed"])),ownerToken:l(P()),reservedAt:l(S()),expiresAt:l(V)});function _(e,t){let s=y(j,t);if(!s.success)throw new Error(`Malformed ${L}/${e}: ${s.issues.map(r=>r.message).join("; ")}`);return s.output}n(_,"parseEventDoc");function $(){let e=null,t=n(async()=>{e||(e=await import("./server-24XGDDO3.js"));let r=e.getFirebaseAdminFirestore();return{firestore:r,Timestamp:e.Timestamp,refOf:n(o=>r.collection(L).doc(o),"refOf")}},"load");return{reserve:n(async r=>{let{firestore:o,Timestamp:a,refOf:f}=await t(),d=f(r);try{return await o.runTransaction(async i=>{let p=await i.get(d),c=Date.now();if(p.exists){let m=_(r,p.data());if(m.status==="processing"){if(c-(m.reservedAt??0)<E)return{state:"in_progress"}}else if((m.expiresAt??0)>=c)return{state:"processed"}}let u=g();return i.set(d,{eventId:r,status:"processing",ownerToken:u,reservedAt:c,expiresAt:a.fromMillis(c+A)}),{state:"reserved",ownerToken:u}})}catch(i){throw h(i)}},"reserve"),async markProcessed(r,o){let{firestore:a,Timestamp:f,refOf:d}=await t(),i=d(r),p=Date.now(),c={eventId:r,status:"processed",processedAt:p,expiresAt:f.fromMillis(p+A)};try{await a.runTransaction(async u=>{let m=await u.get(i);if((m.exists?_(r,m.data()):null)?.ownerToken!==o)throw new w(r);u.set(i,{...c,ownerToken:o})})}catch(u){throw u instanceof w?u:h(u)}},async release(r,o){let{firestore:a,refOf:f}=await t(),d=f(r);try{return await a.runTransaction(async i=>{let p=await i.get(d);if(!p.exists)return!1;let c=_(r,p.data());return c.status!=="processing"||c.ownerToken!==o?!1:(i.delete(d),!0)})}catch(i){throw h(i)}}}}n($,"createFirestoreIdempotencyStore");function ae(){let e=new Map;return{reserve:n(async s=>{let r=e.get(s),o=Date.now();if(r?.status==="processed")return{state:"processed"};if(r&&o-r.at<E)return{state:"in_progress"};let a=g();return e.set(s,{status:"processing",ownerToken:a,at:o}),{state:"reserved",ownerToken:a}},"reserve"),async markProcessed(s,r){if(e.get(s)?.ownerToken!==r)throw new w(s);e.set(s,{status:"processed",ownerToken:r,at:Date.now()})},async release(s,r){let o=e.get(s);return o?.status!=="processing"||o.ownerToken!==r?!1:(e.delete(s),!0)}}}n(ae,"createInMemoryIdempotencyStore");export{N as a,Y as b,C as c,z as d,D as e,H as f,$ as g,ae as h};
|
|
22
|
-
//# sourceMappingURL=chunk-TJPJXJEK.js.map
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|