@lunora/payment 1.0.0-alpha.97 → 1.0.0-alpha.98

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/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-DyCsry1Q.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-5WkBd3aZ.mjs";import{createPayment as y}from"./packem_shared/createPayment-Dmh6IWLZ.mjs";import{createDatabasePaymentStore as p}from"./packem_shared/createDatabasePaymentStore-CVrAhWjP.mjs";import{entitlementsForReference as s,featureNames as c,hasActivePrice as x,resolveEntitlements as S,usagePeriodStart as l}from"./packem_shared/entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as T}from"./packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as P}from"./packem_shared/idempotencyKey-BjxjMMna.mjs";import{addMoney as d,allocateMoney as A,compareMoney as E,formatMoney as N,fromMoneyJSON as h,isZeroDecimalCurrency as R,isZeroMoney as v,money as C,subtractMoney as D,toMoneyJSON as I,zeroMoney as _}from"./packem_shared/addMoney-B4ufWAnD.mjs";import{reconcile as L}from"./packem_shared/reconcile-Cm45pURT.mjs";import{default as k}from"./packem_shared/paymentTables-Be-_11ux.mjs";import{PAYMENT_TERMINAL_STATES as J,SUBSCRIPTION_TERMINAL_STATES as W,canTransitionPayment as Z,canTransitionSubscription as q,nextPaymentState as z,nextSubscriptionState as B}from"./packem_shared/PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";import{MemoryPaymentStore as K}from"./packem_shared/MemoryPaymentStore-Cu9J-zf9.mjs";import{default as Y}from"./packem_shared/applyWebhookAction-daHKTG_Q.mjs";import{constantTimeEqual as w,hmacSha256Hex as G,verifyCreemSignature as Q,verifyStandardWebhook as V}from"./packem_shared/constantTimeEqual-Bj5tU-zT.mjs";export{T as LunoraPaymentError,K as MemoryPaymentStore,J as PAYMENT_TERMINAL_STATES,W as SUBSCRIPTION_TERMINAL_STATES,d as addMoney,A as allocateMoney,Y as applyWebhookAction,Z as canTransitionPayment,q as canTransitionSubscription,E as compareMoney,w as constantTimeEqual,r as createAdapterRegistry,p as createDatabasePaymentStore,y as createPayment,s as entitlementsForReference,c as featureNames,N as formatMoney,h as fromMoneyJSON,x as hasActivePrice,G as hmacSha256Hex,P as idempotencyKey,R as isZeroDecimalCurrency,v as isZeroMoney,a as lunoraDatabaseToPaymentDatabase,C as money,z as nextPaymentState,B as nextSubscriptionState,k as paymentTables,n as paymentsFromContext,L as reconcile,S as resolveEntitlements,D as subtractMoney,I as toMoneyJSON,l as usagePeriodStart,Q as verifyCreemSignature,V as verifyStandardWebhook,_ as zeroMoney};
1
+ import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-DyCsry1Q.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-5WkBd3aZ.mjs";import{createPayment as y}from"./packem_shared/createPayment-Dmh6IWLZ.mjs";import{createDatabasePaymentStore as p}from"./packem_shared/createDatabasePaymentStore-CVrAhWjP.mjs";import{entitlementsForReference as s,featureNames as c,hasActivePrice as x,resolveEntitlements as S,usagePeriodStart as l}from"./packem_shared/entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as T}from"./packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as P}from"./packem_shared/idempotencyKey-BjxjMMna.mjs";import{addMoney as d,allocateMoney as A,compareMoney as E,formatMoney as N,fromMoneyJSON as h,isZeroDecimalCurrency as R,isZeroMoney as v,money as C,subtractMoney as D,toMoneyJSON as I,zeroMoney as _}from"./packem_shared/addMoney-B4ufWAnD.mjs";import{reconcile as L}from"./packem_shared/reconcile-Cm45pURT.mjs";import{default as k}from"./packem_shared/paymentTables-Be-_11ux.mjs";import{PAYMENT_TERMINAL_STATES as J,SUBSCRIPTION_TERMINAL_STATES as W,canTransitionPayment as Z,canTransitionSubscription as q,nextPaymentState as z,nextSubscriptionState as B}from"./packem_shared/PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";import{MemoryPaymentStore as K}from"./packem_shared/MemoryPaymentStore-Cu9J-zf9.mjs";import{default as Y}from"./packem_shared/applyWebhookAction-daHKTG_Q.mjs";import{constantTimeEqual as w,hmacSha256Hex as G,verifyCreemSignature as Q,verifyStandardWebhook as V}from"./packem_shared/constantTimeEqual-D_ynru-O.mjs";export{T as LunoraPaymentError,K as MemoryPaymentStore,J as PAYMENT_TERMINAL_STATES,W as SUBSCRIPTION_TERMINAL_STATES,d as addMoney,A as allocateMoney,Y as applyWebhookAction,Z as canTransitionPayment,q as canTransitionSubscription,E as compareMoney,w as constantTimeEqual,r as createAdapterRegistry,p as createDatabasePaymentStore,y as createPayment,s as entitlementsForReference,c as featureNames,N as formatMoney,h as fromMoneyJSON,x as hasActivePrice,G as hmacSha256Hex,P as idempotencyKey,R as isZeroDecimalCurrency,v as isZeroMoney,a as lunoraDatabaseToPaymentDatabase,C as money,z as nextPaymentState,B as nextSubscriptionState,k as paymentTables,n as paymentsFromContext,L as reconcile,S as resolveEntitlements,D as subtractMoney,I as toMoneyJSON,l as usagePeriodStart,Q as verifyCreemSignature,V as verifyStandardWebhook,_ as zeroMoney};
@@ -0,0 +1 @@
1
+ import{LunoraPaymentError as s}from"./LunoraPaymentError-BSxyhWgu.mjs";const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},l=e=>{const t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)n[o]=t.codePointAt(o)??0;return n},I=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let r=0;r<n;r+=1){const a=r<e.length?e.charCodeAt(r):0,i=r<t.length?t.charCodeAt(r):0;o|=a^i}return o===0},h=new TextEncoder,f=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),d="whsec_",A=async(e,t)=>{const n=await crypto.subtle.importKey("raw",e,{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,h.encode(t));return m(new Uint8Array(o))},g=I,y=async(e,t)=>{const n=await crypto.subtle.importKey("raw",h.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,h.encode(t));return f(o)},u=async e=>{if(!e.secret)throw new s("CONFIG_INVALID","webhook secret not configured");const t=e.toleranceSeconds??300,n=e.now??Date.now(),o=Number(e.webhookTimestamp);if(!e.webhookId||!e.webhookSignature||!Number.isFinite(o))throw new s("WEBHOOK_SIGNATURE_INVALID","missing standard-webhooks headers");if(Math.abs(Math.floor(n/1e3)-o)>t)throw new s("WEBHOOK_TIMESTAMP_INVALID","signature timestamp outside tolerance");const r=e.secret.startsWith(d)?e.secret.slice(d.length):e.secret;if(!r)throw new s("CONFIG_INVALID","webhook secret not configured");const a=l(r);if(a.length===0)throw new s("CONFIG_INVALID","webhook secret not configured");const i=await A(a,`${e.webhookId}.${e.webhookTimestamp}.${e.payload}`);if(!e.webhookSignature.split(" ").map(c=>{const w=c.indexOf(",");return w===-1?"":c.slice(w+1)}).filter(Boolean).some(c=>g(c,i)))throw new s("WEBHOOK_SIGNATURE_INVALID","no matching signature")},N=async e=>{if(!e.secret)throw new s("CONFIG_INVALID","webhook secret not configured");if(!e.signature)throw new s("WEBHOOK_SIGNATURE_INVALID","missing creem-signature header");const t=await y(e.secret,e.payload);if(!g(e.signature,t))throw new s("WEBHOOK_SIGNATURE_INVALID","no matching signature")};export{g as constantTimeEqual,y as hmacSha256Hex,N as verifyCreemSignature,u as verifyStandardWebhook};
@@ -1 +1 @@
1
- import{LunoraPaymentError as O}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{a as i,r as x,c as o,d as p,e as u}from"../packem_shared/json-BJJPJVYj.mjs";import{money as h}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as C}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as D}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as E}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={active:"active",canceled:"canceled",expired:"canceled",past_due:"past_due",scheduled:"paused",trialing:"trialing"},N={activated:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",scheduled:"paused"},w="::",y=D("autumn"),f=(a,c)=>`${a}${w}${c}`,g=a=>{const c=a.lastIndexOf(w);if(c===-1)throw new O("PROVIDER_ERROR",`malformed autumn subscription id "${a}" (expected "<customerId>::<productId>")`);return{customerId:a.slice(0,c),productId:a.slice(c+w.length)}},A=a=>u(a,"canceled_at","canceledAt")!==void 0||o(a,"status")==="scheduled",k=(a,c)=>{const r=Date.now(),e=o(c,"id","product_id","productId","plan_id","planId")??"",n=o(c,"status")??"active",t=p(c,"past_due")??p(c,"pastDue")??!1;return{cancelAtPeriodEnd:A(c),createdAt:r,currentPeriodEnd:u(c,"current_period_end","currentPeriodEnd")??void 0,currentPeriodStart:u(c,"current_period_start","currentPeriodStart")??void 0,id:f(a,e),priceId:e,provider:"autumn",quantity:u(c,"quantity")??1,referenceId:a,state:t?"past_due":P[n]??"past_due",updatedAt:r}},S=a=>Array.isArray(a)?a.map(c=>i(c)):[],T=(a,c)=>[...S(a.products),...S(a.subscriptions)].find(e=>(o(e,"id","product_id","productId","plan_id","planId")??"")===c),b=a=>({balance:u(a,"remaining","balance"),limit:u(a,"granted","included_usage","limit"),unlimited:p(a,"unlimited")??!1,used:u(a,"usage","used")}),R=(a,c,r,e)=>{const n=Date.now();return{cancelAtPeriodEnd:e,createdAt:n,id:f(a,c),priceId:c,provider:"autumn",quantity:1,referenceId:a,state:r,updatedAt:n}},v=async(a,c,r)=>{const e=i(await a.customers.get({customerId:c})),n=T(e,r);return n?k(c,n):R(c,r,"canceled",!1)},I=a=>o(a,"customer_id","customerId"),q=(a,c)=>{const r={eventId:a,provider:"autumn",raw:{object:c,type:"billing.updated"}},e=I(c),n=S(c.plan_changes)[0]??c,t=n.subscription?i(n.subscription):n,d=o(t,"plan_id","planId","product_id","productId","id"),s=o(t,"status"),m=o(n,"action"),l=p(t,"past_due")??p(t,"pastDue")??!1,_=s===void 0?void 0:P[s],U=m===void 0?void 0:N[m],B=l?"past_due":_??U;return{...r,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:e,priceId:d,referenceId:e,subscriptionId:e===void 0||d===void 0?void 0:f(e,d),type:E(B)}},M=(a,c,r)=>{const e={eventId:a,provider:"autumn",raw:{object:r,type:c}},n=o(r,"currency")??"usd";switch(c){case"billing.auto_topup_succeeded":{const t=i(r.invoice),d=u(t,"total","amount")??u(r,"total","amount"),s=o(t,"currency")??n;return{...e,amount:d===void 0?void 0:h(BigInt(Math.round(d)),s),customerId:I(r),referenceId:I(r),sessionId:o(t,"id","stripe_id","invoice_id")??o(r,"id"),type:"payment.captured"}}case"billing.updated":return q(a,r);case"customer.product.added":case"customer.product.canceled":case"customer.product.expired":case"customer.product.updated":case"product.attached":{const t=r.product?i(r.product):r,d=c==="customer.product.canceled"||c==="customer.product.expired"?"canceled":o(t,"status"),s=I(r)??I(t);return{...e,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:s,priceId:o(t,"id","product_id","productId"),referenceId:s,subscriptionId:s===void 0?void 0:f(s,o(t,"id","product_id","productId")??""),type:E(P[d??""]??"past_due")}}case"invoice.paid":case"payment.succeeded":{const t=u(r,"total","amount","amount_paid");return{...e,amount:t===void 0?void 0:h(BigInt(Math.round(t)),n),customerId:I(r),referenceId:I(r),sessionId:o(r,"id","invoice_id","stripe_id"),type:"payment.captured"}}default:return{...e,type:"unhandled"}}},$=a=>o(a,"checkout_url","checkoutUrl","payment_url","paymentUrl","url")??"",z=a=>{const{webhookSecret:c}=a,r=a.client;return{cancelPayment:()=>y("manual payment cancellation"),cancelSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e);return await r.billing.update({cancelAction:n?.atPeriodEnd?"cancel_end_of_cycle":"cancel_immediately",customerId:t,planId:d}),n?.atPeriodEnd?{...await v(r,t,d),cancelAtPeriodEnd:!0}:R(t,d,"canceled",!1)},capabilities:{merchantOfRecord:!1,portal:!0,usageMetering:!0},capturePayment:e=>y("manual capture"),checkEntitlement:async e=>{if(e.featureId===void 0){const m=i(await r.customers.get({customerId:e.referenceId})),l=T(m,e.priceId??""),_=l?k(e.referenceId,l).state:void 0;return{allowed:_==="active"||_==="trialing",unlimited:!1}}const n=i(await r.check({customerId:e.referenceId,featureId:e.featureId,requiredBalance:e.quantity??1})),t=p(n,"allowed")??!1,d=n.balance,s=typeof d=="object"&&d!==null?i(d):n;return{allowed:t,...b(s)}},createCheckout:async e=>{const n=i(await r.billing.attach({customerId:e.referenceId,planId:e.priceId}));return{id:f(e.referenceId,e.priceId),provider:"autumn",url:$(n)}},createPortalSession:async e=>{const n=i(await r.billing.openCustomerPortal({customerId:e.customerId}));return{url:o(n,"url")??""}},getBalances:async e=>{const n=i(await r.customers.get({customerId:e})),t=i(n.balances??n.features);return Object.entries(t).map(([d,s])=>{const m=i(s),l=b(m);return{allowed:l.unlimited||(l.balance??0)>0,featureId:o(m,"featureId","feature_id")??d,...l}})},getOrCreateCustomer:async e=>{const n=i(await r.customers.getOrCreate({customerId:e.referenceId,email:e.email,name:e.metadata?.name}));return{createdAt:Date.now(),email:o(n,"email")??e.email,id:o(n,"id")??e.referenceId,provider:"autumn",referenceId:e.referenceId}},getPaymentStatus:()=>y("payment-session reconciliation"),getSubscriptionStatus:async e=>{const{customerId:n,productId:t}=g(e);return v(r,n,t)},identifier:"autumn",parseWebhook:async({headers:e,payload:n})=>{const t=e.get("svix-id")??e.get("webhook-id")??"";await C({payload:n,secret:c,toleranceSeconds:a.webhookToleranceSeconds,webhookId:t,webhookSignature:e.get("svix-signature")??e.get("webhook-signature")??"",webhookTimestamp:e.get("svix-timestamp")??e.get("webhook-timestamp")??""});const d=i(JSON.parse(n));return M(t,x(d,"type")??"",i(d.data))},refundPayment:()=>y("refunds"),reportUsage:async e=>{await r.track({customerId:e.referenceId,featureId:e.featureId,value:e.quantity})},resumeSubscription:async e=>{const{customerId:n,productId:t}=g(e);return await r.billing.update({cancelAction:"uncancel",customerId:n,planId:t}),{...await v(r,n,t),cancelAtPeriodEnd:!1}},updateSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e),s=n.priceId??d;return await r.billing.attach({customerId:t,planId:s}),v(r,t,s)}}};export{z as createAutumnAdapter};
1
+ import{LunoraPaymentError as O}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{a as i,r as x,c as o,d as p,e as u}from"../packem_shared/json-BJJPJVYj.mjs";import{money as h}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as C}from"../packem_shared/constantTimeEqual-D_ynru-O.mjs";import{m as D}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as E}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={active:"active",canceled:"canceled",expired:"canceled",past_due:"past_due",scheduled:"paused",trialing:"trialing"},N={activated:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",scheduled:"paused"},w="::",y=D("autumn"),f=(a,c)=>`${a}${w}${c}`,g=a=>{const c=a.lastIndexOf(w);if(c===-1)throw new O("PROVIDER_ERROR",`malformed autumn subscription id "${a}" (expected "<customerId>::<productId>")`);return{customerId:a.slice(0,c),productId:a.slice(c+w.length)}},A=a=>u(a,"canceled_at","canceledAt")!==void 0||o(a,"status")==="scheduled",k=(a,c)=>{const r=Date.now(),e=o(c,"id","product_id","productId","plan_id","planId")??"",n=o(c,"status")??"active",t=p(c,"past_due")??p(c,"pastDue")??!1;return{cancelAtPeriodEnd:A(c),createdAt:r,currentPeriodEnd:u(c,"current_period_end","currentPeriodEnd")??void 0,currentPeriodStart:u(c,"current_period_start","currentPeriodStart")??void 0,id:f(a,e),priceId:e,provider:"autumn",quantity:u(c,"quantity")??1,referenceId:a,state:t?"past_due":P[n]??"past_due",updatedAt:r}},S=a=>Array.isArray(a)?a.map(c=>i(c)):[],T=(a,c)=>[...S(a.products),...S(a.subscriptions)].find(e=>(o(e,"id","product_id","productId","plan_id","planId")??"")===c),b=a=>({balance:u(a,"remaining","balance"),limit:u(a,"granted","included_usage","limit"),unlimited:p(a,"unlimited")??!1,used:u(a,"usage","used")}),R=(a,c,r,e)=>{const n=Date.now();return{cancelAtPeriodEnd:e,createdAt:n,id:f(a,c),priceId:c,provider:"autumn",quantity:1,referenceId:a,state:r,updatedAt:n}},v=async(a,c,r)=>{const e=i(await a.customers.get({customerId:c})),n=T(e,r);return n?k(c,n):R(c,r,"canceled",!1)},I=a=>o(a,"customer_id","customerId"),q=(a,c)=>{const r={eventId:a,provider:"autumn",raw:{object:c,type:"billing.updated"}},e=I(c),n=S(c.plan_changes)[0]??c,t=n.subscription?i(n.subscription):n,d=o(t,"plan_id","planId","product_id","productId","id"),s=o(t,"status"),m=o(n,"action"),l=p(t,"past_due")??p(t,"pastDue")??!1,_=s===void 0?void 0:P[s],U=m===void 0?void 0:N[m],B=l?"past_due":_??U;return{...r,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:e,priceId:d,referenceId:e,subscriptionId:e===void 0||d===void 0?void 0:f(e,d),type:E(B)}},M=(a,c,r)=>{const e={eventId:a,provider:"autumn",raw:{object:r,type:c}},n=o(r,"currency")??"usd";switch(c){case"billing.auto_topup_succeeded":{const t=i(r.invoice),d=u(t,"total","amount")??u(r,"total","amount"),s=o(t,"currency")??n;return{...e,amount:d===void 0?void 0:h(BigInt(Math.round(d)),s),customerId:I(r),referenceId:I(r),sessionId:o(t,"id","stripe_id","invoice_id")??o(r,"id"),type:"payment.captured"}}case"billing.updated":return q(a,r);case"customer.product.added":case"customer.product.canceled":case"customer.product.expired":case"customer.product.updated":case"product.attached":{const t=r.product?i(r.product):r,d=c==="customer.product.canceled"||c==="customer.product.expired"?"canceled":o(t,"status"),s=I(r)??I(t);return{...e,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:s,priceId:o(t,"id","product_id","productId"),referenceId:s,subscriptionId:s===void 0?void 0:f(s,o(t,"id","product_id","productId")??""),type:E(P[d??""]??"past_due")}}case"invoice.paid":case"payment.succeeded":{const t=u(r,"total","amount","amount_paid");return{...e,amount:t===void 0?void 0:h(BigInt(Math.round(t)),n),customerId:I(r),referenceId:I(r),sessionId:o(r,"id","invoice_id","stripe_id"),type:"payment.captured"}}default:return{...e,type:"unhandled"}}},$=a=>o(a,"checkout_url","checkoutUrl","payment_url","paymentUrl","url")??"",z=a=>{const{webhookSecret:c}=a,r=a.client;return{cancelPayment:()=>y("manual payment cancellation"),cancelSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e);return await r.billing.update({cancelAction:n?.atPeriodEnd?"cancel_end_of_cycle":"cancel_immediately",customerId:t,planId:d}),n?.atPeriodEnd?{...await v(r,t,d),cancelAtPeriodEnd:!0}:R(t,d,"canceled",!1)},capabilities:{merchantOfRecord:!1,portal:!0,usageMetering:!0},capturePayment:e=>y("manual capture"),checkEntitlement:async e=>{if(e.featureId===void 0){const m=i(await r.customers.get({customerId:e.referenceId})),l=T(m,e.priceId??""),_=l?k(e.referenceId,l).state:void 0;return{allowed:_==="active"||_==="trialing",unlimited:!1}}const n=i(await r.check({customerId:e.referenceId,featureId:e.featureId,requiredBalance:e.quantity??1})),t=p(n,"allowed")??!1,d=n.balance,s=typeof d=="object"&&d!==null?i(d):n;return{allowed:t,...b(s)}},createCheckout:async e=>{const n=i(await r.billing.attach({customerId:e.referenceId,planId:e.priceId}));return{id:f(e.referenceId,e.priceId),provider:"autumn",url:$(n)}},createPortalSession:async e=>{const n=i(await r.billing.openCustomerPortal({customerId:e.customerId}));return{url:o(n,"url")??""}},getBalances:async e=>{const n=i(await r.customers.get({customerId:e})),t=i(n.balances??n.features);return Object.entries(t).map(([d,s])=>{const m=i(s),l=b(m);return{allowed:l.unlimited||(l.balance??0)>0,featureId:o(m,"featureId","feature_id")??d,...l}})},getOrCreateCustomer:async e=>{const n=i(await r.customers.getOrCreate({customerId:e.referenceId,email:e.email,name:e.metadata?.name}));return{createdAt:Date.now(),email:o(n,"email")??e.email,id:o(n,"id")??e.referenceId,provider:"autumn",referenceId:e.referenceId}},getPaymentStatus:()=>y("payment-session reconciliation"),getSubscriptionStatus:async e=>{const{customerId:n,productId:t}=g(e);return v(r,n,t)},identifier:"autumn",parseWebhook:async({headers:e,payload:n})=>{const t=e.get("svix-id")??e.get("webhook-id")??"";await C({payload:n,secret:c,toleranceSeconds:a.webhookToleranceSeconds,webhookId:t,webhookSignature:e.get("svix-signature")??e.get("webhook-signature")??"",webhookTimestamp:e.get("svix-timestamp")??e.get("webhook-timestamp")??""});const d=i(JSON.parse(n));return M(t,x(d,"type")??"",i(d.data))},refundPayment:()=>y("refunds"),reportUsage:async e=>{await r.track({customerId:e.referenceId,featureId:e.featureId,value:e.quantity})},resumeSubscription:async e=>{const{customerId:n,productId:t}=g(e);return await r.billing.update({cancelAction:"uncancel",customerId:n,planId:t}),{...await v(r,n,t),cancelAtPeriodEnd:!1}},updateSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e),s=n.priceId??d;return await r.billing.attach({customerId:t,planId:s}),v(r,t,s)}}};export{z as createAutumnAdapter};
@@ -1 +1 @@
1
- import{a as o,c as u,f as m,r as c,b as p,p as f,d as v,e as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as I,zeroMoney as g}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyCreemSignature as A}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as E}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as P}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const k=/already exists/iu,C={canceled:"canceled",completed:"captured",expired:"canceled",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded"},h={active:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",incomplete:"past_due",paid:"active",past_due:"past_due",paused:"paused",scheduled_cancel:"active",trialing:"trialing",unpaid:"past_due"},_=E("creem (merchant-of-record)"),i=a=>typeof a=="string"?a:c(o(a),"id"),T=a=>u(a,"checkout_url","checkoutUrl")??"",S=a=>u(a,"canceled_at","canceledAt")!==void 0||c(a,"status")==="scheduled_cancel",b=a=>{if(!(a instanceof Error))return!1;const{statusCode:r}=a;return typeof r=="number"&&r!==400&&r!==409?!1:k.test(a.message)},l=a=>{const r=o(a),t=Date.now(),e=c(r,"status")??"";return{cancelAtPeriodEnd:S(r),createdAt:t,currentPeriodEnd:f(u(r,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(r,"current_period_start_date","currentPeriodStartDate")),id:c(r,"id")??"",priceId:i(r.product)??"",provider:"creem",quantity:p(r,"units")??1,referenceId:m(r)??i(r.customer)??"",state:h[e]??"past_due",updatedAt:t}},B=a=>{const r=o(a),t=Date.now(),e=o(r.order),n=c(e,"currency")??c(r,"currency")??"usd",s=I(BigInt(Math.round(p(e,"amount")??p(r,"amount")??0)),n),d=C[c(e,"status")??c(r,"status")??""]??"initiated";return{amount:s,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?s:g(n),createdAt:t,id:c(r,"id")??"",provider:"creem",referenceId:m(r)??"",refundedAmount:d==="refunded"?s:g(n),state:d,updatedAt:t}},D=(a,r,t)=>{const e={eventId:a,provider:"creem",raw:{object:t,type:r}},n=o(t.order),s=c(n,"currency")??c(t,"currency")??"usd";switch(r){case"checkout.completed":{const d=p(n,"amount")??p(t,"amount");return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),s),customerId:i(t.customer),referenceId:m(t),sessionId:c(t,"id"),subscriptionId:i(t.subscription),type:"payment.captured"}}case"refund.created":{const d=w(t,"refund_amount","refundAmount","amount")??p(n,"amount"),y=u(t,"refund_currency","refundCurrency")??s;return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),y),referenceId:m(t),sessionId:i(t.transaction)??i(t.subscription)??i(t.order)??i(t.checkout)??c(t,"id"),type:"payment.refunded"}}case"subscription.active":case"subscription.canceled":case"subscription.expired":case"subscription.paid":case"subscription.past_due":case"subscription.paused":case"subscription.scheduled_cancel":case"subscription.trialing":case"subscription.unpaid":case"subscription.update":{const d=r==="subscription.scheduled_cancel"?"scheduled_cancel":c(t,"status");return{...e,cancelAtPeriodEnd:v(t,"cancel_at_period_end")??S(t),currentPeriodEnd:f(u(t,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(t,"current_period_start_date","currentPeriodStartDate")),customerId:i(t.customer),priceId:i(t.product),referenceId:m(t)??i(t.customer),subscriptionId:c(t,"id"),type:P(h[d??""]??"past_due")}}default:return{...e,type:"unhandled"}}},O=a=>{const{webhookSecret:r}=a,t=a.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,n)=>l(await t.subscriptions.cancel(e,{mode:n?.atPeriodEnd===!0?"scheduled":"immediate"})),capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!1},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const n=await t.checkouts.create({customer:e.customerId?{id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},productId:e.priceId,requestId:e.idempotencyKey,successUrl:e.successUrl,units:e.quantity});return{id:c(n,"id")??"",provider:"creem",url:T(n)}},createPortalSession:async e=>{const n=await t.customers.generateBillingLinks({customerId:e.customerId});return{url:u(n,"customer_portal_link","customerPortalLink")??""}},getOrCreateCustomer:async e=>{const n=s=>({createdAt:Date.now(),email:c(s,"email")??e.email,id:c(s,"id")??"",provider:"creem",referenceId:e.referenceId});try{return n(o(await t.customers.create({email:e.email??"",metadata:{...e.metadata,referenceId:e.referenceId},name:e.metadata?.name??e.referenceId})))}catch(s){if(e.email!==void 0&&b(s)){const d=o(await t.customers.retrieve(void 0,e.email));if(m(d)!==e.referenceId)throw new Error(`Creem customer for email "${e.email}" already belongs to a different reference; refusing to bind it to "${e.referenceId}".`,{cause:s});return n(d)}throw s}},getPaymentStatus:async e=>B(await t.checkouts.retrieve(e)),getSubscriptionStatus:async e=>l(await t.subscriptions.get(e)),identifier:"creem",parseWebhook:async({headers:e,payload:n})=>{await A({payload:n,secret:r,signature:e.get("creem-signature")??""});const s=o(JSON.parse(n));return D(u(s,"id","event_id","eventId")??"",u(s,"eventType","type")??"",o(s.object))},refundPayment:()=>_("programmatic refunds"),resumeSubscription:async e=>l(await t.subscriptions.resume(e)),updateSubscription:async(e,n)=>n.priceId?l(await t.subscriptions.upgrade(e,{productId:n.priceId,updateBehavior:"proration-charge-immediately"})):l(await t.subscriptions.get(e))}};export{O as createCreemAdapter};
1
+ import{a as o,c as u,f as m,r as c,b as p,p as f,d as v,e as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as I,zeroMoney as g}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyCreemSignature as A}from"../packem_shared/constantTimeEqual-D_ynru-O.mjs";import{m as E}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as P}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const k=/already exists/iu,C={canceled:"canceled",completed:"captured",expired:"canceled",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded"},h={active:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",incomplete:"past_due",paid:"active",past_due:"past_due",paused:"paused",scheduled_cancel:"active",trialing:"trialing",unpaid:"past_due"},_=E("creem (merchant-of-record)"),i=a=>typeof a=="string"?a:c(o(a),"id"),T=a=>u(a,"checkout_url","checkoutUrl")??"",S=a=>u(a,"canceled_at","canceledAt")!==void 0||c(a,"status")==="scheduled_cancel",b=a=>{if(!(a instanceof Error))return!1;const{statusCode:r}=a;return typeof r=="number"&&r!==400&&r!==409?!1:k.test(a.message)},l=a=>{const r=o(a),t=Date.now(),e=c(r,"status")??"";return{cancelAtPeriodEnd:S(r),createdAt:t,currentPeriodEnd:f(u(r,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(r,"current_period_start_date","currentPeriodStartDate")),id:c(r,"id")??"",priceId:i(r.product)??"",provider:"creem",quantity:p(r,"units")??1,referenceId:m(r)??i(r.customer)??"",state:h[e]??"past_due",updatedAt:t}},B=a=>{const r=o(a),t=Date.now(),e=o(r.order),n=c(e,"currency")??c(r,"currency")??"usd",s=I(BigInt(Math.round(p(e,"amount")??p(r,"amount")??0)),n),d=C[c(e,"status")??c(r,"status")??""]??"initiated";return{amount:s,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?s:g(n),createdAt:t,id:c(r,"id")??"",provider:"creem",referenceId:m(r)??"",refundedAmount:d==="refunded"?s:g(n),state:d,updatedAt:t}},D=(a,r,t)=>{const e={eventId:a,provider:"creem",raw:{object:t,type:r}},n=o(t.order),s=c(n,"currency")??c(t,"currency")??"usd";switch(r){case"checkout.completed":{const d=p(n,"amount")??p(t,"amount");return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),s),customerId:i(t.customer),referenceId:m(t),sessionId:c(t,"id"),subscriptionId:i(t.subscription),type:"payment.captured"}}case"refund.created":{const d=w(t,"refund_amount","refundAmount","amount")??p(n,"amount"),y=u(t,"refund_currency","refundCurrency")??s;return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),y),referenceId:m(t),sessionId:i(t.transaction)??i(t.subscription)??i(t.order)??i(t.checkout)??c(t,"id"),type:"payment.refunded"}}case"subscription.active":case"subscription.canceled":case"subscription.expired":case"subscription.paid":case"subscription.past_due":case"subscription.paused":case"subscription.scheduled_cancel":case"subscription.trialing":case"subscription.unpaid":case"subscription.update":{const d=r==="subscription.scheduled_cancel"?"scheduled_cancel":c(t,"status");return{...e,cancelAtPeriodEnd:v(t,"cancel_at_period_end")??S(t),currentPeriodEnd:f(u(t,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(t,"current_period_start_date","currentPeriodStartDate")),customerId:i(t.customer),priceId:i(t.product),referenceId:m(t)??i(t.customer),subscriptionId:c(t,"id"),type:P(h[d??""]??"past_due")}}default:return{...e,type:"unhandled"}}},O=a=>{const{webhookSecret:r}=a,t=a.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,n)=>l(await t.subscriptions.cancel(e,{mode:n?.atPeriodEnd===!0?"scheduled":"immediate"})),capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!1},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const n=await t.checkouts.create({customer:e.customerId?{id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},productId:e.priceId,requestId:e.idempotencyKey,successUrl:e.successUrl,units:e.quantity});return{id:c(n,"id")??"",provider:"creem",url:T(n)}},createPortalSession:async e=>{const n=await t.customers.generateBillingLinks({customerId:e.customerId});return{url:u(n,"customer_portal_link","customerPortalLink")??""}},getOrCreateCustomer:async e=>{const n=s=>({createdAt:Date.now(),email:c(s,"email")??e.email,id:c(s,"id")??"",provider:"creem",referenceId:e.referenceId});try{return n(o(await t.customers.create({email:e.email??"",metadata:{...e.metadata,referenceId:e.referenceId},name:e.metadata?.name??e.referenceId})))}catch(s){if(e.email!==void 0&&b(s)){const d=o(await t.customers.retrieve(void 0,e.email));if(m(d)!==e.referenceId)throw new Error(`Creem customer for email "${e.email}" already belongs to a different reference; refusing to bind it to "${e.referenceId}".`,{cause:s});return n(d)}throw s}},getPaymentStatus:async e=>B(await t.checkouts.retrieve(e)),getSubscriptionStatus:async e=>l(await t.subscriptions.get(e)),identifier:"creem",parseWebhook:async({headers:e,payload:n})=>{await A({payload:n,secret:r,signature:e.get("creem-signature")??""});const s=o(JSON.parse(n));return D(u(s,"id","event_id","eventId")??"",u(s,"eventType","type")??"",o(s.object))},refundPayment:()=>_("programmatic refunds"),resumeSubscription:async e=>l(await t.subscriptions.resume(e)),updateSubscription:async(e,n)=>n.priceId?l(await t.subscriptions.upgrade(e,{productId:n.priceId,updateBehavior:"proration-charge-immediately"})):l(await t.subscriptions.get(e))}};export{O as createCreemAdapter};
@@ -1 +1 @@
1
- import{LunoraPaymentError as v}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as S}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as i,b as o,r as a,f as u,p as l,d as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as _,zeroMoney as f}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as b}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as h}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as A}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={cancelled:"canceled",failed:"failed",partially_captured:"captured",partially_captured_and_capturable:"captured",processing:"initiated",requires_capture:"authorized",requires_confirmation:"initiated",requires_customer_action:"authorized",requires_merchant_action:"authorized",requires_payment_method:"initiated",succeeded:"captured"},g={active:"active",cancelled:"canceled",expired:"canceled",failed:"past_due",on_hold:"past_due",paused:"paused",pending:"past_due"},I=h("dodopayments (merchant-of-record)"),p=d=>a(i(d.customer),"customer_id")??a(d,"customer_id"),m=d=>{const n=i(d),t=Date.now(),e=a(n,"status")??"";return{cancelAtPeriodEnd:w(n,"cancel_at_next_billing_date")??!1,createdAt:t,currentPeriodEnd:l(a(n,"next_billing_date")),currentPeriodStart:l(a(n,"previous_billing_date")),id:a(n,"subscription_id")??"",priceId:a(n,"product_id")??"",provider:"dodopayments",quantity:o(n,"quantity")??1,referenceId:u(n)??p(n)??"",state:g[e]??"past_due",updatedAt:t}},q=d=>{const n=i(d),t=Date.now(),e=a(n,"currency")??"usd",r=_(BigInt(Math.round(o(n,"total_amount")??0)),e),s=P[a(n,"status")??""]??"initiated";return{amount:r,capturedAmount:s==="captured"?r:f(e),createdAt:t,id:a(n,"payment_id")??"",provider:"dodopayments",referenceId:u(n)??"",refundedAmount:f(e),state:s,updatedAt:t}},k=(d,n,t)=>{const e={eventId:d,provider:"dodopayments",raw:{object:t,type:n}},r=a(t,"currency")??"usd";switch(n){case"dispute.lost":case"refund.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"amount")??0)),r),referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.refunded"};case"payment.cancelled":case"payment.failed":return{...e,referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.failed"};case"payment.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"total_amount")??0)),r),customerId:p(t),referenceId:u(t),sessionId:a(t,"payment_id"),subscriptionId:a(t,"subscription_id"),type:"payment.captured"};case"subscription.active":case"subscription.cancelled":case"subscription.expired":case"subscription.failed":case"subscription.on_hold":case"subscription.paused":case"subscription.plan_changed":case"subscription.renewed":case"subscription.updated":{const s=a(t,"status");return{...e,cancelAtPeriodEnd:w(t,"cancel_at_next_billing_date"),currentPeriodEnd:l(a(t,"next_billing_date")),currentPeriodStart:l(a(t,"previous_billing_date")),customerId:p(t),priceId:a(t,"product_id"),quantity:o(t,"quantity"),referenceId:u(t)??p(t),subscriptionId:a(t,"subscription_id"),type:A(g[s??""]??"past_due")}}default:return{...e,type:"unhandled"}}},R=d=>{const{webhookSecret:n}=d,t=d.client;return{cancelPayment:()=>I("manual payment cancellation"),cancelSubscription:async(e,r)=>{const s=r?.atPeriodEnd?{cancel_at_next_billing_date:!0}:{status:"cancelled"};return m(await t.subscriptions.update(e,s))},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>I("manual capture"),createCheckout:async e=>{const r=i(await t.checkoutSessions.create({customer:e.customerId?{customer_id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},product_cart:[{product_id:e.priceId,quantity:e.quantity??1}],return_url:e.successUrl}));return{id:a(r,"session_id")??"",provider:"dodopayments",url:a(r,"checkout_url")??""}},createPortalSession:async e=>{const r=i(await t.customers.customerPortal.create(e.customerId,{return_url:e.returnUrl}));return{url:a(r,"link")??a(r,"url")??""}},getOrCreateCustomer:async e=>{const r=i(await t.customers.create({email:e.email??"",name:e.metadata?.name??e.referenceId},{idempotencyKey:S("customer","dodopayments",e.referenceId)}));return{createdAt:Date.now(),email:a(r,"email")??e.email,id:a(r,"customer_id")??"",provider:"dodopayments",referenceId:e.referenceId}},getPaymentStatus:async e=>q(await t.payments.retrieve(e)),getSubscriptionStatus:async e=>m(await t.subscriptions.retrieve(e)),identifier:"dodopayments",parseWebhook:async({headers:e,payload:r})=>{const s=e.get("webhook-id")??"";await b({payload:r,secret:n,toleranceSeconds:d.webhookToleranceSeconds,webhookId:s,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const c=i(JSON.parse(r));return k(s,a(c,"type")??"",i(c.data))},refundPayment:async e=>{if(e.amount!==void 0)throw new v("PROVIDER_ERROR","dodopayments refunds a payment in full; partial refunds require line items and aren't supported here");const r=i(await t.refunds.create({payment_id:e.sessionId,reason:e.reason})),s=a(r,"currency")??"usd",c=_(BigInt(Math.round(o(r,"amount")??0)),s);let y="captured";return a(r,"status")==="succeeded"&&(y="refunded"),{amount:c,capturedAmount:c,createdAt:Date.now(),id:e.sessionId,provider:"dodopayments",referenceId:"",refundedAmount:c,state:y,updatedAt:Date.now()}},reportUsage:async e=>{await t.usageEvents.ingest({events:[{customer_id:e.customerId??e.referenceId,event_id:e.idempotencyKey,event_name:e.featureId,metadata:{value:e.quantity},timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp).toISOString()}]})},resumeSubscription:async e=>{const r=await t.subscriptions.update(e,{cancel_at_next_billing_date:!1});return m(r)},updateSubscription:async(e,r)=>{if(r.priceId!==void 0||r.quantity!==void 0){const s=i(r.priceId!==void 0&&r.quantity!==void 0?void 0:await t.subscriptions.retrieve(e));await t.subscriptions.changePlan(e,{product_id:r.priceId??a(s,"product_id")??"",proration_billing_mode:"prorated_immediately",quantity:r.quantity??o(s,"quantity")??1})}return m(await t.subscriptions.retrieve(e))}}};export{R as createDodoPaymentsAdapter};
1
+ import{LunoraPaymentError as v}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as S}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as i,b as o,r as a,f as u,p as l,d as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as _,zeroMoney as f}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as b}from"../packem_shared/constantTimeEqual-D_ynru-O.mjs";import{m as h}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as A}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={cancelled:"canceled",failed:"failed",partially_captured:"captured",partially_captured_and_capturable:"captured",processing:"initiated",requires_capture:"authorized",requires_confirmation:"initiated",requires_customer_action:"authorized",requires_merchant_action:"authorized",requires_payment_method:"initiated",succeeded:"captured"},g={active:"active",cancelled:"canceled",expired:"canceled",failed:"past_due",on_hold:"past_due",paused:"paused",pending:"past_due"},I=h("dodopayments (merchant-of-record)"),p=d=>a(i(d.customer),"customer_id")??a(d,"customer_id"),m=d=>{const n=i(d),t=Date.now(),e=a(n,"status")??"";return{cancelAtPeriodEnd:w(n,"cancel_at_next_billing_date")??!1,createdAt:t,currentPeriodEnd:l(a(n,"next_billing_date")),currentPeriodStart:l(a(n,"previous_billing_date")),id:a(n,"subscription_id")??"",priceId:a(n,"product_id")??"",provider:"dodopayments",quantity:o(n,"quantity")??1,referenceId:u(n)??p(n)??"",state:g[e]??"past_due",updatedAt:t}},q=d=>{const n=i(d),t=Date.now(),e=a(n,"currency")??"usd",r=_(BigInt(Math.round(o(n,"total_amount")??0)),e),s=P[a(n,"status")??""]??"initiated";return{amount:r,capturedAmount:s==="captured"?r:f(e),createdAt:t,id:a(n,"payment_id")??"",provider:"dodopayments",referenceId:u(n)??"",refundedAmount:f(e),state:s,updatedAt:t}},k=(d,n,t)=>{const e={eventId:d,provider:"dodopayments",raw:{object:t,type:n}},r=a(t,"currency")??"usd";switch(n){case"dispute.lost":case"refund.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"amount")??0)),r),referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.refunded"};case"payment.cancelled":case"payment.failed":return{...e,referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.failed"};case"payment.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"total_amount")??0)),r),customerId:p(t),referenceId:u(t),sessionId:a(t,"payment_id"),subscriptionId:a(t,"subscription_id"),type:"payment.captured"};case"subscription.active":case"subscription.cancelled":case"subscription.expired":case"subscription.failed":case"subscription.on_hold":case"subscription.paused":case"subscription.plan_changed":case"subscription.renewed":case"subscription.updated":{const s=a(t,"status");return{...e,cancelAtPeriodEnd:w(t,"cancel_at_next_billing_date"),currentPeriodEnd:l(a(t,"next_billing_date")),currentPeriodStart:l(a(t,"previous_billing_date")),customerId:p(t),priceId:a(t,"product_id"),quantity:o(t,"quantity"),referenceId:u(t)??p(t),subscriptionId:a(t,"subscription_id"),type:A(g[s??""]??"past_due")}}default:return{...e,type:"unhandled"}}},R=d=>{const{webhookSecret:n}=d,t=d.client;return{cancelPayment:()=>I("manual payment cancellation"),cancelSubscription:async(e,r)=>{const s=r?.atPeriodEnd?{cancel_at_next_billing_date:!0}:{status:"cancelled"};return m(await t.subscriptions.update(e,s))},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>I("manual capture"),createCheckout:async e=>{const r=i(await t.checkoutSessions.create({customer:e.customerId?{customer_id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},product_cart:[{product_id:e.priceId,quantity:e.quantity??1}],return_url:e.successUrl}));return{id:a(r,"session_id")??"",provider:"dodopayments",url:a(r,"checkout_url")??""}},createPortalSession:async e=>{const r=i(await t.customers.customerPortal.create(e.customerId,{return_url:e.returnUrl}));return{url:a(r,"link")??a(r,"url")??""}},getOrCreateCustomer:async e=>{const r=i(await t.customers.create({email:e.email??"",name:e.metadata?.name??e.referenceId},{idempotencyKey:S("customer","dodopayments",e.referenceId)}));return{createdAt:Date.now(),email:a(r,"email")??e.email,id:a(r,"customer_id")??"",provider:"dodopayments",referenceId:e.referenceId}},getPaymentStatus:async e=>q(await t.payments.retrieve(e)),getSubscriptionStatus:async e=>m(await t.subscriptions.retrieve(e)),identifier:"dodopayments",parseWebhook:async({headers:e,payload:r})=>{const s=e.get("webhook-id")??"";await b({payload:r,secret:n,toleranceSeconds:d.webhookToleranceSeconds,webhookId:s,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const c=i(JSON.parse(r));return k(s,a(c,"type")??"",i(c.data))},refundPayment:async e=>{if(e.amount!==void 0)throw new v("PROVIDER_ERROR","dodopayments refunds a payment in full; partial refunds require line items and aren't supported here");const r=i(await t.refunds.create({payment_id:e.sessionId,reason:e.reason})),s=a(r,"currency")??"usd",c=_(BigInt(Math.round(o(r,"amount")??0)),s);let y="captured";return a(r,"status")==="succeeded"&&(y="refunded"),{amount:c,capturedAmount:c,createdAt:Date.now(),id:e.sessionId,provider:"dodopayments",referenceId:"",refundedAmount:c,state:y,updatedAt:Date.now()}},reportUsage:async e=>{await t.usageEvents.ingest({events:[{customer_id:e.customerId??e.referenceId,event_id:e.idempotencyKey,event_name:e.featureId,metadata:{value:e.quantity},timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp).toISOString()}]})},resumeSubscription:async e=>{const r=await t.subscriptions.update(e,{cancel_at_next_billing_date:!1});return m(r)},updateSubscription:async(e,r)=>{if(r.priceId!==void 0||r.quantity!==void 0){const s=i(r.priceId!==void 0&&r.quantity!==void 0?void 0:await t.subscriptions.retrieve(e));await t.subscriptions.changePlan(e,{product_id:r.priceId??a(s,"product_id")??"",proration_billing_mode:"prorated_immediately",quantity:r.quantity??o(s,"quantity")??1})}return m(await t.subscriptions.retrieve(e))}}};export{R as createDodoPaymentsAdapter};
@@ -1 +1 @@
1
- import{a as p,r as n,f as c,d as w,p as f,b as i}from"../packem_shared/json-BJJPJVYj.mjs";import{money as m,zeroMoney as I}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as P}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as g}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as b}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const y=s=>s instanceof Date?s.getTime():f(typeof s=="string"?s:void 0),S={draft:"initiated",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded",void:"canceled"},A={active:"active",canceled:"canceled",incomplete:"past_due",incomplete_expired:"canceled",past_due:"past_due",trialing:"trialing",unpaid:"past_due"},_=g("polar (merchant-of-record)"),u=s=>{const a=p(s),r=Date.now();return{cancelAtPeriodEnd:w(a,"cancelAtPeriodEnd")??!1,createdAt:r,currentPeriodEnd:y(a.currentPeriodEnd),currentPeriodStart:y(a.currentPeriodStart),id:n(a,"id")??"",priceId:n(a,"productId")??"",provider:"polar",quantity:1,referenceId:c(a)??"",state:A[n(a,"status")??""]??"past_due",updatedAt:r}},v=s=>{const a=p(s),r=Date.now(),e=n(a,"currency")??"usd",t=m(BigInt(Math.round(i(a,"totalAmount")??i(a,"amount")??0)),e),d=S[n(a,"status")??""]??"initiated";return{amount:t,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?t:I(e),createdAt:r,id:n(a,"id")??"",provider:"polar",referenceId:c(a)??"",refundedAmount:d==="refunded"?t:I(e),state:d,updatedAt:r}},h=(s,a,r)=>{const e={eventId:s,provider:"polar",raw:{object:r,type:a}},t=n(r,"currency")??"usd";switch(a){case"order.created":case"order.paid":return a==="order.created"&&S[n(r,"status")??""]!=="captured"?{...e,type:"unhandled"}:{...e,amount:m(i(r,"total_amount")??i(r,"amount")??0,t),customerId:n(r,"customer_id"),referenceId:c(r),sessionId:n(r,"id"),subscriptionId:n(r,"subscription_id"),type:"payment.captured"};case"refund.created":return{...e,amount:m(i(r,"amount")??0,t),referenceId:c(r),sessionId:n(r,"order_id")??n(r,"id"),type:"payment.refunded"};case"subscription.active":case"subscription.canceled":case"subscription.created":case"subscription.revoked":case"subscription.uncanceled":case"subscription.updated":{const d=a==="subscription.revoked"?"subscription.canceled":b(A[n(r,"status")??""]??"past_due");return{...e,cancelAtPeriodEnd:w(r,"cancel_at_period_end"),currentPeriodEnd:f(n(r,"current_period_end")),currentPeriodStart:f(n(r,"current_period_start")),customerId:n(r,"customer_id"),priceId:n(r,"product_id"),referenceId:c(r),subscriptionId:n(r,"id"),type:d}}default:return{...e,type:"unhandled"}}},M=s=>{const{webhookSecret:a}=s,r=s.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,t)=>{const d=t?.atPeriodEnd?await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!0}}):await r.subscriptions.revoke({id:e});return u(d)},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const t=await r.checkouts.create({customerEmail:e.customerId?void 0:e.email,customerId:e.customerId,externalCustomerId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},products:[e.priceId],returnUrl:e.cancelUrl,successUrl:e.successUrl});return{id:t.id,provider:"polar",url:t.url}},createPortalSession:async e=>({url:(await r.customerSessions.create({customerId:e.customerId})).customerPortalUrl}),getOrCreateCustomer:async e=>{const t=await r.customers.create({email:e.email??"",externalId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},type:"individual"});return{createdAt:Date.now(),email:t.email??void 0,id:t.id,provider:"polar",referenceId:e.referenceId}},getPaymentStatus:async e=>v(await r.orders.get({id:e})),getSubscriptionStatus:async e=>u(await r.subscriptions.get({id:e})),identifier:"polar",parseWebhook:async({headers:e,payload:t})=>{const d=e.get("webhook-id")??"";await P({payload:t,secret:a,toleranceSeconds:s.webhookToleranceSeconds,webhookId:d,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const o=p(JSON.parse(t));return h(d,n(o,"type")??"",p(o.data))},refundPayment:async e=>{const t=e.amount?void 0:await r.orders.get({id:e.sessionId}),d=e.amount?.currency??t?.currency??"usd",o=e.amount?Number(e.amount.minorUnits):t?.totalAmount??0;await r.refunds.create({amount:o,orderId:e.sessionId,reason:e.reason??"customer_request"});const l=e.amount??m(BigInt(Math.round(o)),d);return{amount:l,capturedAmount:l,createdAt:Date.now(),id:e.sessionId,provider:"polar",referenceId:"",refundedAmount:l,state:"refunded",updatedAt:Date.now()}},reportUsage:async e=>{await r.events.ingest({events:[{externalCustomerId:e.referenceId,metadata:{value:e.quantity},name:e.featureId,timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp)}]})},resumeSubscription:async e=>{const t=await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!1}});return u(t)},updateSubscription:async(e,t)=>{const d=await r.subscriptions.update({id:e,subscriptionUpdate:t.priceId?{productId:t.priceId}:{}});return u(d)}}};export{M as createPolarAdapter};
1
+ import{a as p,r as n,f as c,d as w,p as f,b as i}from"../packem_shared/json-BJJPJVYj.mjs";import{money as m,zeroMoney as I}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as P}from"../packem_shared/constantTimeEqual-D_ynru-O.mjs";import{m as g}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as b}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const y=s=>s instanceof Date?s.getTime():f(typeof s=="string"?s:void 0),S={draft:"initiated",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded",void:"canceled"},A={active:"active",canceled:"canceled",incomplete:"past_due",incomplete_expired:"canceled",past_due:"past_due",trialing:"trialing",unpaid:"past_due"},_=g("polar (merchant-of-record)"),u=s=>{const a=p(s),r=Date.now();return{cancelAtPeriodEnd:w(a,"cancelAtPeriodEnd")??!1,createdAt:r,currentPeriodEnd:y(a.currentPeriodEnd),currentPeriodStart:y(a.currentPeriodStart),id:n(a,"id")??"",priceId:n(a,"productId")??"",provider:"polar",quantity:1,referenceId:c(a)??"",state:A[n(a,"status")??""]??"past_due",updatedAt:r}},v=s=>{const a=p(s),r=Date.now(),e=n(a,"currency")??"usd",t=m(BigInt(Math.round(i(a,"totalAmount")??i(a,"amount")??0)),e),d=S[n(a,"status")??""]??"initiated";return{amount:t,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?t:I(e),createdAt:r,id:n(a,"id")??"",provider:"polar",referenceId:c(a)??"",refundedAmount:d==="refunded"?t:I(e),state:d,updatedAt:r}},h=(s,a,r)=>{const e={eventId:s,provider:"polar",raw:{object:r,type:a}},t=n(r,"currency")??"usd";switch(a){case"order.created":case"order.paid":return a==="order.created"&&S[n(r,"status")??""]!=="captured"?{...e,type:"unhandled"}:{...e,amount:m(i(r,"total_amount")??i(r,"amount")??0,t),customerId:n(r,"customer_id"),referenceId:c(r),sessionId:n(r,"id"),subscriptionId:n(r,"subscription_id"),type:"payment.captured"};case"refund.created":return{...e,amount:m(i(r,"amount")??0,t),referenceId:c(r),sessionId:n(r,"order_id")??n(r,"id"),type:"payment.refunded"};case"subscription.active":case"subscription.canceled":case"subscription.created":case"subscription.revoked":case"subscription.uncanceled":case"subscription.updated":{const d=a==="subscription.revoked"?"subscription.canceled":b(A[n(r,"status")??""]??"past_due");return{...e,cancelAtPeriodEnd:w(r,"cancel_at_period_end"),currentPeriodEnd:f(n(r,"current_period_end")),currentPeriodStart:f(n(r,"current_period_start")),customerId:n(r,"customer_id"),priceId:n(r,"product_id"),referenceId:c(r),subscriptionId:n(r,"id"),type:d}}default:return{...e,type:"unhandled"}}},M=s=>{const{webhookSecret:a}=s,r=s.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,t)=>{const d=t?.atPeriodEnd?await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!0}}):await r.subscriptions.revoke({id:e});return u(d)},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const t=await r.checkouts.create({customerEmail:e.customerId?void 0:e.email,customerId:e.customerId,externalCustomerId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},products:[e.priceId],returnUrl:e.cancelUrl,successUrl:e.successUrl});return{id:t.id,provider:"polar",url:t.url}},createPortalSession:async e=>({url:(await r.customerSessions.create({customerId:e.customerId})).customerPortalUrl}),getOrCreateCustomer:async e=>{const t=await r.customers.create({email:e.email??"",externalId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},type:"individual"});return{createdAt:Date.now(),email:t.email??void 0,id:t.id,provider:"polar",referenceId:e.referenceId}},getPaymentStatus:async e=>v(await r.orders.get({id:e})),getSubscriptionStatus:async e=>u(await r.subscriptions.get({id:e})),identifier:"polar",parseWebhook:async({headers:e,payload:t})=>{const d=e.get("webhook-id")??"";await P({payload:t,secret:a,toleranceSeconds:s.webhookToleranceSeconds,webhookId:d,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const o=p(JSON.parse(t));return h(d,n(o,"type")??"",p(o.data))},refundPayment:async e=>{const t=e.amount?void 0:await r.orders.get({id:e.sessionId}),d=e.amount?.currency??t?.currency??"usd",o=e.amount?Number(e.amount.minorUnits):t?.totalAmount??0;await r.refunds.create({amount:o,orderId:e.sessionId,reason:e.reason??"customer_request"});const l=e.amount??m(BigInt(Math.round(o)),d);return{amount:l,capturedAmount:l,createdAt:Date.now(),id:e.sessionId,provider:"polar",referenceId:"",refundedAmount:l,state:"refunded",updatedAt:Date.now()}},reportUsage:async e=>{await r.events.ingest({events:[{externalCustomerId:e.referenceId,metadata:{value:e.quantity},name:e.featureId,timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp)}]})},resumeSubscription:async e=>{const t=await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!1}});return u(t)},updateSubscription:async(e,t)=>{const d=await r.subscriptions.update({id:e,subscriptionUpdate:t.priceId?{productId:t.priceId}:{}});return u(d)}}};export{M as createPolarAdapter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/payment",
3
- "version": "1.0.0-alpha.97",
3
+ "version": "1.0.0-alpha.98",
4
4
  "description": "Provider-agnostic payments for Lunora: Stripe-first adapter, webhook sync, and subscription/payment state machine",
5
5
  "keywords": [
6
6
  "billing",
@@ -71,9 +71,9 @@
71
71
  "access": "public"
72
72
  },
73
73
  "dependencies": {
74
- "@lunora/errors": "1.0.0-alpha.26",
75
- "@lunora/server": "1.0.0-alpha.95",
76
- "@lunora/values": "1.0.0-alpha.34",
74
+ "@lunora/errors": "1.0.0-alpha.27",
75
+ "@lunora/server": "1.0.0-alpha.96",
76
+ "@lunora/values": "1.0.0-alpha.35",
77
77
  "dinero.js": "2.0.2"
78
78
  },
79
79
  "peerDependencies": {
@@ -1 +0,0 @@
1
- import{LunoraPaymentError as r}from"./LunoraPaymentError-BSxyhWgu.mjs";const g=(e,t)=>{const s=Math.max(e.length,t.length);let o=e.length^t.length;for(let n=0;n<s;n+=1){const a=n<e.length?e.charCodeAt(n):0,i=n<t.length?t.charCodeAt(n):0;o|=a^i}return o===0},h=new TextEncoder,I=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),d="whsec_",l=e=>new Uint8Array(Array.from(atob(e),t=>t.codePointAt(0)??0)),A=e=>btoa(String.fromCodePoint(...new Uint8Array(e))),f=async(e,t)=>{const s=await crypto.subtle.importKey("raw",e,{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,h.encode(t));return A(o)},m=g,y=async(e,t)=>{const s=await crypto.subtle.importKey("raw",h.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,h.encode(t));return I(o)},N=async e=>{if(!e.secret)throw new r("CONFIG_INVALID","webhook secret not configured");const t=e.toleranceSeconds??300,s=e.now??Date.now(),o=Number(e.webhookTimestamp);if(!e.webhookId||!e.webhookSignature||!Number.isFinite(o))throw new r("WEBHOOK_SIGNATURE_INVALID","missing standard-webhooks headers");if(Math.abs(Math.floor(s/1e3)-o)>t)throw new r("WEBHOOK_TIMESTAMP_INVALID","signature timestamp outside tolerance");const n=e.secret.startsWith(d)?e.secret.slice(d.length):e.secret;if(!n)throw new r("CONFIG_INVALID","webhook secret not configured");const a=l(n);if(a.length===0)throw new r("CONFIG_INVALID","webhook secret not configured");const i=await f(a,`${e.webhookId}.${e.webhookTimestamp}.${e.payload}`);if(!e.webhookSignature.split(" ").map(c=>{const w=c.indexOf(",");return w===-1?"":c.slice(w+1)}).filter(Boolean).some(c=>m(c,i)))throw new r("WEBHOOK_SIGNATURE_INVALID","no matching signature")},E=async e=>{if(!e.secret)throw new r("CONFIG_INVALID","webhook secret not configured");if(!e.signature)throw new r("WEBHOOK_SIGNATURE_INVALID","missing creem-signature header");const t=await y(e.secret,e.payload);if(!m(e.signature,t))throw new r("WEBHOOK_SIGNATURE_INVALID","no matching signature")};export{m as constantTimeEqual,y as hmacSha256Hex,E as verifyCreemSignature,N as verifyStandardWebhook};