commerce-kit 0.1.0 → 0.3.0

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.js CHANGED
@@ -1,247 +1 @@
1
- var Wt=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var mt=(t,e)=>{for(var r in e)Wt(t,r,{get:e[r],enumerable:!0})};import{neon as Kt}from"@neondatabase/serverless";var G,ft=P(()=>{"use strict";process.env.DATABASE_URL&&(G=Kt(process.env.DATABASE_URL))});var Qt,Vt,h,H=P(()=>{"use strict";Qt=process.env.STRIPE_SECRET_KEY,Vt=process.env.STRIPE_CURRENCY,h={StripeSecretKey:Qt,StripeCurrency:Vt}});function v(t,e){if(!t)throw new Error(e)}var gt,yt,q,Z,F=P(()=>{"use strict";gt=t=>{v(Number.isInteger(t),"Value must be an integer")},yt=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},q=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},Z=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}}});var jt,tt,et=P(()=>{"use strict";jt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),tt=t=>Object.entries(t).map(([e,r])=>`${e}:"${jt(r)}"`).join(" AND ").trim()});import{z as c}from"zod";function U(t){return t.toSorted((e,r)=>{let n=Number(e.metadata.order),o=Number(r.metadata.order);return Number.isNaN(n)&&Number.isNaN(o)||n===o?r.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(o)?-1:n-o})}function Y({default_price:t,marketing_features:e,...r}){return v(t,"Product must have a default price"),v(typeof t=="object","Product default price must be an object"),{...r,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:Jt.parse(r.metadata)}}function zt(t){return!!(t.active&&!t.deleted&&t.default_price)}function W(t){return{...t,data:t.data.filter(zt)}}function K(t){return t.data.map(Y)}function ht(t){return t}function wt(t){return t.data.map(ht)}function rt(t){return t.filter((e,r,n)=>r===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}function at(t){let e=t.payment_method;v(typeof e!="string","Payment method should not be a string");let r=t.customer;v(typeof r!="string"&&!r?.deleted,"Customer should not be a string");let n=Q.parse(t.metadata),o=Object.entries(n).filter(([a])=>a.startsWith("taxBreakdown")).map(([a,i])=>{let u=Pt.safeParse(Z(String(i)));return u.success?u.data:null}).filter(Boolean);return{...t,metadata:n,customer:r,payment_method:e,taxBreakdown:o}}function Ct({payment_method:t,latest_charge:e,...r}){v(typeof t=="object","Payment method is missing from order"),v(typeof e=="object","Latest charge is missing from order");let n=Q.parse(r.metadata),o=Object.entries(n).filter(([a])=>a.startsWith("taxBreakdown")).map(([a,i])=>{let u=Pt.safeParse(Z(String(i)));return u.success?u.data:null}).filter(Boolean);return{...r,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:n}}var Jt,xt,Q,Pt,vt=P(()=>{"use strict";F();et();Jt=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional(),stock:c.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:c.string().optional(),preview:c.string().optional()});xt=t=>!t.deleted&&t.active,Q=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),couponCode:c.string().optional(),taxedAmount:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string(),c.string())),Pt=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()})});var R,Xt,Ht,N,d,St=P(()=>{"use strict";R={DEBUG:0,LOG:1,WARN:2,ERROR:3},Xt="LOG",Ht=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in R?process.env.LOG_LEVEL:Xt,N=R[Ht],d={time(t){N>R.DEBUG||console.time(t)},timeEnd(t){N>R.DEBUG||console.timeEnd(t)},log(...t){N>R.LOG||console.log(...t)},dir(t,e){N>R.LOG||console.dir(t,e)},warn(...t){N>R.WARN||console.warn(...t)},error(...t){N>R.ERROR||console.error(...t)}}});var I,x,It=P(()=>{"use strict";I=t=>t.filter(Boolean),x={accountGetById:{tags:({accountId:t})=>I(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>I(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>I(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>I(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>I(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>I(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>I(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>I(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>I(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>I(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>I(["tax-settings"]),revalidate:()=>{}}}});import _t from"stripe";var Zt,f,nt=P(()=>{"use strict";H();Zt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(r=>`${e}-${r}`)],f=({tags:t,revalidate:e,cache:r,tagPrefix:n,secretKey:o})=>{let a=o??h.StripeSecretKey;if(!a)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let i=Zt(t,n);return new _t(a,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:_t.createFetchHttpClient(((g,s)=>fetch(g,{...s,cache:r??s?.cache,next:{tags:i??s?.next?.tags,revalidate:e??s?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var m,bt=P(()=>{"use strict";m=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t}});import{revalidateTag as A}from"next/cache";import b from"stripe";import{z as _}from"zod";function Et({productId:t,cartId:e}){return e?ot({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):te({productId:t})}async function ot({productId:t,cartId:e,operation:r,clearTaxCalculation:n}){let[o,a]=await Promise.all([k(t),Tt(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!a)throw new Error(`Cart not found: ${e}`);if(o.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!h.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(h.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let i=a.cart.metadata??{},s=q(i[t])+(r==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let C=ae(a)+(o.default_price.unit_amount??0);try{return await B({paymentIntentId:e,data:{metadata:i,amount:C||V},clearTaxCalculation:n})}catch(w){d.error(w)}finally{A(`cart-${e}`)}}async function E(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let a=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(Bt.includes(a.status)){let i=at(a);if(!i)return null;let u=await st(i.metadata),{metadata:{shippingRateId:g}}=i,s=g&&await O(g);return{cart:i,lines:u.map(({product:C,quantity:w})=>C?{product:C,quantity:w}:null).filter(Boolean),shippingRate:s||null}}}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function te({productId:t}={}){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,cache:"no-cache"});if(!h.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let a=t?await k(t):null;if(a&&a.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await o.paymentIntents.create({currency:h.StripeCurrency,amount:a?.default_price.unit_amount||V,automatic_payment_methods:{enabled:!0},metadata:{...a&&{[a.id]:"1"}}},{stripeAccount:e})}catch(a){throw d.error(a),a}}async function Ze({cart:t,add:e}){if(!e)return t;let r=await k(e);if(!r)return d.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:r,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),a=t?j(t)+(r.default_price.unit_amount??0):r.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:a},lines:o}}async function tr({cartId:t,productId:e,quantity:r}){let[n,o]=await Promise.all([L(e),E(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(h.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let a=o.cart.metadata??{};r<=0?a[e]="":a[e]=r.toString();let i=j(o)+(n.default_price.unit_amount??0);try{return await B({paymentIntentId:t,data:{metadata:a,amount:i||V}})}catch(u){d.error(u)}finally{A(`cart-${t}`)}}async function L(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let a=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return Y(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function At({slug:t}){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),a=await f({secretKey:n,tagPrefix:r,tags:x.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:tt({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(a.data.length>1&&a.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(a.data.map(i=>L(i.id))),U(K(W(a)))}async function it(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m();if(t.filter?.category){let i=t.filter?.category,g=await f({secretKey:n,tagPrefix:r,tags:x.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:tt({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return U(rt(K(W(g)))).slice(t.offset||0,t.first)}let a=await f({secretKey:n,tagPrefix:r,tags:x.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return U(rt(K(W(a))).filter(xt)).slice(t.offset||0,t.first)}async function er(){let{stripeAccount:t,storeId:e,secretKey:r}=await m(),o=await f({secretKey:r,tagPrefix:e,tags:x.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return wt(o)}async function O(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let a=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return a}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function rr(){let e=(await it({first:100})).map(n=>n.metadata.category).filter(Boolean),r=new Set(e);return Array.from(r)}async function ar(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function nr(){let{stripeAccount:t,storeId:e,secretKey:r}=await m(),n=f({secretKey:r,tagPrefix:e,tags:x.accountGetById.tags({}),cache:"force-cache"});try{let[o,a]=await yt(n.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=a?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:a,logo:null}:{account:a,logo:i}}catch(o){if(d.error(o),o instanceof b.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function ee(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let a=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge","customer"]},{stripeAccount:e});return Ct(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function or(t){let e=await ee(t);if(!e)return null;let r=$t(e.metadata),n=await Promise.all(r.map(async([i,u])=>({product:await k(i),quantity:u}))),{metadata:{shippingRateId:o}}=e,a=o&&await O(o);return{order:e,lines:n.map(({product:i,quantity:u})=>i?{product:i,quantity:u}:null).filter(Boolean),shippingRate:a||null}}async function st(t){let e=$t(t);return await Promise.all(e.map(async([n,o])=>({product:await k(n),quantity:o})))}function oe({oldCart:t,data:e,mergedMetadata:r,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),a=r.taxCalculationExp?Number.parseInt(r.taxCalculationExp,10)*1e3:null;if(!a||o>=a)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,u=e.amount,g=ne.some(l=>!r[l]&&!t.cart.metadata[l]?!1:r[l]!==t.cart.metadata[l]),s=n.length!==t.lines.length||n.some(l=>{let S=t.lines.find($=>$.product.id===l.product?.id);return l.product?.default_price.unit_amount!==S?.product.default_price.unit_amount||l.quantity!==S?.quantity});return u&&i!==u||g||s}async function Gt(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let a=await o.customers.retrieve(t,{},{stripeAccount:e});return a.deleted?null:a}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}function se(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}async function sr({productId:t,cartId:e,operation:r,clearTaxCalculation:n}){let[o,a]=await Promise.all([L(t),E(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!a)throw new Error(`Cart not found: ${e}`);if(h.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let i=a.cart.metadata??{},s=q(i[t])+(r==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let C=j(a)+(o.default_price.unit_amount??0);try{return await B({paymentIntentId:e,data:{metadata:i,amount:C||V},clearTaxCalculation:n})}catch(w){d.error(w)}finally{A(`cart-${e}`)}}async function dr({cartId:t,shippingRateId:e}){let r=await E(t);if(!r)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let n=await O(e);if(d.timeEnd(`cartSaveShipping ${t}`),!n)throw new Error(`Shipping rate not found: ${e}`);try{d.time(`updatePaymentIntent ${t}`);let o=await B({paymentIntentId:t,data:{metadata:{...r.cart.metadata,shippingRateId:e},amount:j({...r,shippingRate:n})}});return d.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){d.error(o)}finally{A(`cart-${t}`)}}async function pr({cartId:t,billingAddress:e}){if(!await E(t))throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??"","billingAddress.email":e.email??""}}})}catch(n){d.error(n)}finally{A(`cart-${t}`)}}async function ue(){let{stripeAccount:t,storeId:e,secretKey:r}=await m();return await f({secretKey:r,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function lr(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,r])=>[e,q(r)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function mr(t){if(!G)return null;let{storeId:e}=await m();return await G`
2
- select * from reviews
3
- where product_id = ${t.productId} and store_id = ${e}
4
- order by created_at desc
5
- limit ${t.first??100}
6
- offset ${t.offset??0}
7
- `}async function fr(t){if(!G)return null;let{storeId:e}=await m();return await G`
8
- insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
9
- values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
10
- `}var V,k,Bt,$t,re,Tt,ae,ne,ir,ie,Rt,B,j,ce,cr,ur,gr,ct=P(()=>{"use strict";ft();H();vt();St();It();nt();et();F();bt();V=1e3;k=async t=>{let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let a=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return Y(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}},Bt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],$t=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,r])=>[e,q(r)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),re=async t=>{let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let a=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),i=typeof a.customer=="string"?await Gt(a.customer):null;if(Bt.includes(a.status))return at({...a,customer:i})}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}};Tt=async t=>{let e=await re(t);if(!e)return null;let r=await st(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await O(n);return{cart:e,lines:r.map(({product:a,quantity:i})=>a?{product:a,quantity:i}:null).filter(Boolean),shippingRate:o||null}},ae=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:r,quantity:n})=>e+(r.default_price?.unit_amount??0)*n,0):0,ne=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];ir=t=>_.object({name:_.string({message:t.nameRequired}).min(1,t.nameRequired),city:_.string({message:t.cityRequired}).min(1,t.cityRequired),country:_.string({message:t.countryRequired}).min(1,t.countryRequired),line1:_.string({message:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({message:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:_.string().optional().nullable().default(""),phone:_.string().optional().nullable().default(""),taxId:_.string().optional().nullable().default(""),email:_.string().optional().nullable().default("")}),ie=async({lineItems:t,billingAddress:e,cartId:r,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!h.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:a,storeId:i,secretKey:u}=await m(),g=f({secretKey:u,tagPrefix:i,tags:x.createTaxCalculation.tags({cartId:r}),cache:"force-cache"});if(!e?.country)return null;let s=n?await O(n):null,C=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,w=await ue(),l=h.StripeCurrency==="usd"||h.StripeCurrency==="cad"?"exclusive":"inclusive",S=w.defaults.tax_behavior==="inferred_by_currency"?l:w.defaults.tax_behavior??l;w.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${h.StripeCurrency}: ${l}.`),d.time(`createTaxCalculation ${r}`);let $=await g.tax.calculations.create({expand:["line_items"],line_items:t.map(M=>({...M,tax_behavior:M.tax_behavior??S})),currency:h.StripeCurrency,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":S,tax_code:C??w.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:a});return d.timeEnd(`createTaxCalculation ${r}`),console.log(JSON.stringify($).length),$},Rt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};B=async({paymentIntentId:t,data:e,customerOverride:r,clearTaxCalculation:n})=>{let{stripeAccount:o,storeId:a,secretKey:i}=await m(),u=await Tt(t);v(u,`Cart not found: ${t}`);let g=e.amount?e.amount.toString():null,s=Q.parse({...u.cart.metadata,...e.metadata});d.time("getProductsFromMetadata");let C=await st(s);d.timeEnd("getProductsFromMetadata");let w=!n&&oe({oldCart:u,data:e,mergedMetadata:s,lines:C});console.log({shouldRecalculateTax:w});let l=w?await ie({cartId:t,taxId:s.taxId??null,shippingRateId:s.shippingRateId??null,billingAddress:{country:s["billingAddress.country"]??"",city:s["billingAddress.city"]??"",line1:s["billingAddress.line1"]??"",line2:s["billingAddress.line2"]??"",name:s["billingAddress.name"]??"",postalCode:s["billingAddress.postalCode"]??"",state:s["billingAddress.state"]??""},lineItems:C.map(({product:y,quantity:D})=>{if(y?.default_price.unit_amount)return{product:y.id,reference:[y.metadata.slug,y.metadata.variant].filter(Boolean).join("-"),quantity:D,amount:y.default_price.unit_amount*D,tax_behavior:y.default_price.tax_behavior==="exclusive"?"exclusive":y.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:y.tax_code?typeof y.tax_code=="string"?y.tax_code:y.tax_code.id:void 0}}).filter(Boolean)}):null,S=r??(e.customer?await Gt(e.customer):u.cart.customer);console.log({customer:S});let $=f({secretKey:i,tagPrefix:a,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let M=l&&Object.fromEntries(l.tax_breakdown.map(y=>({taxType:y.tax_rate_details.tax_type,taxPercentage:y.tax_rate_details.percentage_decimal,taxAmount:y.amount})).map((y,D)=>[`taxBreakdown${D}`,JSON.stringify(y)])),T=l?l.amount_total:e.amount,X=T&&S?.discount?.coupon.valid?se(T,S.discount):T;console.log({"discount.coupon.amount_off":S?.discount?.coupon.amount_off,"discount.coupon.percent_off":S?.discount?.coupon.percent_off,discountedAmount:X,taxedAmount:T,"taxCalculation.amount_total":l?.amount_total,"data.amount":e.amount,netAmount:g});let Yt=await $.paymentIntents.update(t,{...e,...X&&{amount:X},metadata:{...s,...g&&{netAmount:g},...T&&{taxedAmount:T},...l?{...Rt,...M,taxCalculationId:l.id,taxCalculationExp:l?.expires_at}:{...n&&{...Rt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return d.timeEnd(`paymentIntents.update ${t}`),Yt},j=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+ce(t):0,ce=t=>t?t.lines.reduce((e,{product:r,quantity:n})=>e+(r.default_price?.unit_amount??0)*n,0):0;cr=async({cartId:t,email:e})=>{let r=await E(t);if(!r)throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{...r.cart.metadata,email:e}}})}catch(n){d.error(n)}finally{A(`cart-${t}`)}},ur=async({cartId:t,taxId:e})=>{let r=await E(t);if(!r)throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{...r.cart.metadata,taxId:e}}})}catch(n){d.error(n)}finally{A(`cart-${t}`)}};gr=m});var Nt={};mt(Nt,{StripeProvider:()=>J,createStripeProvider:()=>pe});function pe(t){return new J(t)}var J,qt=P(()=>{"use strict";ct();J=class{constructor(e){this.config=e}mapStripeProduct(e){let r=e.default_price?.unit_amount||0,n=e.default_price?.currency||"usd";return{id:e.id,name:e.name,slug:e.metadata?.slug,summary:e.description,images:e.images||[],active:e.active,price:r/100,currency:n.toUpperCase(),stock:Number.parseInt(e.metadata?.stock||"0",10),stripeId:e.id,metadata:e.metadata||{}}}async productBrowse(e){let r=await it({first:e.first||10,...e}),n=r.data.map(o=>this.mapStripeProduct(o));return{data:n,meta:{count:r.totalCount||n.length,offset:e.offset||0,limit:e.first||10,hasMore:n.length===(e.first||10)}}}async productGet(e){if(e.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),e.slug){let r=await At({slug:e.slug});return r?this.mapStripeProduct(r):null}if(e.id){let r=await L(e.id);return r?this.mapStripeProduct(r):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(e){return{cartId:(await Et({productId:e.variantId,cartId:e.cartId}))?.id||e.cartId||""}}async cartUpdate(e){let r=e.quantity>0?"INCREASE":"DECREASE";return{cartId:(await ot({cartId:e.cartId,productId:e.variantId,operation:r}))?.id||e.cartId}}async cartClear(e){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartGet(e){let r=await E(e.cartId);if(!r)return null;let n=r.lines.map(a=>({id:a.product?.id||"",productId:a.product?.id||"",variantId:a.product?.id,quantity:a.quantity,price:(a.product?.default_price?.unit_amount||0)/100})),o=n.reduce((a,i)=>a+i.price*i.quantity,0);return{id:r.cart.id,customerId:r.cart.customer,items:n,total:o,currency:r.cart.currency?.toUpperCase()||"USD",createdAt:new Date(r.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}}});function kt(t){return!t||t.length===0?dt:`
11
- query ProductQuery($slug: String!) {
12
- product(slug: $slug) {
13
- ${t.join(`
14
- `)}
15
- }
16
- }
17
- `}function Mt(t){return!t||t.length===0?ut:`
18
- query ProductsQuery(
19
- $offset: Int
20
- $limit: Int
21
- $category: String
22
- $query: String
23
- $active: Boolean
24
- $excludeBundles: Boolean
25
- $orderBy: String
26
- $orderDirection: String
27
- ) {
28
- products(
29
- offset: $offset
30
- limit: $limit
31
- category: $category
32
- query: $query
33
- active: $active
34
- excludeBundles: $excludeBundles
35
- orderBy: $orderBy
36
- orderDirection: $orderDirection
37
- ) {
38
- data {
39
- ${t.join(`
40
- `)}
41
- }
42
- meta {
43
- count
44
- offset
45
- limit
46
- hasMore
47
- }
48
- }
49
- }
50
- `}var Lt,ut,dt,le,Ot,Dt=P(()=>{"use strict";Lt=`
51
- fragment ProductFragment on Product {
52
- id
53
- name
54
- slug
55
- summary
56
- images
57
- active
58
- type
59
- createdAt
60
- updatedAt
61
- category {
62
- id
63
- name
64
- slug
65
- description
66
- image
67
- }
68
- variants {
69
- id
70
- price
71
- originalPrice
72
- prePromotionPrice
73
- stock
74
- shippable
75
- attributes
76
- combinations {
77
- id
78
- variantValue {
79
- id
80
- value
81
- colorValue
82
- variantType {
83
- id
84
- label
85
- type
86
- }
87
- }
88
- }
89
- }
90
- collections {
91
- id
92
- name
93
- slug
94
- description
95
- image
96
- active
97
- }
98
- bundleProducts {
99
- id
100
- quantity
101
- position
102
- variant {
103
- id
104
- price
105
- originalPrice
106
- stock
107
- }
108
- }
109
- bundleDiscountPercentage
110
- }
111
- `,ut=`
112
- query ProductsQuery(
113
- $offset: Int
114
- $limit: Int
115
- $category: String
116
- $query: String
117
- $active: Boolean
118
- $excludeBundles: Boolean
119
- $orderBy: String
120
- $orderDirection: String
121
- ) {
122
- products(
123
- offset: $offset
124
- limit: $limit
125
- category: $category
126
- query: $query
127
- active: $active
128
- excludeBundles: $excludeBundles
129
- orderBy: $orderBy
130
- orderDirection: $orderDirection
131
- ) {
132
- data {
133
- ...ProductFragment
134
- }
135
- meta {
136
- count
137
- offset
138
- limit
139
- hasMore
140
- }
141
- }
142
- }
143
- ${Lt}
144
- `,dt=`
145
- query ProductQuery($slug: String!) {
146
- product(slug: $slug) {
147
- ...ProductFragment
148
- }
149
- }
150
- ${Lt}
151
- `,le=`
152
- fragment CartFragment on Cart {
153
- id
154
- customerId
155
- storeId
156
- shippingId
157
- couponId
158
- billingAddressId
159
- shippingAddressId
160
- stripePaymentIntentId
161
- checkoutSessionId
162
- addonData
163
- createdAt
164
- updatedAt
165
- customer {
166
- id
167
- email
168
- userId
169
- user {
170
- id
171
- email
172
- name
173
- }
174
- }
175
- coupon {
176
- code
177
- type
178
- value
179
- startDate
180
- endDate
181
- }
182
- lineItems {
183
- id
184
- cartId
185
- productVariantId
186
- subscriptionId
187
- quantity
188
- createdAt
189
- updatedAt
190
- productVariant {
191
- id
192
- price
193
- originalPrice
194
- stock
195
- shippable
196
- attributes
197
- }
198
- subscription {
199
- id
200
- name
201
- price
202
- interval
203
- intervalCount
204
- }
205
- }
206
- billingAddress {
207
- id
208
- name
209
- company
210
- line1
211
- line2
212
- city
213
- state
214
- postalCode
215
- country
216
- phone
217
- type
218
- }
219
- shippingAddress {
220
- id
221
- name
222
- company
223
- line1
224
- line2
225
- city
226
- state
227
- postalCode
228
- country
229
- phone
230
- type
231
- }
232
- shipping {
233
- id
234
- name
235
- price
236
- minValue
237
- maxValue
238
- }
239
- }
240
- `,Ot=`
241
- query CartQuery($id: String!) {
242
- cart(id: $id) {
243
- ...CartFragment
244
- }
245
- }
246
- ${le}
247
- `});var Ft={};mt(Ft,{YnsProvider:()=>z,createYnsProvider:()=>me});function me(t){return new z(t)}var z,Ut=P(()=>{"use strict";Dt();z=class{config;constructor(e){this.config=e}async graphqlRequest(e,r){let n=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:e,variables:r})});if(!n.ok)throw new Error(`YNS GraphQL request failed: ${n.status} ${n.statusText}`);let o=await n.json();if(o.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(o.errors)}`);return o.data}async restRequest(e,r="GET",n){let o=await fetch(`${this.config.endpoint}/api${e}`,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:n?JSON.stringify(n):void 0});if(!o.ok)throw new Error(`YNS REST request failed: ${o.status} ${o.statusText}`);return o.json()}mapYnsProduct(e){return{id:e.id,name:e.name,slug:e.slug,summary:e.summary,images:e.images||[],active:e.active,price:e.variants?.[0]?.price?Number.parseFloat(e.variants[0].price):0,currency:"USD",stock:e.variants?.[0]?.stock,category:e.category,variants:e.variants?.map(r=>({id:r.id,price:Number.parseFloat(r.price),stock:r.stock,attributes:r.attributes}))||[]}}mapYnsCart(e){let r=e.lineItems?.map(o=>({id:o.id,productId:o.productVariant?.id||"",variantId:o.productVariantId,quantity:o.quantity,price:Number.parseFloat(o.productVariant?.price||"0")}))||[],n=r.reduce((o,a)=>o+a.price*a.quantity,0);return{id:e.id,customerId:e.customerId,items:r,total:n,currency:"USD",createdAt:e.createdAt,updatedAt:e.updatedAt}}async productBrowse(e){let r=e.fields?Mt(e.fields):ut,n={offset:e.offset||0,limit:e.first||e.offset||10,category:e.category,query:e.query,active:e.active,excludeBundles:!1,orderBy:e.orderBy,orderDirection:e.orderDirection},o=await this.graphqlRequest(r,n);return{data:o.products.data.map(a=>this.mapYnsProduct(a)),meta:o.products.meta}}async productGet(e){if(!e.slug&&!e.id)throw new Error("Either slug or id is required for productGet");let r=e.fields?kt(e.fields):dt,n={slug:e.slug},o=await this.graphqlRequest(r,n);return o.product?this.mapYnsProduct(o.product):null}async cartAdd(e){let r={variantId:e.variantId,cartId:e.cartId,subscriptionId:e.subscriptionId};return await this.restRequest("/cart","POST",r)}async cartUpdate(e){let r={variantId:e.variantId,quantity:e.quantity};return await this.restRequest(`/cart/${e.cartId}`,"PUT",r)}async cartClear(e){return await this.restRequest(`/cart/${e.cartId}`,"DELETE")}async cartGet(e){let r=await this.graphqlRequest(Ot,{id:e.cartId});return r.cart?this.mapYnsCart(r.cart):null}}});ct();var pt=null,lt=new Map;function fe(t){pt=t,lt.clear()}function ge(){if(!pt)throw new Error("Commerce SDK not configured. Call Commerce.configure() with your provider settings first.");return pt}async function ye(t){let e=ge(),r=t||e.provider,n=lt.get(r);if(n)return n;let o;switch(r){case"stripe":{let{createStripeProvider:a}=await Promise.resolve().then(()=>(qt(),Nt));o=a(e.stripe||{});break}case"yns":{if(!e.yns)throw new Error("YNS provider configuration is required when using YNS provider");let{createYnsProvider:a}=await Promise.resolve().then(()=>(Ut(),Ft));o=a(e.yns);break}default:throw new Error(`Unsupported provider: ${r}`)}return lt.set(r,o),o}async function p(t){return ye(t?._provider)}F();var he=t=>(v(t.length===3,"currency needs to be a 3-letter code"),Pe[t.toUpperCase()]??2);var we=({amount:t,currency:e})=>{gt(t);let r=he(e),n=10**r;return Number.parseFloat((t/n).toFixed(r))},xe=({amount:t,currency:e,locale:r="en-US"})=>{let n=we({amount:t,currency:e});return new Intl.NumberFormat(r,{style:"currency",currency:e}).format(n)},Pe={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};var Ce={async add(t){return(await p(t)).cartAdd(t)},async update(t){return(await p(t)).cartUpdate(t)},async clear(t){return(await p(t)).cartClear(t)},async get(t){return(await p(t)).cartGet(t)}};var ve={async get(t){let e=await p(t);if(!e.orderGet)throw new Error("Order retrieval is not supported by the current provider");return e.orderGet(t)},async list(t={}){let e=await p(t);if(!e.orderList)throw new Error("Order listing is not supported by the current provider");return e.orderList(t)}};var Se={async browse(t={}){return(await p(t)).productBrowse(t)},async get(t){return(await p(t)).productGet(t)},async search(t){let e=await p(t);if(!e.productSearch)throw new Error("Product search is not supported by the current provider");return e.productSearch(t)}};nt();function Ie(t){return{product:{async browse(e){return(await p({_provider:t})).productBrowse({...e,_provider:t})},async get(e){return(await p({_provider:t})).productGet({...e,_provider:t})},async search(e){let r=await p({_provider:t});if(!r.productSearch)throw new Error(`Product search is not supported by ${t} provider`);return r.productSearch({...e,_provider:t})}},cart:{async add(e){return(await p({_provider:t})).cartAdd({...e,_provider:t})},async update(e){return(await p({_provider:t})).cartUpdate({...e,_provider:t})},async clear(e){return(await p({_provider:t})).cartClear({...e,_provider:t})},async get(e){return(await p({_provider:t})).cartGet({...e,_provider:t})}},order:{async get(e){let r=await p({_provider:t});if(!r.orderGet)throw new Error(`Order retrieval is not supported by ${t} provider`);return r.orderGet({...e,_provider:t})},async list(e={}){let r=await p({_provider:t});if(!r.orderList)throw new Error(`Order listing is not supported by ${t} provider`);return r.orderList({...e,_provider:t})}}}}export{nr as accountGet,ae as calculateCartTotalNet,ce as calculateCartTotalNetWithoutShipping,j as calculateCartTotalPossiblyWithTax,Ce as cart,Et as cartAdd,Ze as cartAddOptimistic,sr as cartChangeQuantity,lr as cartCount,te as cartCreate,E as cartGet,pr as cartSaveBillingAddress,cr as cartSaveEmail,dr as cartSaveShipping,ur as cartSaveTax,tr as cartSetQuantity,ot as cartUpdateQuantity,rr as categoryBrowse,fe as configure,gr as contextGet,ar as fileGet,xe as formatMoney,ir as getAddressSchema,Tt as getCartWithProductsById,$t as getProductsFromCart,st as getProductsFromMetadata,ve as order,or as orderGet,Se as product,it as productBrowse,At as productGet,L as productGetById,fr as productReviewAdd,mr as productReviewBrowse,f as provider,er as shippingBrowse,O as shippingGet,ue as taxDefaultGet,B as updatePaymentIntent,Ie as withProvider};
1
+ var l=Object.defineProperty;var P=(o,r)=>()=>(o&&(r=o(o=0)),r);var m=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})};var u={};m(u,{YnsProvider:()=>a,createYnsProvider:()=>y});function y(o){return new a(o)}var a,p=P(()=>{"use strict";a=class{config;constructor(r){this.config=r}async graphqlRequest(r,t){let e=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:r,variables:t})});if(!e.ok)throw new Error(`YNS GraphQL request failed: ${e.status} ${e.statusText}`);let i=await e.json();if(i.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(i.errors)}`);return i.data}async restRequest(r,t="GET",e){let i=await fetch(`${this.config.endpoint}/api${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:e?JSON.stringify(e):void 0});if(!i.ok)throw new Error(`YNS REST request failed: ${i.status} ${i.statusText}`);return i.json()}mapYnsProduct(r){return{id:r.id,name:r.name,slug:r.slug,summary:r.summary,images:r.images||[],active:r.active,price:r.variants?.[0]?.price?Number.parseFloat(r.variants[0].price):0,currency:"USD",stock:r.variants?.[0]?.stock,category:r.category,variants:r.variants?.map(t=>({id:t.id,price:Number.parseFloat(t.price),stock:t.stock,attributes:t.attributes}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(i=>({id:i.id,productId:i.productVariant?.id||"",variantId:i.productVariantId,quantity:i.quantity,price:Number.parseFloat(i.productVariant?.price||"0")}))||[],e=t.reduce((i,s)=>i+s.price*s.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:e,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}async productBrowse(r){if(r.graphql){let t={offset:r.offset||0,limit:r.first||10,category:r.category,query:r.query,active:r.active,orderBy:r.orderBy,orderDirection:r.orderDirection},e=await this.graphqlRequest(r.graphql,t);return{data:e.products.data.map(i=>this.mapYnsProduct(i)),meta:e.products.meta}}else{let t=new URLSearchParams;r.first&&t.append("limit",r.first.toString()),r.offset&&t.append("offset",r.offset.toString()),r.category&&t.append("category",r.category),r.query&&t.append("q",r.query),r.active!==void 0&&t.append("active",r.active.toString()),r.orderBy&&t.append("orderBy",r.orderBy),r.orderDirection&&t.append("orderDirection",r.orderDirection);let e=`/products${t.toString()?`?${t.toString()}`:""}`,i=await this.restRequest(e);return{data:i.data.map(s=>this.mapYnsProduct(s)),meta:i.meta}}}async productGet(r){if(!r.slug&&!r.id)throw new Error("Either slug or id is required for productGet");if(r.graphql){let t={slug:r.slug,id:r.id},e=await this.graphqlRequest(r.graphql,t);return e.product?this.mapYnsProduct(e.product):null}else{let t=r.id?`/products/${r.id}`:`/products/slug/${r.slug}`,e=await this.restRequest(t);return e?this.mapYnsProduct(e):null}}async cartAdd(r){let t={variantId:r.variantId,cartId:r.cartId,subscriptionId:r.subscriptionId};return await this.restRequest("/cart","POST",t)}async cartUpdate(r){let t={variantId:r.variantId,quantity:r.quantity};return await this.restRequest(`/cart/${r.cartId}`,"PUT",t)}async cartClear(r){return await this.restRequest(`/cart/${r.cartId}`,"DELETE")}async cartGet(r){let t=await this.restRequest(`/cart/${r.cartId}`);return t?this.mapYnsCart(t):null}}});function n(o,r){if(!o)throw new Error(r)}var c=o=>{n(Number.isInteger(o),"Value must be an integer")};var g=o=>(n(o.length===3,"currency needs to be a 3-letter code"),h[o.toUpperCase()]??2);var v=({amount:o,currency:r})=>{c(o);let t=g(r),e=10**t;return Number.parseFloat((o/e).toFixed(t))},f=({amount:o,currency:r,locale:t="en-US"})=>{let e=v({amount:o,currency:r});return new Intl.NumberFormat(t,{style:"currency",currency:r}).format(e)},h={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};var d=class{config;provider;providerPromise;constructor(r){if(this.config=r||this.detectFromEnv(),!this.config.endpoint||!this.config.token)throw new Error("YNS configuration required. Provide endpoint and token in constructor or set YNS_ENDPOINT and YNS_TOKEN environment variables.")}detectFromEnv(){return{endpoint:process.env.YNS_ENDPOINT||"",token:process.env.YNS_TOKEN||""}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createYnsProvider:r}=await Promise.resolve().then(()=>(p(),u));return r(this.config)}catch(r){throw new Error(`Failed to initialize YNS provider: ${r instanceof Error?r.message:"Unknown error"}`)}}get product(){return{browse:async(r={})=>(await this.getProvider()).productBrowse(r),get:async r=>(await this.getProvider()).productGet(r),search:async r=>{let t=await this.getProvider();if(!t.productSearch)throw new Error("Product search is not supported by YNS provider");return t.productSearch(r)}}}get cart(){return{add:async r=>(await this.getProvider()).cartAdd(r),update:async r=>(await this.getProvider()).cartUpdate(r),clear:async r=>(await this.getProvider()).cartClear(r),get:async r=>(await this.getProvider()).cartGet(r)}}get order(){return{get:async r=>{let t=await this.getProvider();if(!t.orderGet)throw new Error("Order retrieval is not supported by YNS provider");return t.orderGet(r)},list:async(r={})=>{let t=await this.getProvider();if(!t.orderList)throw new Error("Order listing is not supported by YNS provider");return t.orderList(r)}}}};export{d as Commerce,f as formatMoney};
@@ -0,0 +1,140 @@
1
+ interface BaseProvider {
2
+ productBrowse(params: ProductBrowseParams): Promise<ProductBrowseResult>;
3
+ productGet(params: ProductGetParams): Promise<Product | null>;
4
+ productSearch?(params: ProductSearchParams): Promise<ProductSearchResult>;
5
+ cartAdd(params: CartAddParams): Promise<{
6
+ cartId: string;
7
+ }>;
8
+ cartUpdate(params: CartUpdateParams): Promise<{
9
+ cartId: string;
10
+ }>;
11
+ cartClear(params: CartClearParams): Promise<{
12
+ cartId: string;
13
+ }>;
14
+ cartGet(params: CartGetParams): Promise<Cart | null>;
15
+ orderGet?(params: OrderGetParams): Promise<Order | null>;
16
+ orderList?(params: OrderListParams): Promise<OrderListResult>;
17
+ }
18
+ interface StripeProviderConfig {
19
+ secretKey?: string;
20
+ tagPrefix?: string;
21
+ }
22
+ interface YnsProviderConfig {
23
+ endpoint: string;
24
+ token: string;
25
+ }
26
+ interface Product {
27
+ id: string;
28
+ name: string;
29
+ slug?: string;
30
+ summary?: string;
31
+ images: string[];
32
+ active: boolean;
33
+ price: number;
34
+ currency: string;
35
+ stock?: number;
36
+ }
37
+ interface Cart {
38
+ id: string;
39
+ customerId?: string;
40
+ items: CartItem[];
41
+ total: number;
42
+ currency: string;
43
+ createdAt: string;
44
+ updatedAt: string;
45
+ }
46
+ interface CartItem {
47
+ id: string;
48
+ productId: string;
49
+ variantId?: string;
50
+ quantity: number;
51
+ price: number;
52
+ }
53
+ interface Order {
54
+ id: string;
55
+ customerId?: string;
56
+ items: CartItem[];
57
+ total: number;
58
+ currency: string;
59
+ status: string;
60
+ createdAt: string;
61
+ updatedAt: string;
62
+ }
63
+ interface ProductBrowseParams {
64
+ first?: number;
65
+ offset?: number;
66
+ category?: string;
67
+ query?: string;
68
+ active?: boolean;
69
+ orderBy?: string;
70
+ orderDirection?: "asc" | "desc";
71
+ graphql?: string;
72
+ _provider?: "stripe" | "yns";
73
+ }
74
+ interface ProductGetParams {
75
+ slug?: string;
76
+ id?: string;
77
+ graphql?: string;
78
+ _provider?: "stripe" | "yns";
79
+ }
80
+ interface ProductSearchParams {
81
+ query: string;
82
+ limit?: number;
83
+ fields?: string[];
84
+ _provider?: "stripe" | "yns";
85
+ }
86
+ interface CartAddParams {
87
+ variantId: string;
88
+ cartId?: string;
89
+ quantity?: number;
90
+ subscriptionId?: string;
91
+ _provider?: "stripe" | "yns";
92
+ }
93
+ interface CartUpdateParams {
94
+ cartId: string;
95
+ variantId: string;
96
+ quantity: number;
97
+ _provider?: "stripe" | "yns";
98
+ }
99
+ interface CartClearParams {
100
+ cartId: string;
101
+ _provider?: "stripe" | "yns";
102
+ }
103
+ interface CartGetParams {
104
+ cartId: string;
105
+ _provider?: "stripe" | "yns";
106
+ }
107
+ interface OrderGetParams {
108
+ orderId: string;
109
+ _provider?: "stripe" | "yns";
110
+ }
111
+ interface OrderListParams {
112
+ customerId?: string;
113
+ limit?: number;
114
+ offset?: number;
115
+ _provider?: "stripe" | "yns";
116
+ }
117
+ interface ProductBrowseResult {
118
+ data: Product[];
119
+ meta: {
120
+ count: number;
121
+ offset: number;
122
+ limit: number;
123
+ hasMore: boolean;
124
+ };
125
+ }
126
+ interface ProductSearchResult {
127
+ data: Product[];
128
+ total: number;
129
+ }
130
+ interface OrderListResult {
131
+ data: Order[];
132
+ meta: {
133
+ count: number;
134
+ offset: number;
135
+ limit: number;
136
+ hasMore: boolean;
137
+ };
138
+ }
139
+
140
+ export type { BaseProvider as B, Cart as C, Order as O, Product as P, StripeProviderConfig as S, YnsProviderConfig as Y, CartAddParams as a, CartClearParams as b, CartGetParams as c, CartItem as d, CartUpdateParams as e, OrderGetParams as f, OrderListParams as g, OrderListResult as h, ProductBrowseParams as i, ProductBrowseResult as j, ProductGetParams as k, ProductSearchParams as l, ProductSearchResult as m };
@@ -0,0 +1,77 @@
1
+ import { S as StripeProviderConfig, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, P as Product, a as CartAddParams, e as CartUpdateParams, b as CartClearParams, c as CartGetParams, C as Cart } from './provider-Co3VegT-.js';
2
+
3
+ /**
4
+ * Stripe Commerce client - zero-config constructor
5
+ * Reads configuration from environment variables by default
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { Commerce } from "commerce-kit/stripe";
10
+ *
11
+ * // Zero config - uses STRIPE_SECRET_KEY from environment
12
+ * const commerce = new Commerce();
13
+ *
14
+ * const products = await commerce.product.browse({ first: 10 });
15
+ * const result = await commerce.cart.add({ variantId: "price_123", quantity: 1 });
16
+ * ```
17
+ */
18
+ declare class Commerce {
19
+ private config;
20
+ private provider?;
21
+ private providerPromise?;
22
+ constructor(config?: StripeProviderConfig);
23
+ /**
24
+ * Detect Stripe configuration from environment variables
25
+ */
26
+ private detectFromEnv;
27
+ /**
28
+ * Lazy-load and cache provider instance
29
+ */
30
+ private getProvider;
31
+ /**
32
+ * Load Stripe provider
33
+ */
34
+ private loadProvider;
35
+ /**
36
+ * Product operations - Stripe specific
37
+ */
38
+ get product(): {
39
+ /**
40
+ * Browse/list products with Stripe-specific parameters
41
+ */
42
+ browse: (params?: ProductBrowseParams) => Promise<ProductBrowseResult>;
43
+ /**
44
+ * Get single product by ID or slug
45
+ */
46
+ get: (params: ProductGetParams) => Promise<Product | null>;
47
+ };
48
+ /**
49
+ * Cart operations - Stripe specific
50
+ */
51
+ get cart(): {
52
+ /**
53
+ * Add item to cart
54
+ */
55
+ add: (params: CartAddParams) => Promise<{
56
+ cartId: string;
57
+ }>;
58
+ /**
59
+ * Update item in cart
60
+ */
61
+ update: (params: CartUpdateParams) => Promise<{
62
+ cartId: string;
63
+ }>;
64
+ /**
65
+ * Clear cart
66
+ */
67
+ clear: (params: CartClearParams) => Promise<{
68
+ cartId: string;
69
+ }>;
70
+ /**
71
+ * Get cart details
72
+ */
73
+ get: (params: CartGetParams) => Promise<Cart | null>;
74
+ };
75
+ }
76
+
77
+ export { Commerce };
package/dist/stripe.js ADDED
@@ -0,0 +1 @@
1
+ var xt=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var wt=(t,e)=>{for(var a in e)xt(t,a,{get:e[a],enumerable:!0})};var Ct,Pt,y,M=P(()=>{"use strict";Ct=process.env.STRIPE_SECRET_KEY,Pt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:Ct,StripeCurrency:Pt}});function _(t,e){if(!t)throw new Error(e)}var q,J,K=P(()=>{"use strict";q=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},J=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}}});var vt,O,W=P(()=>{"use strict";vt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${vt(a)}"`).join(" AND ").trim()});import{z as i}from"zod";function B(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),o=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(o)||n===o?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(o)?-1:n-o})}function $({default_price:t,marketing_features:e,...a}){return _(t,"Product must have a default price"),_(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:St.parse(a.metadata)}}function _t(t){return!!(t.active&&!t.deleted&&t.default_price)}function N(t){return{...t,data:t.data.filter(_t)}}function L(t){return t.data.map($)}function U(t){return t.filter((e,a,n)=>a===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}function Y(t){let e=t.payment_method;_(typeof e!="string","Payment method should not be a string");let a=t.customer;_(typeof a!="string"&&!a?.deleted,"Customer should not be a string");let n=F.parse(t.metadata),o=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,s])=>{let d=It.safeParse(J(String(s)));return d.success?d.data:null}).filter(Boolean);return{...t,metadata:n,customer:a,payment_method:e,taxBreakdown:o}}var St,X,F,It,H=P(()=>{"use strict";K();W();St=i.object({category:i.string().optional(),order:i.coerce.number().optional(),slug:i.string(),variant:i.string().optional(),stock:i.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:i.string().optional(),preview:i.string().optional()});X=t=>!t.deleted&&t.active,F=i.object({shippingRateId:i.string().optional(),taxCalculationId:i.string().optional(),taxCalculationExp:i.string().optional(),taxId:i.string().optional(),couponCode:i.string().optional(),taxedAmount:i.string().optional(),"billingAddress.city":i.string().optional(),"billingAddress.country":i.string().optional(),"billingAddress.line1":i.string().optional(),"billingAddress.line2":i.string().optional(),"billingAddress.name":i.string().optional(),"billingAddress.postalCode":i.string().optional(),"billingAddress.state":i.string().optional(),netAmount:i.string().optional(),taxBreakdown0:i.string().optional(),taxBreakdown1:i.string().optional(),taxBreakdown2:i.string().optional(),taxBreakdown3:i.string().optional(),taxBreakdown4:i.string().optional(),taxBreakdown5:i.string().optional()}).and(i.record(i.string(),i.string())),It=i.object({taxType:i.string(),taxPercentage:i.string(),taxAmount:i.number()})});var S,Et,Rt,R,m,Z=P(()=>{"use strict";S={DEBUG:0,LOG:1,WARN:2,ERROR:3},Et="LOG",Rt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in S?process.env.LOG_LEVEL:Et,R=S[Rt],m={time(t){R>S.DEBUG||console.time(t)},timeEnd(t){R>S.DEBUG||console.timeEnd(t)},log(...t){R>S.LOG||console.log(...t)},dir(t,e){R>S.LOG||console.dir(t,e)},warn(...t){R>S.WARN||console.warn(...t)},error(...t){R>S.ERROR||console.error(...t)}}});var w,v,tt=P(()=>{"use strict";w=t=>t.filter(Boolean),v={accountGetById:{tags:({accountId:t})=>w(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>w(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>w(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>w(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>w(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>w(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>w(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}}});import et from"stripe";var bt,f,rt=P(()=>{"use strict";M();bt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],f=({tags:t,revalidate:e,cache:a,tagPrefix:n,secretKey:o})=>{let r=o??y.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let s=bt(t,n);return new et(r,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:et.createFetchHttpClient(((l,c)=>fetch(l,{...c,cache:a??c?.cache,next:{tags:s??c?.next?.tags,revalidate:e??c?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var h,at=P(()=>{"use strict";h=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t}});import{revalidateTag as At}from"next/cache";import b from"stripe";import{z as ue}from"zod";function it({productId:t,cartId:e}){return e?j({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):Tt({productId:t})}async function j({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([Q(t),pt(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(o.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(y.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let s=r.cart.metadata??{},c=q(s[t])+(a==="INCREASE"?1:-1);c<=0?s[t]="":s[t]=c.toString();let C=Nt(r)+(o.default_price.unit_amount??0);try{return await qt({paymentIntentId:e,data:{metadata:s,amount:C||ot},clearTaxCalculation:n})}catch(g){m.error(g)}finally{At(`cart-${e}`)}}async function st(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(dt.includes(r.status)){let s=Y(r);if(!s)return null;let d=await z(s.metadata),{metadata:{shippingRateId:l}}=s,c=l&&await V(l);return{cart:s,lines:d.map(({product:C,quantity:g})=>C?{product:C,quantity:g}:null).filter(Boolean),shippingRate:c||null}}}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Tt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await Q(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await o.paymentIntents.create({currency:y.StripeCurrency,amount:r?.default_price.unit_amount||ot,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw m.error(r),r}}async function D(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ct({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),r=await f({secretKey:n,tagPrefix:a,tags:v.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:O({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(s=>!s.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(r.data.map(s=>D(s.id))),B(L(N(r)))}async function ut(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h();if(t.filter?.category){let s=t.filter?.category,l=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({category:s}),cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':s}),expand:["data.default_price"]},{stripeAccount:e});return B(U(L(N(l)))).slice(t.offset||0,t.first)}let r=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return B(U(L(N(r))).filter(X)).slice(t.offset||0,t.first)}async function V(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function z(t){let e=Bt(t);return await Promise.all(e.map(async([n,o])=>({product:await Q(n),quantity:o})))}function Gt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp,10)*1e3:null;if(!r||o>=r)return!0;let s=t.cart.metadata.netAmount||t.cart.amount,d=e.amount,l=Lt.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),c=n.length!==t.lines.length||n.some(u=>{let x=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==x?.product.default_price.unit_amount||u.quantity!==x?.quantity});return d&&s!==d||l||c}async function lt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let r=await o.customers.retrieve(t,{},{stripeAccount:e});return r.deleted?null:r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function Mt(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}async function Kt(){let{stripeAccount:t,storeId:e,secretKey:a}=await h();return await f({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}var ot,Q,dt,Bt,$t,pt,Nt,Lt,kt,nt,qt,mt=P(()=>{"use strict";M();H();Z();tt();rt();W();K();at();ot=1e3;Q=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},dt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Bt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,q(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),$t=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),s=typeof r.customer=="string"?await lt(r.customer):null;if(dt.includes(r.status))return Y({...r,customer:s})}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};pt=async t=>{let e=await $t(t);if(!e)return null;let a=await z(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await V(n);return{cart:e,lines:a.map(({product:r,quantity:s})=>r?{product:r,quantity:s}:null).filter(Boolean),shippingRate:o||null}},Nt=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0,Lt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];kt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:s,secretKey:d}=await h(),l=f({secretKey:d,tagPrefix:s,tags:v.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let c=n?await V(n):null,C=typeof c?.tax_code=="string"?c.tax_code:c?.tax_code?.id,g=await Kt(),u=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",x=g.defaults.tax_behavior==="inferred_by_currency"?u:g.defaults.tax_behavior??u;g.defaults.tax_behavior||m.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${u}.`),m.time(`createTaxCalculation ${a}`);let I=await l.tax.calculations.create({expand:["line_items"],line_items:t.map(A=>({...A,tax_behavior:A.tax_behavior??x})),currency:y.StripeCurrency,shipping_cost:c?.active&&c?.fixed_amount?{amount:c.fixed_amount.amount,tax_behavior:c.tax_behavior==="inclusive"?"inclusive":c.tax_behavior==="exclusive"?"exclusive":x,tax_code:C??g.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return m.timeEnd(`createTaxCalculation ${a}`),console.log(JSON.stringify(I).length),I},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};qt=async({paymentIntentId:t,data:e,customerOverride:a,clearTaxCalculation:n})=>{let{stripeAccount:o,storeId:r,secretKey:s}=await h(),d=await pt(t);_(d,`Cart not found: ${t}`);let l=e.amount?e.amount.toString():null,c=F.parse({...d.cart.metadata,...e.metadata});m.time("getProductsFromMetadata");let C=await z(c);m.timeEnd("getProductsFromMetadata");let g=!n&&Gt({oldCart:d,data:e,mergedMetadata:c,lines:C});console.log({shouldRecalculateTax:g});let u=g?await kt({cartId:t,taxId:c.taxId??null,shippingRateId:c.shippingRateId??null,billingAddress:{country:c["billingAddress.country"]??"",city:c["billingAddress.city"]??"",line1:c["billingAddress.line1"]??"",line2:c["billingAddress.line2"]??"",name:c["billingAddress.name"]??"",postalCode:c["billingAddress.postalCode"]??"",state:c["billingAddress.state"]??""},lineItems:C.map(({product:p,quantity:T})=>{if(p?.default_price.unit_amount)return{product:p.id,reference:[p.metadata.slug,p.metadata.variant].filter(Boolean).join("-"),quantity:T,amount:p.default_price.unit_amount*T,tax_behavior:p.default_price.tax_behavior==="exclusive"?"exclusive":p.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:p.tax_code?typeof p.tax_code=="string"?p.tax_code:p.tax_code.id:void 0}}).filter(Boolean)}):null,x=a??(e.customer?await lt(e.customer):d.cart.customer);console.log({customer:x});let I=f({secretKey:s,tagPrefix:r,cache:"no-cache"});m.time(`paymentIntents.update ${t}`);let A=u&&Object.fromEntries(u.tax_breakdown.map(p=>({taxType:p.tax_rate_details.tax_type,taxPercentage:p.tax_rate_details.percentage_decimal,taxAmount:p.amount})).map((p,T)=>[`taxBreakdown${T}`,JSON.stringify(p)])),E=u?u.amount_total:e.amount,k=E&&x?.discount?.coupon.valid?Mt(E,x.discount):E;console.log({"discount.coupon.amount_off":x?.discount?.coupon.amount_off,"discount.coupon.percent_off":x?.discount?.coupon.percent_off,discountedAmount:k,taxedAmount:E,"taxCalculation.amount_total":u?.amount_total,"data.amount":e.amount,netAmount:l});let ht=await I.paymentIntents.update(t,{...e,...k&&{amount:k},metadata:{...c,...l&&{netAmount:l},...E&&{taxedAmount:E},...u?{...nt,...A,taxCalculationId:u.id,taxCalculationExp:u?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return m.timeEnd(`paymentIntents.update ${t}`),ht}});var ft={};wt(ft,{StripeProvider:()=>G,createStripeProvider:()=>Wt});function Wt(t){return new G(t)}var G,gt=P(()=>{"use strict";mt();G=class{constructor(e){this.config=e}mapStripeProduct(e){let a=e.default_price?.unit_amount||0,n=e.default_price?.currency||"usd";return{id:e.id,name:e.name,slug:e.metadata?.slug,summary:e.description,images:e.images||[],active:e.active,price:a/100,currency:n.toUpperCase(),stock:Number.parseInt(e.metadata?.stock||"0",10),stripeId:e.id,metadata:e.metadata||{}}}async productBrowse(e){let a=await ut({first:e.first||10,...e}),n=a.data.map(o=>this.mapStripeProduct(o));return{data:n,meta:{count:a.totalCount||n.length,offset:e.offset||0,limit:e.first||10,hasMore:n.length===(e.first||10)}}}async productGet(e){if(e.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),e.slug){let a=await ct({slug:e.slug});return a?this.mapStripeProduct(a):null}if(e.id){let a=await D(e.id);return a?this.mapStripeProduct(a):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(e){return{cartId:(await it({productId:e.variantId,cartId:e.cartId}))?.id||e.cartId||""}}async cartUpdate(e){let a=e.quantity>0?"INCREASE":"DECREASE";return{cartId:(await j({cartId:e.cartId,productId:e.variantId,operation:a}))?.id||e.cartId}}async cartClear(e){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartGet(e){let a=await st(e.cartId);if(!a)return null;let n=a.lines.map(r=>({id:r.product?.id||"",productId:r.product?.id||"",variantId:r.product?.id,quantity:r.quantity,price:(r.product?.default_price?.unit_amount||0)/100})),o=n.reduce((r,s)=>r+s.price*s.quantity,0);return{id:a.cart.id,customerId:a.cart.customer,items:n,total:o,currency:a.cart.currency?.toUpperCase()||"USD",createdAt:new Date(a.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}}});var yt=class{config;provider;providerPromise;constructor(e){if(this.config=e||this.detectFromEnv(),!this.config.secretKey&&!process.env.STRIPE_SECRET_KEY)throw new Error("Stripe configuration required. Provide secretKey in constructor or set STRIPE_SECRET_KEY environment variable.")}detectFromEnv(){return{secretKey:process.env.STRIPE_SECRET_KEY,tagPrefix:process.env.STRIPE_TAG_PREFIX}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createStripeProvider:e}=await Promise.resolve().then(()=>(gt(),ft));return e(this.config)}catch(e){throw new Error(`Failed to initialize Stripe provider: ${e instanceof Error?e.message:"Unknown error"}`)}}get product(){return{browse:async(e={})=>(await this.getProvider()).productBrowse(e),get:async e=>(await this.getProvider()).productGet(e)}}get cart(){return{add:async e=>(await this.getProvider()).cartAdd(e),update:async e=>(await this.getProvider()).cartUpdate(e),clear:async e=>(await this.getProvider()).cartClear(e),get:async e=>(await this.getProvider()).cartGet(e)}}};export{yt as Commerce};
@@ -0,0 +1,22 @@
1
+ type YnsFindStripeAccountResult = {
2
+ stripeAccount: string | undefined;
3
+ storeId: string | undefined;
4
+ secretKey: string | undefined;
5
+ publishableKey: string | undefined;
6
+ };
7
+ type YnsContextResult = {
8
+ stripeAccount: string | undefined;
9
+ storeId: string | undefined;
10
+ secretKey: string | undefined;
11
+ publishableKey: string | undefined;
12
+ };
13
+ declare global {
14
+ /**
15
+ * ⚠️ Warning: This might be `undefined` but TypeScript doesn't have a syntax to express that.
16
+ * @see https://github.com/microsoft/TypeScript/issues/36057
17
+ */
18
+ function __ynsFindStripeAccount(): YnsFindStripeAccountResult | undefined | Promise<YnsFindStripeAccountResult | undefined>;
19
+ }
20
+ declare const getYnsContext: () => Promise<YnsContextResult>;
21
+
22
+ export { getYnsContext };
@@ -0,0 +1 @@
1
+ var t=async()=>{let e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??e};export{t as getYnsContext};