commerce-kit 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"server-only";import"server-only";import{z as s}from"zod";function _(t,e){if(!t)throw new Error(e)}var W=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},R=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},L=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var O=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),j=t=>Object.entries(t).map(([e,a])=>`${e}:"${O(a)}"`).join(" AND ").trim();function A(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),r=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(r)||n===r?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(r)?-1:n-r})}var at=s.object({category:s.string().optional(),order:s.coerce.number().optional(),slug:s.string(),variant:s.string().optional()});function N({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:at.parse(a.metadata)}}function v(t){return t.data.map(N)}function Q(t){return t.filter((e,a,n)=>a===n.findIndex(r=>r.metadata.slug===e.metadata.slug))}var B=t=>!t.deleted&&t.active,$=s.object({shippingRateId:s.string().optional(),taxCalculationId:s.string().optional(),taxCalculationExp:s.string().optional(),taxId:s.string().optional(),"billingAddress.city":s.string().optional(),"billingAddress.country":s.string().optional(),"billingAddress.line1":s.string().optional(),"billingAddress.line2":s.string().optional(),"billingAddress.name":s.string().optional(),"billingAddress.postalCode":s.string().optional(),"billingAddress.state":s.string().optional(),netAmount:s.string().optional(),taxBreakdown0:s.string().optional(),taxBreakdown1:s.string().optional(),taxBreakdown2:s.string().optional(),taxBreakdown3:s.string().optional(),taxBreakdown4:s.string().optional(),taxBreakdown5:s.string().optional()}).and(s.record(s.string())),Y=s.object({taxType:s.string(),taxPercentage:s.string(),taxAmount:s.number()});function G(t){let e=t.payment_method;_(typeof e!="string","Payment method is missing from cart");let a=$.parse(t.metadata),n=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let o=Y.safeParse(L(String(i)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function V({payment_method:t,latest_charge:e,...a}){_(typeof t=="object","Payment method is missing from order"),_(typeof e=="object","Latest charge is missing from order");let n=$.parse(a.metadata),r=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,o])=>{let c=Y.safeParse(L(String(o)));return c.success?c.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:r,metadata:n}}import"server-only";import{revalidatePath as J,revalidateTag as S}from"next/cache";import C from"stripe";import{z as w}from"zod";import"server-only";var f=async()=>{let t={stripeAccount:void 0,storeId:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import K from"stripe";import"server-only";var z=process.env.STRIPE_SECRET_KEY;if(!z)throw new Error("Missing STRIPE_SECRET_KEY");var D=process.env.STRIPE_CURRENCY;if(!D)throw new Error("Missing STRIPE_CURRENCY");var g={StripeSecretKey:z,StripeCurrency:D};var nt=({tags:t,revalidate:e,cache:a})=>new K(g.StripeSecretKey,{typescript:!0,apiVersion:"2024-06-20",httpClient:K.createFetchHttpClient((r,i)=>fetch(r,{...i,cache:a??i?.cache,next:{tags:t??i?.next?.tags,revalidate:e??i?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),it=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],d=({tags:t,revalidate:e,cache:a,tagPrefix:n})=>nt({tags:it(t,n),revalidate:e,cache:a});var q=1e3;function jt({productId:t,cartId:e}){return e?k.add(d,{productId:t,cartId:e}):k.create(d,{productId:t})}function I(t){return k.get(d,{cartId:t})}function Qt(){return k.create(d,{})}async function Gt({cart:t,add:e}){if(!e)return t;let a=await E(e);if(!a)return console.warn(`Product not found: ${e}`),t;let r=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),i=t?M(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:i},lines:r}}async function Ut({cartId:t,productId:e,quantity:a}){let[n,r]=await Promise.all([H(e),I(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!r)throw new Error(`Cart not found: ${t}`);if(g.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let i=r.cart.metadata??{};a<=0?i[e]="":i[e]=a.toString();let o=M(r)+(n.default_price.unit_amount??0);try{return await P({paymentIntentId:t,data:{metadata:i,amount:o||q}})}catch(c){console.error(c)}finally{S(`cart-${t}`),J("/cart"),J("/cart-overlay")}}async function H(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return N(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Wt({slug:t}){let{stripeAccount:e,storeId:a}=await f(),r=await d({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"}).products.search({query:j({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return A(v(r).filter(B))}async function ot(t){let{stripeAccount:e,storeId:a}=await f();if(t.filter?.category){let n=t.filter?.category,i=await d({tagPrefix:a,tags:["product",`category-${n}`],cache:"force-cache"}).products.search({limit:100,query:j({active:!0,'metadata["category"]':n}),expand:["data.default_price"]},{stripeAccount:e});return A(Q(v(i)).filter(B).slice(t.offset,t.first))}else{let r=await d({tagPrefix:a,tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return A(Q(v(r)).filter(B).slice(t.offset,t.first))}}async function Yt(){let{stripeAccount:t,storeId:e}=await f();return await d({tagPrefix:e,tags:["shipping"]}).shippingRates.list({active:!0},{stripeAccount:t})}async function T(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["shipping",`shipping-${t}`]});try{return await n.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Vt(t){let a=(await ot({first:100})).map(r=>r.metadata.category),n=new Set(a);return Array.from(n).filter(Boolean)}async function zt(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["products","search"]}),r=O(t.query),i=await n.products.search({limit:100,query:`name~"${r}" OR description~"${r}" OR metadata["slug"]:"${r}" OR metadata["category"]:"${r}"`,expand:["data.default_price"]},{stripeAccount:e});return A(v(i).filter(o=>o.active&&!o.deleted))}async function Dt(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["files",`file-${t}`]});try{return await n.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Kt(){let{stripeAccount:t,storeId:e}=await f(),a=d({tagPrefix:e,tags:["account"]});try{let[n,r]=await W(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(n){if(console.error(n),n instanceof C.errors.StripeError&&n.code==="resource_missing")return null;throw n}}async function st(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["order",`order-${t}`]});try{let r=await n.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return V(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Jt(t){let e=await st(t);if(!e)return null;let a=tt(e.metadata),n=await Promise.all(a.map(async([o,c])=>({product:await E(o),quantity:c}))),{metadata:{shippingRateId:r}}=e,i=r&&await T(r);return{order:e,lines:n.map(({product:o,quantity:c})=>o?{product:o,quantity:c}:null).filter(Boolean),shippingRate:i||null}}var E=async t=>{let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return N(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}},Z=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],tt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),ct=async(t,e)=>{let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status))return G(i)}catch(i){if(console.error(i),i instanceof C.errors.StripeError&&i.code==="resource_missing")return null;throw i}};async function U(t){let e=tt(t);return await Promise.all(e.map(async([n,r])=>({product:await E(n),quantity:r})))}var et=async(t,e)=>{let a=await ct(t,e);if(!a)return null;let n=await U(a.metadata),{metadata:{shippingRateId:r}}=a,i=r&&await T(r);return{cart:a,lines:n.map(({product:o,quantity:c})=>o?{product:o,quantity:c}:null).filter(Boolean),shippingRate:i||null}},ut=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,dt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function pt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let r=Date.now(),i=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!i||r>=i)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,c=e.amount,u=dt.some(y=>!a[y]&&!t.cart.metadata[y]?!1:a[y]!==t.cart.metadata[y]),m=n.length!==t.lines.length||n.some(y=>{let l=t.lines.find(h=>h.product.id===y.product?.id);return y.product?.default_price.unit_amount!==l?.product.default_price.unit_amount||y.quantity!==l?.quantity});return c&&o!==c||u||m}var Xt=t=>w.object({name:w.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:w.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:w.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:w.string({required_error:t.line1Required}).min(1,t.line1Required),line2:w.string().optional().nullable().default(""),postalCode:w.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:w.string().optional().nullable().default(""),phone:w.string().optional().nullable().default(""),taxId:w.string().optional().nullable().default("")}),lt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:r})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:i,storeId:o}=await f(),c=d({tagPrefix:o,tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let u=n?await T(n):null,m=typeof u?.tax_code=="string"?u.tax_code:u?.tax_code?.id,p=await ft(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",y=p.defaults.tax_behavior==="inferred_by_currency"?x:p.defaults.tax_behavior??x;return p.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${x}.`),await c.tax.calculations.create({expand:["line_items"],line_items:t.map(h=>({...h,tax_behavior:h.tax_behavior??y})),currency:g.StripeCurrency,shipping_cost:u?.active&&u?.fixed_amount?{amount:u.fixed_amount.amount,tax_behavior:u.tax_behavior==="inclusive"?"inclusive":u.tax_behavior==="exclusive"?"exclusive":y,tax_code:m??p.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:r?[{type:"eu_vat",value:r}]: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:i})},X={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},P=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:r}=await f(),i=await et(d,t);_(i,`Cart not found: ${t}`);let o=$.parse({...i.cart.metadata,...e.metadata}),c=await U(o),m=!a&&pt({oldCart:i,data:e,mergedMetadata:o,lines:c})?await lt({cartId:t,taxId:o.taxId??null,shippingRateId:o.shippingRateId??null,billingAddress:{country:o["billingAddress.country"]??"",city:o["billingAddress.city"]??"",line1:o["billingAddress.line1"]??"",line2:o["billingAddress.line2"]??"",name:o["billingAddress.name"]??"",postalCode:o["billingAddress.postalCode"]??"",state:o["billingAddress.state"]??""},lineItems:c.map(({product:l,quantity:h})=>{if(l?.default_price.unit_amount)return{product:l.id,reference:[l.metadata.slug,l.metadata.variant].filter(Boolean).join("-"),quantity:h,amount:l.default_price.unit_amount*h,tax_behavior:l.default_price.tax_behavior==="exclusive"?"exclusive":l.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:l.tax_code?typeof l.tax_code=="string"?l.tax_code:l.tax_code.id:void 0}}).filter(Boolean)}):null,p=e.amount?e.amount.toString():null;if(m){let l=Object.fromEntries(m.tax_breakdown.map(b=>({taxType:b.tax_rate_details.tax_type,taxPercentage:b.tax_rate_details.percentage_decimal,taxAmount:b.amount})).map((b,rt)=>[`taxBreakdown${rt}`,JSON.stringify(b)]));return await d({tagPrefix:r,tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,amount:m.amount_total,metadata:{...o,...p&&{netAmount:p},...X,...l,taxCalculationId:m.id,taxCalculationExp:m?.expires_at}},{stripeAccount:n})}return await d({tagPrefix:r,tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,metadata:{...o,...p&&{netAmount:p},...a&&{...X,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n})},k={async create(t,{productId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,cache:"no-cache"});try{let i=e?await E(e):null;return await r.paymentIntents.create({currency:g.StripeCurrency,amount:i?.default_price.unit_amount||q,automatic_payment_methods:{enabled:!0},metadata:{...i&&{[i.id]:"1"}}},{stripeAccount:a})}catch(i){throw console.error(i),i}},async get(t,{cartId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status)){let o=G(i);if(!o)return null;let c=await U(o.metadata),{metadata:{shippingRateId:u}}=o,m=u&&await T(u);return{cart:o,lines:c.map(({product:p,quantity:x})=>p?{product:p,quantity:x}:null).filter(Boolean),shippingRate:m||null}}}catch(i){if(console.error(i),i instanceof C.errors.StripeError&&i.code==="resource_missing")return null;throw i}},async add(t,{cartId:e,productId:a}){return(async({productId:r,cartId:i,operation:o,clearTaxCalculation:c})=>{let[u,m]=await Promise.all([E(r),et(t,i)]);if(!u)throw new Error(`Product not found: ${r}`);if(!m)throw new Error(`Cart not found: ${i}`);if(g.StripeCurrency.toLowerCase()!==u.default_price.currency.toLowerCase())throw new Error(`Product currency ${u.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let p=m.cart.metadata??{},l=R(p[r])+(o==="INCREASE"?1:-1);l<=0?p[r]="":p[r]=l.toString();let h=ut(m)+(u.default_price.unit_amount??0);try{return await P({paymentIntentId:i,data:{metadata:p,amount:h||q},clearTaxCalculation:c})}catch(F){console.error(F)}finally{S(`cart-${i}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},M=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+mt(t):0,mt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function Ht({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[r,i]=await Promise.all([H(t),I(e)]);if(!r)throw new Error(`Product not found: ${t}`);if(!i)throw new Error(`Cart not found: ${e}`);if(g.StripeCurrency?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=i.cart.metadata??{},m=R(o[t])+(a==="INCREASE"?1:-1);m<=0?o[t]="":o[t]=m.toString();let p=M(i)+(r.default_price.unit_amount??0);try{return await P({paymentIntentId:e,data:{metadata:o,amount:p||q},clearTaxCalculation:n})}catch(x){console.error(x)}finally{S(`cart-${e}`)}}var Zt=async({cartId:t,taxId:e})=>{let a=await I(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await P({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){console.error(n)}finally{S(`cart-${t}`)}};async function te({cartId:t,shippingRateId:e}){let a=await I(t);if(!a)throw new Error(`Cart not found: ${t}`);let n=await T(e);if(!n)throw new Error(`Shipping rate not found: ${e}`);try{return await P({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:M({...a,shippingRate:n})}})}catch(r){console.error(r)}finally{S(`cart-${t}`)}}async function ee({cartId:t,billingAddress:e}){if(!await I(t))throw new Error(`Cart not found: ${t}`);try{return await P({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??""}}})}catch(n){console.error(n)}finally{S(`cart-${t}`)}}async function ft(){let{stripeAccount:t,storeId:e}=await f();return await d({tagPrefix:e,tags:["tax-settings"]}).tax.settings.retrieve({},{stripeAccount:t})}function re(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{nt as StripeClient,Kt as accountGet,ut as calculateCartTotalNet,mt as calculateCartTotalNetWithoutShipping,M as calculateCartTotalPossiblyWithTax,jt as cartAdd,Gt as cartAddOptimistic,Ht as cartChangeQuantity,re as cartCount,Qt as cartCreate,I as cartGet,ee as cartSaveBillingAddress,te as cartSaveShipping,Zt as cartSaveTax,Ut as cartSetQuantity,Vt as categoryBrowse,Dt as fileGet,Xt as getAddressSchema,et as getCartWithProductsById,tt as getProductsFromCart,Jt as orderGet,ot as productBrowse,Wt as productGet,H as productGetById,zt as productSearch,d as provider,Yt as shippingBrowse,T as shippingGet,ft as taxDefaultGet};
1
+ import"server-only";import"server-only";import{z as c}from"zod";function C(t,e){if(!t)throw new Error(e)}var U=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},R=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},F=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var L=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${L(a)}"`).join(" AND ").trim();function A(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),r=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(r)||n===r?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(r)?-1:n-r})}var at=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional()});function $({default_price:t,marketing_features:e,...a}){return C(t,"Product must have a default price"),C(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:at.parse(a.metadata)}}function v(t){return t.data.map($)}function j(t){return t.filter((e,a,n)=>a===n.findIndex(r=>r.metadata.slug===e.metadata.slug))}var B=t=>!t.deleted&&t.active,q=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId: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())),Y=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Q(t){let e=t.payment_method;C(typeof e!="string","Payment method is missing from cart");let a=q.parse(t.metadata),n=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let o=Y.safeParse(F(String(i)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function V({payment_method:t,latest_charge:e,...a}){C(typeof t=="object","Payment method is missing from order"),C(typeof e=="object","Latest charge is missing from order");let n=q.parse(a.metadata),r=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,o])=>{let s=Y.safeParse(F(String(o)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:r,metadata:n}}import"server-only";import{revalidatePath as J,revalidateTag as P}from"next/cache";import _ from"stripe";import{z as w}from"zod";import"server-only";var f=async()=>{let t={stripeAccount:void 0,storeId:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import K from"stripe";import"server-only";var z=process.env.STRIPE_SECRET_KEY;if(!z)throw new Error("Missing STRIPE_SECRET_KEY");var D=process.env.STRIPE_CURRENCY;if(!D)throw new Error("Missing STRIPE_CURRENCY");var h={StripeSecretKey:z,StripeCurrency:D};var nt=({tags:t,revalidate:e,cache:a})=>new K(h.StripeSecretKey,{typescript:!0,apiVersion:"2024-06-20",httpClient:K.createFetchHttpClient((r,i)=>fetch(r,{...i,cache:a??i?.cache,next:{tags:t??i?.next?.tags,revalidate:e??i?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),it=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],p=({tags:t,revalidate:e,cache:a,tagPrefix:n})=>nt({tags:it(t,n),revalidate:e,cache:a});var k=1e3;function Ot({productId:t,cartId:e}){return e?M.add(p,{productId:t,cartId:e}):M.create(p,{productId:t})}function T(t){return M.get(p,{cartId:t})}function jt(){return M.create(p,{})}async function Qt({cart:t,add:e}){if(!e)return t;let a=await E(e);if(!a)return console.warn(`Product not found: ${e}`),t;let r=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),i=t?W(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:i},lines:r}}async function Gt({cartId:t,productId:e,quantity:a}){let[n,r]=await Promise.all([H(e),T(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!r)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 i=r.cart.metadata??{};a<=0?i[e]="":i[e]=a.toString();let o=W(r)+(n.default_price.unit_amount??0);try{return await S({paymentIntentId:t,data:{metadata:i,amount:o||k}})}catch(s){console.error(s)}finally{P(`cart-${t}`),J("/cart"),J("/cart-overlay")}}async function H(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Ut({slug:t}){let{stripeAccount:e,storeId:a}=await f(),r=await p({tagPrefix:a,tags:["product",`product-${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(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return A(v(r).filter(B))}async function ot(t){let{stripeAccount:e,storeId:a}=await f();if(t.filter?.category){let n=t.filter?.category,i=await p({tagPrefix:a,tags:["product",`category-${n}`],cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':n}),expand:["data.default_price"]},{stripeAccount:e});return A(j(v(i)).filter(B).slice(t.offset,t.first))}else{let r=await p({tagPrefix:a,tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return A(j(v(r)).filter(B).slice(t.offset,t.first))}}async function Yt(){let{stripeAccount:t,storeId:e}=await f();return await p({tagPrefix:e,tags:["shipping"],cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t})}async function I(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["shipping",`shipping-${t}`],cache:"force-cache"});try{return await n.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Vt(t){let a=(await ot({first:100})).map(r=>r.metadata.category),n=new Set(a);return Array.from(n).filter(Boolean)}async function zt(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["products","search"],cache:"force-cache"}),r=L(t.query),i=await n.products.search({limit:100,query:`name~"${r}" OR description~"${r}" OR metadata["slug"]:"${r}" OR metadata["category"]:"${r}"`,expand:["data.default_price"]},{stripeAccount:e});return A(v(i).filter(o=>o.active&&!o.deleted))}async function Dt(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["files",`file-${t}`],cache:"force-cache"});try{return await n.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Kt(){let{stripeAccount:t,storeId:e}=await f(),a=p({tagPrefix:e,tags:["account"],cache:"force-cache"});try{let[n,r]=await U(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(n){if(console.error(n),n instanceof _.errors.StripeError&&n.code==="resource_missing")return null;throw n}}async function ct(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["order",`order-${t}`],cache:"force-cache"});try{let r=await n.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return V(r)}catch(r){if(r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Jt(t){let e=await ct(t);if(!e)return null;let a=tt(e.metadata),n=await Promise.all(a.map(async([o,s])=>({product:await E(o),quantity:s}))),{metadata:{shippingRateId:r}}=e,i=r&&await I(r);return{order:e,lines:n.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:i||null}}var E=async t=>{let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}},Z=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],tt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),st=async(t,e)=>{let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status))return Q(i)}catch(i){if(console.error(i),i instanceof _.errors.StripeError&&i.code==="resource_missing")return null;throw i}};async function G(t){let e=tt(t);return await Promise.all(e.map(async([n,r])=>({product:await E(n),quantity:r})))}var et=async(t,e)=>{let a=await st(t,e);if(!a)return null;let n=await G(a.metadata),{metadata:{shippingRateId:r}}=a,i=r&&await I(r);return{cart:a,lines:n.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:i||null}},ut=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,dt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function pt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let r=Date.now(),i=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!i||r>=i)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,u=dt.some(g=>!a[g]&&!t.cart.metadata[g]?!1:a[g]!==t.cart.metadata[g]),m=n.length!==t.lines.length||n.some(g=>{let d=t.lines.find(x=>x.product.id===g.product?.id);return g.product?.default_price.unit_amount!==d?.product.default_price.unit_amount||g.quantity!==d?.quantity});return s&&o!==s||u||m}var Xt=t=>w.object({name:w.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:w.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:w.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:w.string({required_error:t.line1Required}).min(1,t.line1Required),line2:w.string().optional().nullable().default(""),postalCode:w.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:w.string().optional().nullable().default(""),phone:w.string().optional().nullable().default(""),taxId:w.string().optional().nullable().default("")}),lt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:r})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:i,storeId:o}=await f(),s=p({tagPrefix:o,tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let u=n?await I(n):null,m=typeof u?.tax_code=="string"?u.tax_code:u?.tax_code?.id,l=await ft(),y=h.StripeCurrency==="usd"||h.StripeCurrency==="cad"?"exclusive":"inclusive",g=l.defaults.tax_behavior==="inferred_by_currency"?y:l.defaults.tax_behavior??y;l.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${h.StripeCurrency}: ${y}.`),console.time("createTaxCalculation ${cartId}");let d=await s.tax.calculations.create({expand:["line_items"],line_items:t.map(x=>({...x,tax_behavior:x.tax_behavior??g})),currency:h.StripeCurrency,shipping_cost:u?.active&&u?.fixed_amount?{amount:u.fixed_amount.amount,tax_behavior:u.tax_behavior==="inclusive"?"inclusive":u.tax_behavior==="exclusive"?"exclusive":g,tax_code:m??l.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:r?[{type:"eu_vat",value:r}]: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:i});return console.timeEnd("createTaxCalculation ${cartId}"),d},X={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},S=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:r}=await f(),i=await et(p,t);C(i,`Cart not found: ${t}`);let o=q.parse({...i.cart.metadata,...e.metadata}),s=await G(o),m=!a&&pt({oldCart:i,data:e,mergedMetadata:o,lines:s})?await lt({cartId:t,taxId:o.taxId??null,shippingRateId:o.shippingRateId??null,billingAddress:{country:o["billingAddress.country"]??"",city:o["billingAddress.city"]??"",line1:o["billingAddress.line1"]??"",line2:o["billingAddress.line2"]??"",name:o["billingAddress.name"]??"",postalCode:o["billingAddress.postalCode"]??"",state:o["billingAddress.state"]??""},lineItems:s.map(({product:d,quantity:x})=>{if(d?.default_price.unit_amount)return{product:d.id,reference:[d.metadata.slug,d.metadata.variant].filter(Boolean).join("-"),quantity:x,amount:d.default_price.unit_amount*x,tax_behavior:d.default_price.tax_behavior==="exclusive"?"exclusive":d.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:d.tax_code?typeof d.tax_code=="string"?d.tax_code:d.tax_code.id:void 0}}).filter(Boolean)}):null,l=e.amount?e.amount.toString():null;if(m){let d=Object.fromEntries(m.tax_breakdown.map(b=>({taxType:b.tax_rate_details.tax_type,taxPercentage:b.tax_rate_details.percentage_decimal,taxAmount:b.amount})).map((b,rt)=>[`taxBreakdown${rt}`,JSON.stringify(b)])),x=p({tagPrefix:r,tags:[],cache:"no-cache"});console.time(`updatePaymentIntent ${t}`);let N=await x.paymentIntents.update(t,{...e,amount:m.amount_total,metadata:{...o,...l&&{netAmount:l},...X,...d,taxCalculationId:m.id,taxCalculationExp:m?.expires_at}},{stripeAccount:n});return console.timeEnd(`updatePaymentIntent ${t}`),N}let y=p({tagPrefix:r,tags:[],cache:"no-cache"});console.time(`updatePaymentIntent ${t}`);let g=await y.paymentIntents.update(t,{...e,metadata:{...o,...l&&{netAmount:l},...a&&{...X,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n});return console.timeEnd(`updatePaymentIntent ${t}`),g},M={async create(t,{productId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,cache:"no-cache"});try{let i=e?await E(e):null;return await r.paymentIntents.create({currency:h.StripeCurrency,amount:i?.default_price.unit_amount||k,automatic_payment_methods:{enabled:!0},metadata:{...i&&{[i.id]:"1"}}},{stripeAccount:a})}catch(i){throw console.error(i),i}},async get(t,{cartId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status)){let o=Q(i);if(!o)return null;let s=await G(o.metadata),{metadata:{shippingRateId:u}}=o,m=u&&await I(u);return{cart:o,lines:s.map(({product:l,quantity:y})=>l?{product:l,quantity:y}:null).filter(Boolean),shippingRate:m||null}}}catch(i){if(console.error(i),i instanceof _.errors.StripeError&&i.code==="resource_missing")return null;throw i}},async add(t,{cartId:e,productId:a}){return(async({productId:r,cartId:i,operation:o,clearTaxCalculation:s})=>{let[u,m]=await Promise.all([E(r),et(t,i)]);if(!u)throw new Error(`Product not found: ${r}`);if(!m)throw new Error(`Cart not found: ${i}`);if(h.StripeCurrency.toLowerCase()!==u.default_price.currency.toLowerCase())throw new Error(`Product currency ${u.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let l=m.cart.metadata??{},d=R(l[r])+(o==="INCREASE"?1:-1);d<=0?l[r]="":l[r]=d.toString();let x=ut(m)+(u.default_price.unit_amount??0);try{return await S({paymentIntentId:i,data:{metadata:l,amount:x||k},clearTaxCalculation:s})}catch(N){console.error(N)}finally{P(`cart-${i}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},W=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+mt(t):0,mt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function Ht({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[r,i]=await Promise.all([H(t),T(e)]);if(!r)throw new Error(`Product not found: ${t}`);if(!i)throw new Error(`Cart not found: ${e}`);if(h.StripeCurrency?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let o=i.cart.metadata??{},m=R(o[t])+(a==="INCREASE"?1:-1);m<=0?o[t]="":o[t]=m.toString();let l=W(i)+(r.default_price.unit_amount??0);try{return await S({paymentIntentId:e,data:{metadata:o,amount:l||k},clearTaxCalculation:n})}catch(y){console.error(y)}finally{P(`cart-${e}`)}}var Zt=async({cartId:t,taxId:e})=>{let a=await T(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){console.error(n)}finally{P(`cart-${t}`)}};async function te({cartId:t,shippingRateId:e}){let a=await T(t);if(!a)throw new Error(`Cart not found: ${t}`);let n=await I(e);if(!n)throw new Error(`Shipping rate not found: ${e}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:W({...a,shippingRate:n})}})}catch(r){console.error(r)}finally{P(`cart-${t}`)}}async function ee({cartId:t,billingAddress:e}){if(!await T(t))throw new Error(`Cart not found: ${t}`);try{return await S({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??""}}})}catch(n){console.error(n)}finally{P(`cart-${t}`)}}async function ft(){let{stripeAccount:t,storeId:e}=await f();return await p({tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function re(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{nt as StripeClient,Kt as accountGet,ut as calculateCartTotalNet,mt as calculateCartTotalNetWithoutShipping,W as calculateCartTotalPossiblyWithTax,Ot as cartAdd,Qt as cartAddOptimistic,Ht as cartChangeQuantity,re as cartCount,jt as cartCreate,T as cartGet,ee as cartSaveBillingAddress,te as cartSaveShipping,Zt as cartSaveTax,Gt as cartSetQuantity,Vt as categoryBrowse,Dt as fileGet,Xt as getAddressSchema,et as getCartWithProductsById,tt as getProductsFromCart,Jt as orderGet,ot as productBrowse,Ut as productGet,H as productGetById,zt as productSearch,p as provider,Yt as shippingBrowse,I as shippingGet,ft as taxDefaultGet};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "commerce-kit",
4
- "version": "0.0.12",
4
+ "version": "0.0.13",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [