@donotdev/functions 0.3.2 → 0.3.4

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.
Files changed (50) hide show
  1. package/lib/chunks/{chunk-IO4MUTT6.js → chunk-6JBLL6ZX.js} +2 -2
  2. package/lib/chunks/{chunk-LJXSA7EP.js → chunk-6PXANFSJ.js} +2 -2
  3. package/lib/chunks/chunk-CZ5IFNKD.js +22 -0
  4. package/lib/chunks/chunk-CZ5IFNKD.js.map +7 -0
  5. package/lib/chunks/{chunk-Y6BR2QOV.js → chunk-FGXZMPSY.js} +2 -2
  6. package/lib/chunks/{chunk-NP4Y2LAO.js → chunk-GIKHRVAH.js} +2 -2
  7. package/lib/chunks/{chunk-MJ5VZTLM.js → chunk-H5ZLI4H4.js} +2 -2
  8. package/lib/chunks/{chunk-4BJP372Z.js → chunk-ID7MUXVQ.js} +2 -2
  9. package/lib/chunks/{chunk-WJUL2W7Y.js → chunk-KVU7ZB5P.js} +2 -2
  10. package/lib/chunks/{chunk-CCEGC2T6.js → chunk-PTC62U6W.js} +2 -2
  11. package/lib/chunks/{monitoring-B2DYDCYC.js → monitoring-CRYSBHK2.js} +2 -2
  12. package/lib/chunks/{rateLimiter-JCBEG33M.js → rateLimiter-OPEHIYNW.js} +2 -2
  13. package/lib/chunks/{server-YXYTPMRF.js → server-BABJRPD3.js} +2 -2
  14. package/lib/firebase/auth/index.d.ts +1 -0
  15. package/lib/firebase/auth/listAuthUsers.d.ts +24 -0
  16. package/lib/firebase/index.js +1 -1
  17. package/lib/firebase/index.js.map +4 -4
  18. package/lib/shared/index.js +1 -1
  19. package/lib/shared/utils.d.ts +5 -27
  20. package/lib/supabase/auth/listAuthUsers.d.ts +19 -0
  21. package/lib/supabase/index.d.ts +1 -0
  22. package/lib/supabase/index.js +1 -1
  23. package/lib/supabase/index.js.map +4 -4
  24. package/lib/vercel/api/index.js +1 -1
  25. package/package.json +3 -3
  26. package/src/firebase/auth/__tests__/listAuthUsers.test.ts +130 -0
  27. package/src/firebase/auth/index.ts +1 -0
  28. package/src/firebase/auth/listAuthUsers.ts +110 -0
  29. package/src/firebase/crud/delete.ts +57 -1
  30. package/src/shared/email/provider.ts +0 -0
  31. package/src/shared/email/resendProvider.ts +0 -0
  32. package/src/shared/utils.ts +5 -75
  33. package/src/supabase/__tests__/firebaseBoundary.test.ts +53 -0
  34. package/src/supabase/auth/__tests__/listAuthUsers.test.ts +156 -0
  35. package/src/supabase/auth/listAuthUsers.ts +98 -0
  36. package/src/supabase/baseFunction.ts +0 -0
  37. package/src/supabase/index.ts +1 -0
  38. package/lib/chunks/chunk-TBHRDSX5.js +0 -22
  39. package/lib/chunks/chunk-TBHRDSX5.js.map +0 -7
  40. /package/lib/chunks/{chunk-IO4MUTT6.js.map → chunk-6JBLL6ZX.js.map} +0 -0
  41. /package/lib/chunks/{chunk-LJXSA7EP.js.map → chunk-6PXANFSJ.js.map} +0 -0
  42. /package/lib/chunks/{chunk-Y6BR2QOV.js.map → chunk-FGXZMPSY.js.map} +0 -0
  43. /package/lib/chunks/{chunk-NP4Y2LAO.js.map → chunk-GIKHRVAH.js.map} +0 -0
  44. /package/lib/chunks/{chunk-MJ5VZTLM.js.map → chunk-H5ZLI4H4.js.map} +0 -0
  45. /package/lib/chunks/{chunk-4BJP372Z.js.map → chunk-ID7MUXVQ.js.map} +0 -0
  46. /package/lib/chunks/{chunk-WJUL2W7Y.js.map → chunk-KVU7ZB5P.js.map} +0 -0
  47. /package/lib/chunks/{chunk-CCEGC2T6.js.map → chunk-PTC62U6W.js.map} +0 -0
  48. /package/lib/chunks/{monitoring-B2DYDCYC.js.map → monitoring-CRYSBHK2.js.map} +0 -0
  49. /package/lib/chunks/{rateLimiter-JCBEG33M.js.map → rateLimiter-OPEHIYNW.js.map} +0 -0
  50. /package/lib/chunks/{server-YXYTPMRF.js.map → server-BABJRPD3.js.map} +0 -0
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a as i}from"./chunk-W6W4L44F.js";import{a as u}from"./chunk-AYY7UXNI.js";async function d(){let{getFirebaseAdminFirestore:r}=await import("./server-YXYTPMRF.js");return r()}u(d,"getFirestore");async function w(r){try{await(await d()).collection("payment_metrics").doc().set({...r,recordedAt:new Date().toISOString()}),i.info("Payment metrics recorded",{operation:r.operation,status:r.status,userId:r.userId})}catch(t){i.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:r})}}u(w,"recordPaymentMetrics");async function b(r=24){try{let t=await d(),e=new Date;e.setHours(e.getHours()-r);let c=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).get();if(c.empty)return{failureRate:0,shouldAlert:!1};let m=c.size,a=c.docs.filter(l=>l.data().status==="failed").length,s=a/m*100,n=s>10;return n&&await y(s,m,a),{failureRate:s,shouldAlert:n}}catch(t){return i.error("Failed to check payment failure rate",{error:t instanceof Error?t.message:String(t)}),{failureRate:0,shouldAlert:!1}}}u(b,"checkPaymentFailureRate");async function S(r=1e4){try{let t=await d(),e=new Date;e.setHours(0,0,0,0);let o=new Date(e);o.setDate(o.getDate()+1);let m=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).where("timestamp","<",o.toISOString()).where("status","==","success").get(),a=0;m.docs.forEach(n=>{let l=n.data();l.amount&&l.currency==="usd"&&(a+=l.amount/100)});let s=a>r;return s&&await p(a,r),{totalVolume:a,shouldAlert:s}}catch(t){return i.error("Failed to check payment volume",{error:t instanceof Error?t.message:String(t)}),{totalVolume:0,shouldAlert:!1}}}u(S,"checkPaymentVolume");async function y(r,t,e){try{await(await d()).collection("payment_alerts").doc().set({type:"payment_failure_rate",severity:"high",message:`Payment failure rate is ${r.toFixed(2)}% (${e}/${t} payments failed)`,data:{failureRate:r,totalPayments:t,failedPayments:e},triggeredAt:new Date().toISOString(),status:"active"}),i.error("PAYMENT FAILURE ALERT TRIGGERED",{failureRate:r,totalPayments:t,failedPayments:e})}catch(o){i.error("Failed to trigger payment failure alert",{error:o instanceof Error?o.message:String(o)})}}u(y,"triggerPaymentFailureAlert");async function p(r,t){try{await(await d()).collection("payment_alerts").doc().set({type:"high_payment_volume",severity:"medium",message:`Daily payment volume exceeded threshold: $${r.toFixed(2)} (threshold: $${t})`,data:{totalVolume:r,threshold:t},triggeredAt:new Date().toISOString(),status:"active"}),i.warn("HIGH PAYMENT VOLUME ALERT TRIGGERED",{totalVolume:r,threshold:t})}catch(e){i.error("Failed to trigger high volume alert",{error:e instanceof Error?e.message:String(e)})}}u(p,"triggerHighVolumeAlert");async function P(r,t){try{let c=await(await d()).collection("payment_metrics").where("timestamp",">=",r.toISOString()).where("timestamp","<=",t.toISOString()).get(),m=0,a=0,s=0,n=0;c.docs.forEach(g=>{let f=g.data();m++,f.status==="success"?(a++,f.amount&&f.currency==="usd"&&(n+=f.amount/100)):f.status==="failed"&&s++});let l=a>0?n/a:0;return{totalPayments:m,successfulPayments:a,failedPayments:s,totalVolume:n,averageAmount:l}}catch(e){return i.error("Failed to get payment metrics summary",{error:e instanceof Error?e.message:String(e)}),{totalPayments:0,successfulPayments:0,failedPayments:0,totalVolume:0,averageAmount:0}}}u(P,"getPaymentMetricsSummary");async function A(r=90,t=30){try{let e=await d(),o=new Date,c=new Date(o);c.setDate(c.getDate()-r);let m=await e.collection("payment_metrics").where("recordedAt","<",c.toISOString()).limit(500).get();if(!m.empty){let n=e.batch();m.docs.forEach(l=>n.delete(l.ref)),await n.commit()}let a=new Date(o);a.setDate(a.getDate()-t);let s=await e.collection("payment_alerts").where("triggeredAt","<",a.toISOString()).limit(500).get();if(!s.empty){let n=e.batch();s.docs.forEach(l=>n.delete(l.ref)),await n.commit()}i.info("Payment metrics cleanup completed",{deletedMetrics:m.size,deletedAlerts:s.size})}catch(e){i.error("Payment metrics cleanup failed",{error:e instanceof Error?e.message:String(e)})}}u(A,"cleanupOldMetrics");export{w as a,b,S as c,P as d,A as e};
22
- //# sourceMappingURL=chunk-IO4MUTT6.js.map
21
+ import{a as i}from"./chunk-W6W4L44F.js";import{a as u}from"./chunk-AYY7UXNI.js";async function d(){let{getFirebaseAdminFirestore:r}=await import("./server-BABJRPD3.js");return r()}u(d,"getFirestore");async function w(r){try{await(await d()).collection("payment_metrics").doc().set({...r,recordedAt:new Date().toISOString()}),i.info("Payment metrics recorded",{operation:r.operation,status:r.status,userId:r.userId})}catch(t){i.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:r})}}u(w,"recordPaymentMetrics");async function b(r=24){try{let t=await d(),e=new Date;e.setHours(e.getHours()-r);let c=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).get();if(c.empty)return{failureRate:0,shouldAlert:!1};let m=c.size,a=c.docs.filter(l=>l.data().status==="failed").length,s=a/m*100,n=s>10;return n&&await y(s,m,a),{failureRate:s,shouldAlert:n}}catch(t){return i.error("Failed to check payment failure rate",{error:t instanceof Error?t.message:String(t)}),{failureRate:0,shouldAlert:!1}}}u(b,"checkPaymentFailureRate");async function S(r=1e4){try{let t=await d(),e=new Date;e.setHours(0,0,0,0);let o=new Date(e);o.setDate(o.getDate()+1);let m=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).where("timestamp","<",o.toISOString()).where("status","==","success").get(),a=0;m.docs.forEach(n=>{let l=n.data();l.amount&&l.currency==="usd"&&(a+=l.amount/100)});let s=a>r;return s&&await p(a,r),{totalVolume:a,shouldAlert:s}}catch(t){return i.error("Failed to check payment volume",{error:t instanceof Error?t.message:String(t)}),{totalVolume:0,shouldAlert:!1}}}u(S,"checkPaymentVolume");async function y(r,t,e){try{await(await d()).collection("payment_alerts").doc().set({type:"payment_failure_rate",severity:"high",message:`Payment failure rate is ${r.toFixed(2)}% (${e}/${t} payments failed)`,data:{failureRate:r,totalPayments:t,failedPayments:e},triggeredAt:new Date().toISOString(),status:"active"}),i.error("PAYMENT FAILURE ALERT TRIGGERED",{failureRate:r,totalPayments:t,failedPayments:e})}catch(o){i.error("Failed to trigger payment failure alert",{error:o instanceof Error?o.message:String(o)})}}u(y,"triggerPaymentFailureAlert");async function p(r,t){try{await(await d()).collection("payment_alerts").doc().set({type:"high_payment_volume",severity:"medium",message:`Daily payment volume exceeded threshold: $${r.toFixed(2)} (threshold: $${t})`,data:{totalVolume:r,threshold:t},triggeredAt:new Date().toISOString(),status:"active"}),i.warn("HIGH PAYMENT VOLUME ALERT TRIGGERED",{totalVolume:r,threshold:t})}catch(e){i.error("Failed to trigger high volume alert",{error:e instanceof Error?e.message:String(e)})}}u(p,"triggerHighVolumeAlert");async function P(r,t){try{let c=await(await d()).collection("payment_metrics").where("timestamp",">=",r.toISOString()).where("timestamp","<=",t.toISOString()).get(),m=0,a=0,s=0,n=0;c.docs.forEach(g=>{let f=g.data();m++,f.status==="success"?(a++,f.amount&&f.currency==="usd"&&(n+=f.amount/100)):f.status==="failed"&&s++});let l=a>0?n/a:0;return{totalPayments:m,successfulPayments:a,failedPayments:s,totalVolume:n,averageAmount:l}}catch(e){return i.error("Failed to get payment metrics summary",{error:e instanceof Error?e.message:String(e)}),{totalPayments:0,successfulPayments:0,failedPayments:0,totalVolume:0,averageAmount:0}}}u(P,"getPaymentMetricsSummary");async function A(r=90,t=30){try{let e=await d(),o=new Date,c=new Date(o);c.setDate(c.getDate()-r);let m=await e.collection("payment_metrics").where("recordedAt","<",c.toISOString()).limit(500).get();if(!m.empty){let n=e.batch();m.docs.forEach(l=>n.delete(l.ref)),await n.commit()}let a=new Date(o);a.setDate(a.getDate()-t);let s=await e.collection("payment_alerts").where("triggeredAt","<",a.toISOString()).limit(500).get();if(!s.empty){let n=e.batch();s.docs.forEach(l=>n.delete(l.ref)),await n.commit()}i.info("Payment metrics cleanup completed",{deletedMetrics:m.size,deletedAlerts:s.size})}catch(e){i.error("Payment metrics cleanup failed",{error:e instanceof Error?e.message:String(e)})}}u(A,"cleanupOldMetrics");export{w as a,b,S as c,P as d,A as e};
22
+ //# sourceMappingURL=chunk-6JBLL6ZX.js.map
@@ -18,7 +18,7 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{E as le,G as L,I as me,J as B,K as fe,L as he,P as ge,S as _e,V as g,a as ae,b as z,ba as q,c as ce,d as de,ja as K,la as we,na as Ee,o as ue,oa as ke,pa as ye,qa as Se,ra as ve,sa as Ie,ta as be,x as pe}from"./chunk-Y6BR2QOV.js";import{a as p}from"./chunk-W6W4L44F.js";import{a as s}from"./chunk-AYY7UXNI.js";function S(e){let t,r,o;if(e instanceof g)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||"name"in e&&e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||"name"in e&&e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new g(r,t,o?{details:o}:void 0)}s(S,"handleError");function Tt(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}s(Tt,"createMetadata");function At(e){return{updatedAt:new Date().toISOString(),updatedById:e}}s(At,"updateMetadata");function J(e,t,r){if(e.unknownKeys.length>0&&console.warn(`[dndev] ${t} ${r}: fields the entity does not have, not written: ${e.unknownKeys.join(", ")}`),e.ok)return e.written;let o=e.issues.map(n=>`${n.path?.map(i=>String(i.key)).join(".")||"root"}: ${n.message}`).join("; ");throw new g(`Validation failed on ${t} ${r}: ${o}`,"invalid-argument",{details:{validationErrors:e.issues}})}s(J,"writtenOf");var Ye=Object.freeze({insertedIds:[],updatedIds:[],deletedIds:[]});async function Mt(e){let{collection:t,ops:r,createSchema:o,draftCreateSchema:n,updateSchema:i,access:a,uid:c,userRole:u,transact:d,readStored:m,mintInsertId:_,stampInsertMetadata:k,stampUpdateMetadata:I,audit:A}=e,C=L(Ee,r);if(!C.success){let f=C.issues.map(w=>`${w.path?.map(P=>P.key).join(".")||"root"}: ${w.message}`).join("; ");throw new g(`Bulk payload validation failed: ${f}`,"invalid-argument",{details:{validationErrors:C.issues}})}let R=C.output,v=R.inserts??[],h=R.updates??[],E=R.deletes??[],T=ye(R);if(T.where!==null)throw new _e(T.collisions,T.where);if(v.length===0&&h.length===0&&E.length===0)return Ye;if(v.length>0){if(!a.create)throw new g(`Bulk insert requested on ${t} but no create role is configured`,"permission-denied");if(!q(u,a.create))throw new g(`Access denied for bulk insert on ${t}. Required: ${a.create}, your role: ${u}`,"permission-denied")}if(h.length>0){if(!a.update)throw new g(`Bulk update requested on ${t} but no update role is configured`,"permission-denied");if(!q(u,a.update))throw new g(`Access denied for bulk update on ${t}. Required: ${a.update}, your role: ${u}`,"permission-denied")}if(E.length>0){if(!a.delete)throw new g(`Bulk delete requested on ${t} but no delete role is configured`,"permission-denied");if(!q(u,a.delete))throw new g(`Access denied for bulk delete on ${t}. Required: ${a.delete}, your role: ${u}`,"permission-denied")}let y=s(f=>{throw new g(`Validation failed on ${f}: draft row sent to ${t} but no draft schema is configured`,"invalid-argument")},"noDraftSchema"),U={create:o,draft:n??o,update:i},$=[];for(let f=0;f<v.length;f++){let w=v[f];!n&&we(Se(w),"saveIncomplete")&&y(`inserts[${f}]`);let P=J(ve(U,w),t,`inserts[${f}]`);$.push({row:P,id:typeof w.id=="string"?w.id:null})}if(h.length>0&&!m)throw new g(`Bulk update requested on ${t} but no readStored is configured: the stored row decides each patch's rules`,"internal");let l=h.length>0&&m?await m(h.map(f=>f.id)):new Map,b=[];for(let f=0;f<h.length;f++){let{id:w,patch:P}=h[f],O=`updates[${f}]`,M=l.get(w);if(!M)throw new g(`Document not found on ${O}: ${t}/${w}`,"not-found");!n&&Ie(P,M).schemaKey==="draft"&&y(O),b.push(J(be(U,{id:w,patch:P,stored:M}),t,O))}let D=$.map(({row:f,id:w})=>{let P=_?_():w??"",O=!_&&w!==null?{...f,id:w}:f,M=k?k(O,c):O;return{id:P,row:M}}),W=h.map((f,w)=>({id:f.id,patch:I?I(b[w],c):b[w]})),Y=await d({inserts:D,updates:W,deletes:[...E]}),se=L(ke,Y);if(!se.success)throw new g(`Bulk transact() returned an unexpected shape for ${t}`,"internal");return A&&A(`crud.bulk.${t}`,{counts:{inserts:D.length,updates:W.length,deletes:E.length}}),se.output}s(Mt,"executeBulk");function Z(e,t,r=ce){let o=de[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,i=e.completionTokens/1e6*o.completionPer1M,a=n+i;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:i}}}s(Z,"calculateCost");function j(){return globalThis.Deno?.env}s(j,"getDenoEnv");async function ze(e,t){let o={anthropic:s(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:s(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:s(async()=>{let{createGoogle:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=tt(e);return(await o())(n)}s(ze,"resolveModel");var Je={maxRequests:30,windowMs:6e4},x=null;async function Ze(){if(x)return x;let e=V("UPSTASH_REDIS_REST_URL"),t=V("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),x={check:s(async()=>{},"check")},x;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),i=new Map;return x={check:s(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=i.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),i.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},x}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),x={check:s(async()=>{},"check")},x}}s(Ze,"getRateLimiter");function Qe(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[i,a]of Object.entries(o))n[i]=e.tool({description:a.description,inputSchema:e.jsonSchema(a.parameters)});return n}s(Qe,"resolveTools");function Q(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}s(Q,"toAIUsage");async function et(e,t,r){let o=me(e);if(!o.success)return H(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",i=ae[n],a=e.model||t.model||i?.default||"claude-sonnet-4-20250514";if(i){let l=i.models;if(!l.includes(a))return H(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await Ze()).check(r.userId,t.rateLimitConfig||Je)}catch(l){return H(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await ze(n,a)}catch(l){return H(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
21
+ import{E as le,G as L,I as me,J as B,K as fe,L as he,P as ge,S as _e,V as g,a as ae,b as z,ba as q,c as ce,d as de,ja as K,la as we,na as Ee,o as ue,oa as ke,pa as ye,qa as Se,ra as ve,sa as Ie,ta as be,x as pe}from"./chunk-FGXZMPSY.js";import{a as p}from"./chunk-W6W4L44F.js";import{a as s}from"./chunk-AYY7UXNI.js";function S(e){let t,r,o;if(e instanceof g)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||"name"in e&&e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||"name"in e&&e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new g(r,t,o?{details:o}:void 0)}s(S,"handleError");function Tt(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}s(Tt,"createMetadata");function At(e){return{updatedAt:new Date().toISOString(),updatedById:e}}s(At,"updateMetadata");function J(e,t,r){if(e.unknownKeys.length>0&&console.warn(`[dndev] ${t} ${r}: fields the entity does not have, not written: ${e.unknownKeys.join(", ")}`),e.ok)return e.written;let o=e.issues.map(n=>`${n.path?.map(i=>String(i.key)).join(".")||"root"}: ${n.message}`).join("; ");throw new g(`Validation failed on ${t} ${r}: ${o}`,"invalid-argument",{details:{validationErrors:e.issues}})}s(J,"writtenOf");var Ye=Object.freeze({insertedIds:[],updatedIds:[],deletedIds:[]});async function Mt(e){let{collection:t,ops:r,createSchema:o,draftCreateSchema:n,updateSchema:i,access:a,uid:c,userRole:u,transact:d,readStored:m,mintInsertId:_,stampInsertMetadata:k,stampUpdateMetadata:I,audit:A}=e,C=L(Ee,r);if(!C.success){let f=C.issues.map(w=>`${w.path?.map(P=>P.key).join(".")||"root"}: ${w.message}`).join("; ");throw new g(`Bulk payload validation failed: ${f}`,"invalid-argument",{details:{validationErrors:C.issues}})}let R=C.output,v=R.inserts??[],h=R.updates??[],E=R.deletes??[],T=ye(R);if(T.where!==null)throw new _e(T.collisions,T.where);if(v.length===0&&h.length===0&&E.length===0)return Ye;if(v.length>0){if(!a.create)throw new g(`Bulk insert requested on ${t} but no create role is configured`,"permission-denied");if(!q(u,a.create))throw new g(`Access denied for bulk insert on ${t}. Required: ${a.create}, your role: ${u}`,"permission-denied")}if(h.length>0){if(!a.update)throw new g(`Bulk update requested on ${t} but no update role is configured`,"permission-denied");if(!q(u,a.update))throw new g(`Access denied for bulk update on ${t}. Required: ${a.update}, your role: ${u}`,"permission-denied")}if(E.length>0){if(!a.delete)throw new g(`Bulk delete requested on ${t} but no delete role is configured`,"permission-denied");if(!q(u,a.delete))throw new g(`Access denied for bulk delete on ${t}. Required: ${a.delete}, your role: ${u}`,"permission-denied")}let y=s(f=>{throw new g(`Validation failed on ${f}: draft row sent to ${t} but no draft schema is configured`,"invalid-argument")},"noDraftSchema"),U={create:o,draft:n??o,update:i},$=[];for(let f=0;f<v.length;f++){let w=v[f];!n&&we(Se(w),"saveIncomplete")&&y(`inserts[${f}]`);let P=J(ve(U,w),t,`inserts[${f}]`);$.push({row:P,id:typeof w.id=="string"?w.id:null})}if(h.length>0&&!m)throw new g(`Bulk update requested on ${t} but no readStored is configured: the stored row decides each patch's rules`,"internal");let l=h.length>0&&m?await m(h.map(f=>f.id)):new Map,b=[];for(let f=0;f<h.length;f++){let{id:w,patch:P}=h[f],O=`updates[${f}]`,M=l.get(w);if(!M)throw new g(`Document not found on ${O}: ${t}/${w}`,"not-found");!n&&Ie(P,M).schemaKey==="draft"&&y(O),b.push(J(be(U,{id:w,patch:P,stored:M}),t,O))}let D=$.map(({row:f,id:w})=>{let P=_?_():w??"",O=!_&&w!==null?{...f,id:w}:f,M=k?k(O,c):O;return{id:P,row:M}}),W=h.map((f,w)=>({id:f.id,patch:I?I(b[w],c):b[w]})),Y=await d({inserts:D,updates:W,deletes:[...E]}),se=L(ke,Y);if(!se.success)throw new g(`Bulk transact() returned an unexpected shape for ${t}`,"internal");return A&&A(`crud.bulk.${t}`,{counts:{inserts:D.length,updates:W.length,deletes:E.length}}),se.output}s(Mt,"executeBulk");function Z(e,t,r=ce){let o=de[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,i=e.completionTokens/1e6*o.completionPer1M,a=n+i;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:i}}}s(Z,"calculateCost");function j(){return globalThis.Deno?.env}s(j,"getDenoEnv");async function ze(e,t){let o={anthropic:s(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:s(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:s(async()=>{let{createGoogle:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=tt(e);return(await o())(n)}s(ze,"resolveModel");var Je={maxRequests:30,windowMs:6e4},x=null;async function Ze(){if(x)return x;let e=V("UPSTASH_REDIS_REST_URL"),t=V("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),x={check:s(async()=>{},"check")},x;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),i=new Map;return x={check:s(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=i.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),i.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},x}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),x={check:s(async()=>{},"check")},x}}s(Ze,"getRateLimiter");function Qe(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[i,a]of Object.entries(o))n[i]=e.tool({description:a.description,inputSchema:e.jsonSchema(a.parameters)});return n}s(Qe,"resolveTools");function Q(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}s(Q,"toAIUsage");async function et(e,t,r){let o=me(e);if(!o.success)return H(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",i=ae[n],a=e.model||t.model||i?.default||"claude-sonnet-4-20250514";if(i){let l=i.models;if(!l.includes(a))return H(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await Ze()).check(r.userId,t.rateLimitConfig||Je)}catch(l){return H(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await ze(n,a)}catch(l){return H(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
22
22
  `):void 0),m=e.messages.filter(l=>l.role!=="system").map(l=>({role:l.role,content:l.content})),_=e.maxTokens||t.maxTokens||4096,k=e.temperature??t.temperature??.7,I=r.requestId||crypto.randomUUID(),A=await import("ai"),{streamText:C,generateText:R,toUIMessageStream:v,createUIMessageStreamResponse:h}=A,E=Qe(A,e.tools,t.tools),T=s(async l=>{if(!r.onCostRecord)return;let b=t.cost?.markup??4,D=Z(l,a,b),W={userId:r.userId,model:a,provider:n,usage:l,providerCost:D.providerCost,billedCost:D.billedCost,markup:b,timestamp:new Date().toISOString(),requestId:I};r.onCostRecord(W).catch(Y=>{console.error("[AI] Failed to record cost:",Y)})},"recordCost");if(e.stream!==!1){let l=C({model:c,messages:m,instructions:d,maxOutputTokens:_,temperature:k,tools:E,onEnd:s(async({usage:b})=>{await T(Q(b))},"onEnd")});return h({stream:v({stream:l.stream,messageMetadata:s(({part:b})=>b.type==="finish"?{usage:Q(b.totalUsage)}:void 0,"messageMetadata")})})}let y=await R({model:c,messages:m,instructions:d,maxOutputTokens:_,temperature:k,tools:E}),U=Q(y.usage);await T(U);let $=y.toolCalls.map(l=>({id:l.toolCallId,name:l.toolName,args:l.input}));return new Response(JSON.stringify({message:{role:"assistant",content:y.text},usage:U,finishReason:y.finishReason,toolCalls:$.length>0?$:void 0,model:a,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}s(et,"handleAIRequest");function H(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}s(H,"jsonError");function V(e){return typeof globalThis<"u"&&"Deno"in globalThis?j()?.get(e):typeof process<"u"?process.env[e]:void 0}s(V,"getEnv");function tt(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=V(r);if(n)return n}let o=V("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}s(tt,"getAIApiKey");function Re(e){return typeof globalThis<"u"&&"Deno"in globalThis?j()?.get(e):typeof process<"u"?process.env[e]:void 0}s(Re,"getEnv");function rt(e,t){if(t){let n=Re(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=Re(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(z).find(n=>n.id===e)?.defaultModel??z.STANDARD.defaultModel)}s(rt,"resolveModelForTier");function ot(e){let t=it(e),r=st(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:Te(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:Te(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}s(ot,"classifyAIError");function nt(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}s(nt,"mapClassifiedToHTTP");function it(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error=="object"&&e.error!==null&&"status"in e.error&&typeof e.error.status=="number")return e.error.status}}s(it,"extractStatus");function st(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}s(st,"extractMessage");function Te(e){if(e&&typeof e=="object"){let t="headers"in e?e.headers:void 0;if(t&&typeof t=="object"){let r="get"in t&&typeof t.get=="function"?t.get("retry-after"):"retry-after"in t?t["retry-after"]:void 0;if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}s(Te,"extractRetryAfter");var Ae="2025-02-24.acacia";var ee=Ae,F="orderId",X="productId";function G(e){return e===null?null:typeof e=="string"?e:e.id}s(G,"idOf");function Pe(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}s(Pe,"toAddress");function at(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:G(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?Pe(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:Pe(r.address)}:null,invoiceId:G(e.invoice),paymentIntentId:G(e.payment_intent),metadata:e.metadata??{}}}s(at,"toCheckoutSessionSnapshot");async function ct(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,i=n&&typeof n!="string"&&!n.deleted?n.metadata[X]:void 0;if(!i)throw new Error(`Line item ${o.id} of session ${t} has no ${X} product metadata`);r.push({productId:i,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}s(ct,"listPaidLineItems");async function xe(e,t,r,o,n,i,a){if(!r||r.slice(0,10)<ee.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[F]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${ee} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${ee}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[F];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},_=at(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let I=await ct(a,o.id);await i.onOrderPaid(_,I,m),p.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":p.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":i.onOrderPaymentFailed&&await i.onOrderPaymentFailed(_,m),p.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":i.onOrderExpired&&await i.onOrderExpired(_,m),p.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}s(xe,"handleOrderSessionEvent");function dt(e){return{id:e.id,customerId:G(e.customer),type:e.type,value:e.value,country:e.country,verification:e.verification&&{status:e.verification.status,verifiedName:e.verification.verified_name,verifiedAddress:e.verification.verified_address}}}s(dt,"toTaxIdSnapshot");async function Oe(e,t,r){let o=dt(t),n=new Set;for(let[i,a]of Object.entries(r))a.type!=="StripeOrder"||!a.onTaxIdUpdated||n.has(a.onTaxIdUpdated)||(n.add(a.onTaxIdUpdated),await a.onTaxIdUpdated(o,{billingConfigKey:i,eventId:e}),p.info("[Webhook] Tax ID updated",{taxIdId:o.id,status:o.verification?.status??null,billingConfigKey:i,operation:"tax_id_updated"}));n.size===0&&p.debug("[Webhook] customer.tax_id.updated without onTaxIdUpdated hook",{eventId:e})}s(Oe,"handleTaxIdUpdated");function Ne(e,t){let{billingConfigKey:r,priceId:o}=t,[n]=t.lineItems;if(t.lineItems.length!==1||!n||n.productId!==r||n.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let i=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,mode:i}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,mode:i}}s(Ne,"resolvePricePlan");function Ue(e){let t=e.mode||"payment";return{mode:t,line_items:[{price:e.priceId,quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}s(Ue,"toStripeSessionParams");var ut={maxKeys:50,maxKeyLength:40,maxValueLength:500};function re(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}s(re,"validateCheckoutUrl");function De(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}s(De,"sanitizeMetadata");function oe(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=ut,i=Object.entries(e);if(i.length>r)throw new Error(`${t}: ${i.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[a,c]of i){if(a.length>o)throw new Error(`${t}: metadata key '${a}' is too long (max ${o} characters)`);if(/[[\]]/.test(a))throw new Error(`${t}: metadata key '${a}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${a}' is too long (max ${n} characters)`)}}s(oe,"assertStripeMetadata");function ne(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&oe(o,r)}s(ne,"assertCheckoutSessionMetadata");function Me(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&ht(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`);if(r.taxCode!==void 0&&!ft.test(r.taxCode))throw new Error(`Line '${r.productId}': taxCode must be a Stripe tax code (txcd_ + 8 digits), got '${r.taxCode}'`)}}s(Me,"assertResolvedOrder");var pt={minSeconds:1800,maxSeconds:1440*60},$e=5e3,lt=["card","sepa_debit"],mt=/^cus_[A-Za-z0-9]+$/,ft=/^txcd_\d{8}$/;function ht(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:i,invoiceFooter:a,customerId:c}=e;if(c!==void 0&&!mt.test(c))throw new Error(`resolveLineItems for '${t}': session.customerId must be a Stripe Customer ID (cus_...), got '${c}'`);if(o&&o.some(u=>typeof u!="string"||u.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let u of n)if(!lt.includes(u))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${u}'`)}if(i!==void 0){let{minSeconds:u,maxSeconds:d}=pt;if(!Number.isInteger(i)||i<r+u||i>r+d)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${i}`)}if(a!==void 0&&(a.length===0||a.length>$e))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${$e} characters`)}s(ht,"assertResolvedOrderSession");var te=new Map;async function ie(e,t,r){for(let o of t){let n=te.get(o);if(n||(n=e(o).then(i=>i.inclusive),te.set(o,n),n.catch(()=>te.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}s(ie,"assertExclusiveTaxRates");function Le(e){return"createStripeSession"in e}s(Le,"isSessionProvider");function Be(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}s(Be,"resolveRedirectUrl");function gt(e,t){let r={...e.tax.mode==="automatic"&&{address:"auto"},...e.shipping&&{shipping:"auto"},...t&&{name:"auto"}};return Object.keys(r).length>0?r:void 0}s(gt,"customerUpdate");function _t(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,i={...r.metadata,[F]:t.orderId},a=e.taxIdCollection!=="disabled",c=gt(e,a),u=o.customerId?{customer:o.customerId,...c&&{customer_update:c}}:{customer_creation:e.customerCreation,customer_email:r.customerEmail};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(d=>({price_data:{currency:e.currency,unit_amount:d.unitAmount,tax_behavior:"exclusive",product_data:{name:d.name,...d.description&&{description:d.description},...d.taxCode&&{tax_code:d.taxCode},metadata:{[X]:d.productId}}},quantity:d.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:a?{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"}:{enabled:!1},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(d=>({shipping_rate:d}))}},...u,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:i,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,metadata:i,payment_intent_data:{metadata:i}}}s(_t,"buildOrderSessionParams");async function Er(e,...t){let r=t.length===3,[o,n,i,a]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=a[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",_=m?void 0:Ne(d,u);await i.getUser(o);let k=De(u.metadata??{}),I={...k,userId:o,billingConfigKey:c};oe(m?{...I,[F]:""}:I,"metadata");let A=u.allowPromotionCodes??!0;if(d.beforeCheckout){let h={...u,userId:o,mode:_?.mode??"payment",priceId:_?.priceId,metadata:u.metadata??{},allowPromotionCodes:A},E=await d.beforeCheckout(o,h,k);if(!E.allowed)throw new Error(E.reason||"Checkout blocked by beforeCheckout hook")}let C=Be(u.successUrl,"success"),R=Be(u.cancelUrl,"cancel");re(C,"success"),re(R,"cancel");let v;if(d.type==="StripeOrder"){if(!Le(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await ie(y=>n.retrieveTaxRate(y),d.tax.taxRateIds,c);let h=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:k});Me(h,c);let E=h.session;if(E?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await ie(y=>n.retrieveTaxRate(y),E.taxRateIds,c)}if(d.tax.mode!=="automatic"&&h.lineItems.some(y=>y.taxCode!==void 0))throw new Error(`resolveLineItems for '${c}': line taxCode needs tax.mode 'automatic'`);if(E?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let T=_t(d,h,{successUrl:C,cancelUrl:R,customerEmail:u.customerEmail,metadata:I});ne(T),v=await n.createStripeSession(T)}else{let h={priceId:_?.priceId,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:I,allowPromotionCodes:A,successUrl:C,cancelUrl:R,mode:_?.mode};if(Le(n)){let E=Ue(h);ne(E),v=await n.createStripeSession(E)}else v=await n.createCheckoutSession(h)}return{sessionId:v.id,sessionUrl:v.url}}s(Er,"createCheckoutAlgorithm");async function vr(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");let i=le(he,{tier:t.tier,subscriptionId:t.subscriptionId??null,customerId:t.customerId??null,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd??!1,updatedAt:new Date().toISOString(),isDefault:!1}),a={...n,subscription:i};await r.setCustomUserClaims(e,a)}s(vr,"updateUserSubscription");var N=class extends Error{static{s(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},Fe=4200*1e3,Cr=720*60*60*1e3;function We(){return crypto.randomUUID()}s(We,"newOwnerToken");function qe(e){return e.subscription}s(qe,"pinnedInvoiceSubscriptionId");function Ar(e,t){return e.includes(t)}s(Ar,"isOneOf");async function je(e,t,r,o,n){let i={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){p.info("[Webhook] Purchase awaiting async payment",{...i,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw S(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await Ke(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await Ke(t,r,o,n);return;case"checkout.session.async_payment_failed":p.warn("[Webhook] Async purchase payment failed, nothing granted",{...i,operation:"purchase_payment_failed"});return;case"checkout.session.expired":p.debug("[Webhook] Checkout session expired",i);return}}s(je,"handleTierCheckoutEvent");async function Ke(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)throw S(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${i}`));let a=t[i];if(!a)throw S(new Error(`Unknown billing config key: ${i}`));if(p.info("[Webhook] Processing purchase",{userId:n,configKey:i,type:a.type,operation:"purchase_processing"}),a.type==="StripePayment"){if(!o)throw S(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:B.ACTIVE,subscriptionEnd:K(a.duration),customerId:e.customer},o),a.onPurchaseSuccess)try{await a.onPurchaseSuccess(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(a.type==="StripeSubscription"){if(!o)throw S(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:B.ACTIVE,subscriptionEnd:K(a.duration),subscriptionId:e.subscription,customerId:e.customer},o),a.onSubscriptionCreated)try{await a.onSubscriptionCreated(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}p.info("[Webhook] Purchase processed",{userId:n,configKey:i,operation:"purchase_processed"})}s(Ke,"grantCheckoutPurchase");async function He(e,t,r,o,n){let i=qe(e);if(!i)return;let a=await o.subscriptions.retrieve(i),{userId:c,billingConfigKey:u}=a.metadata||{};if(!c||!u){p.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:i,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw S(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:B.ACTIVE,subscriptionEnd:K(d.duration),subscriptionId:i,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,a.metadata||{})}catch(m){p.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}p.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}s(He,"handleInvoicePaymentSucceeded");async function Ve(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)return;let a=t[i];if(!(!a||a.type!=="StripeSubscription")){if(!o)throw S(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:fe.FREE,status:B.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),a.onSubscriptionCancelled)try{await a.onSubscriptionCancelled(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}p.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:i,operation:"subscription_cancelled"})}}s(Ve,"handleSubscriptionDeleted");async function Ge(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){p.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){p.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}p.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}s(Ge,"handlePaymentFailed");var wt=3,Et=200;async function Hr(e,t,r,o,n,i,a,c){try{ge(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);p.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return p.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw p.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new g(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:_}=m;a||p.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await St(d,u,i,o,a)}catch(k){throw p.error("[Webhook] Event processing failed, releasing reservation",{error:k instanceof Error?k:new Error(String(k)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await kt(c,d.id,_),k}return await yt(c,d.id,_),{success:!0,message:"Webhook processed"}}catch(u){throw S(u)}}s(Hr,"processWebhook");async function kt(e,t,r){try{await e.release(t,r)||p.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){p.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}s(kt,"releaseReservation");async function yt(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let i=n instanceof Error?n:new Error(String(n));if(n instanceof N)throw p.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:i,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=wt)throw p.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:i,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;p.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:i.message}),await new Promise(a=>setTimeout(a,Et*o))}}s(yt,"markProcessedWithRetry");async function St(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await vt(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await He(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await Ve(e.data.object,t,r,n);break;case"invoice.payment_failed":await Ge(e.data.object,t);break;case"customer.tax_id.updated":await Oe(e.id,e.data.object,t);break;default:p.debug("[Webhook] Unhandled event type",{type:e.type})}}s(St,"routeEvent");async function vt(e,t,r,o,n,i,a,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await xe(e,t,r,o,u,d,a);return}await je(e,o,n,i,c)}s(vt,"handleCheckoutSessionEvent");var zr=`
23
23
  CREATE TABLE IF NOT EXISTS public.webhook_events (
24
24
  event_id TEXT PRIMARY KEY,
@@ -148,4 +148,4 @@ SELECT cron.schedule(
148
148
  $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
149
149
  );
150
150
  `,It=pe(["reserved","processed","in_progress"]),Xe=ue();function Jr(e){let t=s(async(r,o,n)=>{let{data:i,error:a}=await e.rpc(r,o);if(a)throw S(a);let c=L(n,i);if(!c.success)throw S(new Error(`${r} returned an unexpected result: ${JSON.stringify(i)}`));return c.output},"call");return{async reserve(r){let o=We(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:Fe/1e3},It);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Xe))throw new N(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Xe)}}}s(Jr,"createSupabaseIdempotencyStore");export{S as a,Tt as b,At as c,J as d,Mt as e,Z as f,j as g,et as h,rt as i,ot as j,nt as k,ne as l,Ae as m,ee as n,F as o,X as p,at as q,ct as r,xe as s,dt as t,Oe as u,Er as v,vr as w,N as x,Fe as y,Cr as z,We as A,Ar as B,Hr as C,zr as D,Jr as E};
151
- //# sourceMappingURL=chunk-LJXSA7EP.js.map
151
+ //# sourceMappingURL=chunk-6PXANFSJ.js.map
@@ -0,0 +1,22 @@
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{B as g,a as u,m as w,w as f}from"./chunk-6PXANFSJ.js";import{a as t}from"./chunk-AYY7UXNI.js";function h(r){if(!r?.uid)return"guest";let e=r.token?.role;return e==="super"?"super":e==="admin"?"admin":r.token?.isSuper?"super":r.token?.isAdmin?"admin":"user"}t(h,"getUserRole");function A(r){return{success:!0,data:r}}t(A,"createSuccessResponse");function U(r){if(!r||typeof r!="string")throw new Error("Collection name is required");if(r.includes("/")||r.includes("..")||r.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}t(U,"validateCollectionName");import I from"stripe";var l=null;function v(r){if(!r)throw new Error("Stripe API key is required");let e=process.env.STRIPE_API_VERSION||w;return l=new I(r,{apiVersion:e}),l}t(v,"initStripe");function R(){if(!l){let r=process.env.STRIPE_SECRET_KEY;if(r)v(r);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return l}t(R,"getStripe");var p=new Proxy({},{get(r,e){return R()[e]}});function m(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}t(m,"validateStripeEnvironment");async function z(r,e){m();let o=((await e.getUser(r)).customClaims||{}).subscription,i=o?.subscriptionId;if(!i)throw u(new Error("No active subscription found"));let s=await p.subscriptions.update(i,{cancel_at_period_end:!0}),d=g(["active","canceled","past_due","trialing","incomplete"],s.status)?s.status:"incomplete";return await f(r,{tier:o?.tier||"free",status:d,subscriptionEnd:new Date(s.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:s.id,customerId:s.customer},e),{success:!0,endsAt:new Date(s.current_period_end*1e3).toISOString()}}t(z,"cancelUserSubscription");async function M(r,e,n,S,o){m();let i=S[n];if(!i||i.type!=="StripeSubscription")throw u(new Error("Invalid plan"));if(i.priceId!==e)throw u(new Error("Price ID mismatch with configuration"));let a=((await o.getUser(r)).customClaims||{}).subscription?.subscriptionId;if(!a)throw u(new Error("No active subscription found"));let _=await p.subscriptions.retrieve(a),c=await p.subscriptions.update(a,{items:[{id:_.items.data[0]?.id,price:e}],proration_behavior:"create_prorations"}),b=g(["active","canceled","past_due","trialing","incomplete"],c.status)?c.status:"incomplete";return await f(r,{tier:i.tier,status:b,subscriptionEnd:new Date(c.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:c.cancel_at_period_end,subscriptionId:c.id,customerId:c.customer},o),{success:!0,newTier:i.tier,newPrice:i.price}}t(M,"changeUserPlan");async function W(r,e,n){m();let s=((await e.getUser(r)).customClaims||{}).subscription?.customerId;if(!s)throw u(new Error("No customer found"));if(n){let d=new URL(n),a=new URL(process.env.FRONTEND_URL||"");if(d.origin!==a.origin)throw new Error("Invalid return URL: must match frontend domain")}return{url:(await p.billingPortal.sessions.create({customer:s,return_url:n||`${process.env.FRONTEND_URL}/billing`})).url}}t(W,"createCustomerPortalSession");export{h as a,A as b,U as c,v as d,p as e,m as f,z as g,M as h,W as i};
22
+ //# sourceMappingURL=chunk-CZ5IFNKD.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/shared/utils.ts", "../../src/shared/billing/stripeClient.ts", "../../src/shared/billing/helpers/subscriptionManagement.ts"],
4
+ "sourcesContent": ["// packages/functions/src/shared/utils.ts\n\n/**\n * @fileoverview Shared utilities for Firebase, Vercel and Supabase functions\n * @description Common utilities for every function implementation. Provider-neutral:\n * Supabase Edge Functions import this module, and the edge bundler resolves every\n * import in it (even a lazy `import()` that is never called). Firebase-only code\n * lives under `firebase/`.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n\nimport { DoNotDevError } from '@donotdev/core/server';\nimport type { OAuthPartnerId, UserRole } from '@donotdev/core/server';\n\n// Re-export DoNotDevError for external use\nexport { DoNotDevError };\n\n/**\n * Get user role from Firebase auth context\n *\n * Determines the user's role for visibility filtering based on:\n * - auth.uid: If missing \u2192 'guest'\n * - auth.token.isSuper: If true \u2192 'super'\n * - auth.token.isAdmin: If true \u2192 'admin'\n * - Otherwise \u2192 'user' (authenticated)\n *\n * @param auth - Firebase auth context from callable function\n * @returns UserRole for visibility filtering\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getUserRole(\n auth: { uid?: string; token?: Record<string, unknown> } | null | undefined\n): UserRole {\n if (!auth?.uid) return 'guest';\n\n // Check role claim (standard pattern: auth.token.role = 'admin' | 'super' | etc.)\n const role = auth.token?.role;\n if (role === 'super') return 'super';\n if (role === 'admin') return 'admin';\n\n // Fallback: check legacy boolean flags for backward compatibility\n if (auth.token?.isSuper) return 'super';\n if (auth.token?.isAdmin) return 'admin';\n\n return 'user';\n}\n\n/**\n * Creates a standardized success response\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createSuccessResponse<T>(data: T): { success: true; data: T } {\n return {\n success: true,\n data,\n };\n}\n\n/**\n * Creates a standardized error response\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createErrorResponse(error: unknown): {\n success: false;\n error: {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n };\n} {\n if (error instanceof DoNotDevError) {\n return {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n details: error.details,\n },\n };\n }\n\n if (error instanceof Error) {\n return {\n success: false,\n error: {\n code: 'internal',\n message: error.message,\n },\n };\n }\n\n return {\n success: false,\n error: {\n code: 'internal',\n message: 'An unexpected error occurred',\n },\n };\n}\n\n/**\n * Validates a Firestore collection name from client-supplied schema.\n *\n * W22: Vercel CRUD handlers accept `schema` (including collection name) from\n * the client. This is a known design limitation. As a defense-in-depth measure,\n * reject collection names that could be used for path traversal or access to\n * internal collections.\n *\n * @param name - Collection name to validate\n * @throws Error if the name is unsafe\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateCollectionName(name: string): void {\n if (!name || typeof name !== 'string') {\n throw new Error('Collection name is required');\n }\n if (name.includes('/') || name.includes('..') || name.startsWith('_')) {\n throw new Error(\n 'Invalid collection name: must not contain \"/\", \"..\", or start with \"_\"'\n );\n }\n}\n", "// packages/functions/src/shared/billing/stripeClient.ts\n\n/**\n * @fileoverview Stripe client for billing functions\n * @description Lazily initialized Stripe SDK instance shared by the Firebase,\n * Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so\n * code that does not bill (CRUD, auth) never loads the Stripe SDK.\n *\n * @version 0.2.1\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport Stripe from 'stripe';\n\nimport { STRIPE_API_VERSION_PIN } from './apiVersion.js';\n\n// Lazy initialization of Stripe\nlet _stripe: Stripe | null = null;\n\n/**\n * Initialize Stripe explicitly (e.g. with a secret from defineSecret).\n * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.\n * @param apiKey - Stripe secret key\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function initStripe(apiKey: string) {\n if (!apiKey) throw new Error('Stripe API key is required');\n\n // Unset: the framework pin (pre-basil fields are still read by subscription handlers)\n const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;\n\n _stripe = new Stripe(apiKey, {\n // why: SDK types accept only the latest API version; the pinned/env version is older by design\n apiVersion: apiVersion as Stripe.LatestApiVersion,\n });\n return _stripe;\n}\n\n/**\n * Get Stripe instance with lazy initialization\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getStripe(): Stripe {\n if (!_stripe) {\n // Legacy/Vercel fallback: Try process.env\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (STRIPE_SECRET_KEY) {\n initStripe(STRIPE_SECRET_KEY);\n } else {\n throw new Error(\n 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'\n );\n }\n }\n // We know _stripe is set here or we threw\n return _stripe!;\n}\n\n/**\n * Lazy-initialized Stripe instance proxy\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport const stripe = new Proxy({} as Stripe, {\n get(target, prop) {\n return getStripe()[prop as keyof Stripe];\n },\n});\n\n/**\n * Validates that required Stripe environment variables are set\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripeEnvironment(): void {\n // Functions v2 automatically injects secrets as process.env when declared in config\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (!STRIPE_SECRET_KEY) {\n throw new Error('Missing STRIPE_SECRET_KEY environment variable');\n }\n}\n", "// packages/functions/src/shared/billing/helpers/subscriptionManagement.ts\n\n/**\n * @fileoverview Shared Subscription Management Logic\n * @description Platform-agnostic subscription management functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport { SUBSCRIPTION_STATUS } from '@donotdev/core/server';\nimport type {\n BillingAuthProvider,\n StripeBackConfig,\n} from '@donotdev/core/server';\n\nimport { updateUserSubscription } from './updateUserSubscription.js';\nimport { handleError } from '../../errorHandling.js';\nimport { stripe, validateStripeEnvironment } from '../stripeClient.js';\nimport { isOneOf, pinnedSubscriptionPeriod } from '../stripePinned.js';\n\n/**\n * Cancel user subscription at period end\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n userId: string,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; endsAt: string }> {\n validateStripeEnvironment();\n\n // Get user's current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string; tier?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Cancel at period end (don't delete immediately)\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n cancel_at_period_end: true,\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = isOneOf(validStatuses, updatedSubscription.status)\n ? updatedSubscription.status\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: subscription?.tier || 'free',\n status,\n subscriptionEnd: new Date(\n pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: true,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n endsAt: new Date(\n pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000\n ).toISOString(),\n };\n}\n\n/**\n * Change user subscription plan\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function changeUserPlan(\n userId: string,\n newPriceId: string,\n billingConfigKey: string,\n billingConfig: StripeBackConfig,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; newTier: string; newPrice: number }> {\n validateStripeEnvironment();\n\n // Validate new plan exists in config\n const billingItem = billingConfig[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') {\n throw handleError(new Error('Invalid plan'));\n }\n\n // Validate price ID matches config\n if (billingItem.priceId !== newPriceId) {\n throw handleError(new Error('Price ID mismatch with configuration'));\n }\n\n // Get current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Get current subscription from Stripe\n const currentSubscription = (await stripe.subscriptions.retrieve(\n subscriptionId\n )) as Stripe.Subscription;\n\n // Update subscription in Stripe\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n items: [\n {\n id: currentSubscription.items.data[0]?.id,\n price: newPriceId,\n },\n ],\n proration_behavior: 'create_prorations', // Pro-rate the change\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = isOneOf(validStatuses, updatedSubscription.status)\n ? updatedSubscription.status\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: billingItem.tier,\n status,\n subscriptionEnd: new Date(\n pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n newTier: billingItem.tier,\n newPrice: billingItem.price,\n };\n}\n\n/**\n * Create Stripe Customer Portal session\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function createCustomerPortalSession(\n userId: string,\n authProvider: BillingAuthProvider,\n returnUrl?: string\n): Promise<{ url: string }> {\n validateStripeEnvironment();\n\n // Get customer ID from user claims\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { customerId?: string }\n | undefined;\n const customerId = subscription?.customerId;\n\n if (!customerId) {\n throw handleError(new Error('No customer found'));\n }\n\n // Validate returnUrl domain\n if (returnUrl) {\n const parsed = new URL(returnUrl);\n const frontendUrl = new URL(process.env.FRONTEND_URL || '');\n if (parsed.origin !== frontendUrl.origin) {\n throw new Error('Invalid return URL: must match frontend domain');\n }\n }\n\n // Create portal session\n const session = await stripe.billingPortal.sessions.create({\n customer: customerId,\n return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,\n });\n\n return {\n url: session.url,\n };\n}\n"],
5
+ "mappings": "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",
6
+ "names": ["getUserRole", "auth", "role", "__name", "createSuccessResponse", "data", "validateCollectionName", "name", "__name", "Stripe", "_stripe", "initStripe", "apiKey", "apiVersion", "STRIPE_API_VERSION_PIN", "Stripe", "__name", "getStripe", "STRIPE_SECRET_KEY", "stripe", "target", "prop", "validateStripeEnvironment", "cancelUserSubscription", "userId", "authProvider", "validateStripeEnvironment", "subscription", "subscriptionId", "handleError", "updatedSubscription", "stripe", "status", "isOneOf", "updateUserSubscription", "__name", "changeUserPlan", "newPriceId", "billingConfigKey", "billingConfig", "billingItem", "currentSubscription", "createCustomerPortalSession", "returnUrl", "customerId", "parsed", "frontendUrl"]
7
+ }