commerce-kit 0.0.29 → 0.0.31

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.d.ts CHANGED
@@ -21,6 +21,8 @@ declare function cartGet(cartId: string): Promise<{
21
21
  taxCalculationId?: string | undefined;
22
22
  taxCalculationExp?: string | undefined;
23
23
  taxId?: string | undefined;
24
+ couponCode?: string | undefined;
25
+ taxedAmount?: string | undefined;
24
26
  "billingAddress.city"?: string | undefined;
25
27
  "billingAddress.country"?: string | undefined;
26
28
  "billingAddress.line1"?: string | undefined;
@@ -36,6 +38,7 @@ declare function cartGet(cartId: string): Promise<{
36
38
  taxBreakdown4?: string | undefined;
37
39
  taxBreakdown5?: string | undefined;
38
40
  } & Record<string, string>;
41
+ customer: Stripe.Customer | null;
39
42
  payment_method: Stripe.PaymentMethod | null;
40
43
  taxBreakdown: {
41
44
  taxPercentage: string;
@@ -58,7 +61,6 @@ declare function cartGet(cartId: string): Promise<{
58
61
  confirmation_method: Stripe.PaymentIntent.ConfirmationMethod;
59
62
  created: number;
60
63
  currency: string;
61
- customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
62
64
  description: string | null;
63
65
  invoice: string | Stripe.Invoice | null;
64
66
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
@@ -129,6 +131,8 @@ declare function cartAddOptimistic({ cart, add, }: {
129
131
  taxCalculationId?: string | undefined;
130
132
  taxCalculationExp?: string | undefined;
131
133
  taxId?: string | undefined;
134
+ couponCode?: string | undefined;
135
+ taxedAmount?: string | undefined;
132
136
  "billingAddress.city"?: string | undefined;
133
137
  "billingAddress.country"?: string | undefined;
134
138
  "billingAddress.line1"?: string | undefined;
@@ -144,6 +148,7 @@ declare function cartAddOptimistic({ cart, add, }: {
144
148
  taxBreakdown4?: string | undefined;
145
149
  taxBreakdown5?: string | undefined;
146
150
  } & Record<string, string>) | undefined;
151
+ customer?: Stripe.Customer | null | undefined;
147
152
  payment_method?: Stripe.PaymentMethod | null | undefined;
148
153
  taxBreakdown?: {
149
154
  taxPercentage: string;
@@ -165,7 +170,6 @@ declare function cartAddOptimistic({ cart, add, }: {
165
170
  confirmation_method?: Stripe.PaymentIntent.ConfirmationMethod | undefined;
166
171
  created?: number | undefined;
167
172
  currency?: string | undefined;
168
- customer?: string | Stripe.Customer | Stripe.DeletedCustomer | null | undefined;
169
173
  description?: string | null | undefined;
170
174
  invoice?: string | Stripe.Invoice | null | undefined;
171
175
  last_payment_error?: Stripe.PaymentIntent.LastPaymentError | null | undefined;
@@ -366,6 +370,8 @@ declare function orderGet(orderId: string): Promise<{
366
370
  taxCalculationId?: string | undefined;
367
371
  taxCalculationExp?: string | undefined;
368
372
  taxId?: string | undefined;
373
+ couponCode?: string | undefined;
374
+ taxedAmount?: string | undefined;
369
375
  "billingAddress.city"?: string | undefined;
370
376
  "billingAddress.country"?: string | undefined;
371
377
  "billingAddress.line1"?: string | undefined;
@@ -492,6 +498,8 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
492
498
  taxCalculationId?: string | undefined;
493
499
  taxCalculationExp?: string | undefined;
494
500
  taxId?: string | undefined;
501
+ couponCode?: string | undefined;
502
+ taxedAmount?: string | undefined;
495
503
  "billingAddress.city"?: string | undefined;
496
504
  "billingAddress.country"?: string | undefined;
497
505
  "billingAddress.line1"?: string | undefined;
@@ -507,6 +515,7 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
507
515
  taxBreakdown4?: string | undefined;
508
516
  taxBreakdown5?: string | undefined;
509
517
  } & Record<string, string>;
518
+ customer: Stripe.Customer | null;
510
519
  payment_method: Stripe.PaymentMethod | null;
511
520
  taxBreakdown: {
512
521
  taxPercentage: string;
@@ -529,7 +538,6 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
529
538
  confirmation_method: Stripe.PaymentIntent.ConfirmationMethod;
530
539
  created: number;
531
540
  currency: string;
532
- customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
533
541
  description: string | null;
534
542
  invoice: string | Stripe.Invoice | null;
535
543
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var z=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},L=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 st=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),U=t=>Object.entries(t).map(([e,n])=>`${e}:"${st(n)}"`).join(" AND ").trim();function M(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),i=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(i)||a===i?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(i)?-1:a-i})}var ct=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?1/0:t)});function q({default_price:t,marketing_features:e,...n}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:e.map(a=>a.name).filter(Boolean),metadata:ct.parse(n.metadata)}}function G(t){return t.data.map(q)}function J(t){return t}function X(t){return t.data.map(J)}function Y(t){return t.filter((e,n,a)=>n===a.findIndex(i=>i.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,K=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())),H=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function D(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let n=K.parse(t.metadata),a=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,r])=>{let o=H.safeParse(j(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:e,taxBreakdown:a}}function Z({payment_method:t,latest_charge:e,...n}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let a=K.parse(n.metadata),i=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let s=H.safeParse(j(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import{revalidateTag as E}from"next/cache";import R from"stripe";import{z as _}from"zod";var p=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};import tt from"stripe";var ut=process.env.STRIPE_SECRET_KEY,dt=process.env.STRIPE_CURRENCY,g={StripeSecretKey:ut,StripeCurrency:dt};var pt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],m=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:i})=>{let r=i??g.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let o=pt(t,a);return new tt(r,{typescript:!0,apiVersion:"2024-09-30.acacia",httpClient:tt.createFetchHttpClient((h,d)=>fetch(h,{...d,cache:n??d?.cache,next:{tags:o??d?.next?.tags,revalidate:e??d?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var b={DEBUG:0,LOG:1,WARN:2,ERROR:3},lt="LOG",mt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:lt,A=b[mt],u={time(t){A>b.DEBUG||console.time(t)},timeEnd(t){A>b.DEBUG||console.timeEnd(t)},log(...t){A>b.LOG||console.log(...t)},dir(t,e){A>b.LOG||console.dir(t,e)},warn(...t){A>b.WARN||console.warn(...t)},error(...t){A>b.ERROR||console.error(...t)}};var C=t=>t.filter(Boolean),w={accountGetById:{tags:({accountId:t})=>C(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>C(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>C(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>C(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>C(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>C(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>C(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>C(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>C(["tax-settings"]),revalidate:()=>{}}};import{neon as ft}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=ft(process.env.DATABASE_URL));var O=1e3;function te({productId:t,cartId:e}){return e?gt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function gt({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),at(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(i.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(g.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=r.cart.metadata??{},d=L(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let y=Ct(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:y||O},clearTaxCalculation:a})}catch(l){u.error(l)}finally{E(`cart-${e}`)}}async function B(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(rt.includes(r.status)){let o=D(r);if(!o)return null;let s=await V(o.metadata),{metadata:{shippingRateId:h}}=o,d=h&&await N(h);return{cart:o,lines:s.map(({product:y,quantity:l})=>y?{product:y,quantity:l}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,cache:"no-cache"});if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await k(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await i.paymentIntents.create({currency:g.StripeCurrency,amount:r?.default_price.unit_amount||O,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw u.error(r),r}}async function ee({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return u.warn(`Product not found: ${e}`),t;let i=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),r=t?F(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:i}}async function re({cartId:t,productId:e,quantity:n}){let[a,i]=await Promise.all([Q(e),B(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!i)throw new Error(`Cart not found: ${t}`);if(g.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let r=i.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let o=F(i)+(a.default_price.unit_amount??0);try{return await I({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{E(`cart-${t}`)}}async function Q(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ne({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),r=await m({secretKey:a,tagPrefix:n,tags:w.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:U({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.all(r.data.map(o=>Q(o.id))),M(G(r).filter(W))}async function ht(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p();if(t.filter?.category){let i=t.filter?.category,o=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:U({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return M(Y(G(o)).filter(W).slice(t.offset,t.first))}else{let r=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return M(Y(G(r)).filter(W).slice(t.offset,t.first))}}async function ae(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return X(i)}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await i.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie(){let e=(await ht({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function oe(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await i.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),a=m({secretKey:n,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await z(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),o=r?.settings?.branding.logo??null;return!o||typeof o=="string"?{account:r,logo:null}:{account:r,logo:o}}catch(i){if(u.error(i),i instanceof R.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return Z(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(t){let e=await xt(t);if(!e)return null;let n=nt(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await N(i);return{order:e,lines:a.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}},rt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],nt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),wt=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(rt.includes(r.status))return D(r)}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function V(t){let e=nt(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var at=async t=>{let e=await wt(t);if(!e)return null;let n=await V(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await N(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||null}},Ct=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0,_t=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function St({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,h=_t.some(x=>!n[x]&&!t.cart.metadata[x]?!1:n[x]!==t.cart.metadata[x]),d=a.length!==t.lines.length||a.some(x=>{let v=t.lines.find(f=>f.product.id===x.product?.id);return x.product?.default_price.unit_amount!==v?.product.default_price.unit_amount||x.quantity!==v?.quantity});return s&&o!==s||h||d}var ue=t=>_.object({name:_.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:_.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:_.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:_.string({required_error:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({required_error: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("")}),bt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:o,secretKey:s}=await p(),h=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await N(a):null,y=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,l=await vt(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",v=l.defaults.tax_behavior==="inferred_by_currency"?x:l.defaults.tax_behavior??x;l.defaults.tax_behavior||u.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${x}.`),u.time("createTaxCalculation ${cartId}");let f=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??v})),currency:g.StripeCurrency,shipping_cost:d?.active&&d?.fixed_amount?{amount:d.fixed_amount.amount,tax_behavior:d.tax_behavior==="inclusive"?"inclusive":d.tax_behavior==="exclusive"?"exclusive":v,tax_code:y??l.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:i?[{type:"eu_vat",value:i}]: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 u.timeEnd("createTaxCalculation ${cartId}"),f},et={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},I=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await p(),o=await at(t);S(o,`Cart not found: ${t}`);let s=K.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let h=await V(s);u.timeEnd("getProductsFromMetadata");let y=!n&&St({oldCart:o,data:e,mergedMetadata:s,lines:h})?await bt({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:h.map(({product:f,quantity:P})=>{if(f?.default_price.unit_amount)return{product:f.id,reference:[f.metadata.slug,f.metadata.variant].filter(Boolean).join("-"),quantity:P,amount:f.default_price.unit_amount*P,tax_behavior:f.default_price.tax_behavior==="exclusive"?"exclusive":f.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:f.tax_code?typeof f.tax_code=="string"?f.tax_code:f.tax_code.id:void 0}}).filter(Boolean)}):null,l=e.amount?e.amount.toString():null;if(y){let f=Object.fromEntries(y.tax_breakdown.map($=>({taxType:$.tax_rate_details.tax_type,taxPercentage:$.tax_rate_details.percentage_decimal,taxAmount:$.amount})).map(($,ot)=>[`taxBreakdown${ot}`,JSON.stringify($)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let it=await P.paymentIntents.update(t,{...e,amount:y.amount_total,metadata:{...s,...l&&{netAmount:l},...et,...f,taxCalculationId:y.id,taxCalculationExp:y?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),it}let x=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let v=await x.paymentIntents.update(t,{...e,metadata:{...s,...l&&{netAmount:l},...n&&{...et,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),v},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Rt(t):0,Rt=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function de({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([Q(t),B(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(g.StripeCurrency?.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=r.cart.metadata??{},d=L(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let y=F(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:y||O},clearTaxCalculation:a})}catch(l){u.error(l)}finally{E(`cart-${e}`)}}var pe=async({cartId:t,email:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}},le=async({cartId:t,taxId:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}};async function me({cartId:t,shippingRateId:e}){let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);u.time(`cartSaveShipping ${t}`);let a=await N(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:F({...n,shippingRate:a})}});return u.timeEnd(`updatePaymentIntent ${t}`),i}catch(i){u.error(i)}finally{E(`cart-${t}`)}}async function fe({cartId:t,billingAddress:e}){if(!await B(t))throw new Error(`Cart not found: ${t}`);try{return await I({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(a){u.error(a)}finally{E(`cart-${t}`)}}async function vt(){let{stripeAccount:t,storeId:e,secretKey:n}=await p();return await m({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ge(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function ye(t){if(!T)return null;let{storeId:e}=await p();return await T`
2
- select * from reviews
1
+ import{z as s}from"zod";function S(t,e){if(!t)throw new Error(e)}var X=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},L=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},U=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var ct=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),D=t=>Object.entries(t).map(([e,n])=>`${e}:"${ct(n)}"`).join(" AND ").trim();function G(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var ut=s.object({category:s.string().optional(),order:s.coerce.number().optional(),slug:s.string(),variant:s.string().optional(),stock:s.coerce.number().optional().transform(t=>t===void 0?1/0:t)});function q({default_price:t,marketing_features:e,...n}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:e.map(a=>a.name).filter(Boolean),metadata:ut.parse(n.metadata)}}function W(t){return t.data.map(q)}function H(t){return t}function Z(t){return t.data.map(H)}function Y(t){return t.filter((e,n,a)=>n===a.findIndex(o=>o.metadata.slug===e.metadata.slug))}var K=t=>!t.deleted&&t.active,O=s.object({shippingRateId:s.string().optional(),taxCalculationId:s.string().optional(),taxCalculationExp:s.string().optional(),taxId:s.string().optional(),couponCode:s.string().optional(),taxedAmount: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())),tt=s.object({taxType:s.string(),taxPercentage:s.string(),taxAmount:s.number()});function Q(t){let e=t.payment_method;S(typeof e!="string","Payment method should not be a string");let n=t.customer;S(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=O.parse(t.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let d=tt.safeParse(U(String(i)));return d.success?d.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:e,taxBreakdown:o}}function et({payment_method:t,latest_charge:e,...n}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let a=O.parse(n.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let d=tt.safeParse(U(String(i)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:a}}import{revalidateTag as E}from"next/cache";import b from"stripe";import{z as C}from"zod";var m=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};import rt from"stripe";var dt=process.env.STRIPE_SECRET_KEY,pt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:dt,StripeCurrency:pt};var lt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],f=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:o})=>{let r=o??y.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let i=lt(t,a);return new rt(r,{typescript:!0,apiVersion:"2024-09-30.acacia",httpClient:rt.createFetchHttpClient((p,u)=>fetch(p,{...u,cache:n??u?.cache,next:{tags:i??u?.next?.tags,revalidate:e??u?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var v={DEBUG:0,LOG:1,WARN:2,ERROR:3},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in v?process.env.LOG_LEVEL:mt,T=v[ft],c={time(t){T>v.DEBUG||console.time(t)},timeEnd(t){T>v.DEBUG||console.timeEnd(t)},log(...t){T>v.LOG||console.log(...t)},dir(t,e){T>v.LOG||console.dir(t,e)},warn(...t){T>v.WARN||console.warn(...t)},error(...t){T>v.ERROR||console.error(...t)}};var w=t=>t.filter(Boolean),x={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{neon as gt}from"@neondatabase/serverless";var B;process.env.DATABASE_URL&&(B=gt(process.env.DATABASE_URL));var F=1e3;function ne({productId:t,cartId:e}){return e?yt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):ht({productId:t})}async function yt({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([k(t),it(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 i=r.cart.metadata??{},u=L(i[t])+(n==="INCREASE"?1:-1);u<=0?i[t]="":i[t]=u.toString();let _=_t(r)+(o.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:i,amount:_||F},clearTaxCalculation:a})}catch(l){c.error(l)}finally{E(`cart-${e}`)}}async function $(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(at.includes(r.status)){let i=Q(r);if(!i)return null;let d=await z(i.metadata),{metadata:{shippingRateId:p}}=i,u=p&&await N(p);return{cart:i,lines:d.map(({product:_,quantity:l})=>_?{product:_,quantity:l}:null).filter(Boolean),shippingRate:u||null}}}catch(r){if(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ht({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await k(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||F,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw c.error(r),r}}async function ae({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return c.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),r=t?j(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:o}}async function oe({cartId:t,productId:e,quantity:n}){let[a,o]=await Promise.all([V(e),$(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(y.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let r=o.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let i=j(o)+(a.default_price.unit_amount??0);try{return await I({paymentIntentId:t,data:{metadata:r,amount:i||F}})}catch(d){c.error(d)}finally{E(`cart-${t}`)}}async function V(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),r=await f({secretKey:a,tagPrefix:n,tags:x.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:D({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 await Promise.all(r.data.map(i=>V(i.id))),G(W(r).filter(K))}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m();if(t.filter?.category){let o=t.filter?.category,i=await f({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:D({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return G(Y(W(i)).filter(K).slice(t.offset,t.first))}else{let r=await f({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return G(Y(W(r)).filter(K).slice(t.offset,t.first))}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await m(),o=await f({secretKey:n,tagPrefix:e,tags:x.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return Z(o)}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(){let e=(await xt({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function ue(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function de(){let{stripeAccount:t,storeId:e,secretKey:n}=await m(),a=f({secretKey:n,tagPrefix:e,tags:x.accountGetById.tags({}),cache:"force-cache"});try{let[o,r]=await X(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(o){if(c.error(o),o instanceof b.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge","customer"]},{stripeAccount:e});return et(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function pe(t){let e=await wt(t);if(!e)return null;let n=ot(e.metadata),a=await Promise.all(n.map(async([i,d])=>({product:await k(i),quantity:d}))),{metadata:{shippingRateId:o}}=e,r=o&&await N(o);return{order:e,lines:a.map(({product:i,quantity:d})=>i?{product:i,quantity:d}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},at=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],ot=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Ct=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(at.includes(r.status))return Q(r)}catch(r){if(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function z(t){let e=ot(t);return await Promise.all(e.map(async([a,o])=>({product:await k(a),quantity:o})))}var it=async t=>{let e=await Ct(t);if(!e)return null;let n=await z(e.metadata),{metadata:{shippingRateId:a}}=e,o=a&&await N(a);return{cart:e,lines:n.map(({product:r,quantity:i})=>r?{product:r,quantity:i}:null).filter(Boolean),shippingRate:o||null}},_t=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0,St=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];function bt({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||o>=r)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,d=e.amount,p=St.some(h=>!n[h]&&!t.cart.metadata[h]?!1:n[h]!==t.cart.metadata[h]),u=a.length!==t.lines.length||a.some(h=>{let P=t.lines.find(A=>A.product.id===h.product?.id);return h.product?.default_price.unit_amount!==P?.product.default_price.unit_amount||h.quantity!==P?.quantity});return d&&i!==d||p||u}var le=t=>C.object({name:C.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:C.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:C.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:C.string({required_error:t.line1Required}).min(1,t.line1Required),line2:C.string().optional().nullable().default(""),postalCode:C.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:C.string().optional().nullable().default(""),phone:C.string().optional().nullable().default(""),taxId:C.string().optional().nullable().default(""),email:C.string().optional().nullable().default("")}),Rt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,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:i,secretKey:d}=await m(),p=f({secretKey:d,tagPrefix:i,tags:x.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let u=a?await N(a):null,_=typeof u?.tax_code=="string"?u.tax_code:u?.tax_code?.id,l=await It(),h=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",P=l.defaults.tax_behavior==="inferred_by_currency"?h:l.defaults.tax_behavior??h;l.defaults.tax_behavior||c.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${h}.`),c.time("createTaxCalculation ${cartId}");let A=await p.tax.calculations.create({expand:["line_items"],line_items:t.map(R=>({...R,tax_behavior:R.tax_behavior??P})),currency:y.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":P,tax_code:_??l.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 c.timeEnd("createTaxCalculation ${cartId}"),console.log(JSON.stringify(A).length),A},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};async function vt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({secretKey:a,tagPrefix:n,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(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function Pt(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}var I=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:o,secretKey:r}=await m(),i=await it(t);S(i,`Cart not found: ${t}`);let d=e.amount?e.amount.toString():null,p=O.parse({...i.cart.metadata,...e.metadata});c.time("getProductsFromMetadata");let u=await z(p);c.timeEnd("getProductsFromMetadata");let l=!n&&bt({oldCart:i,data:e,mergedMetadata:p,lines:u})?await Rt({cartId:t,taxId:p.taxId??null,shippingRateId:p.shippingRateId??null,billingAddress:{country:p["billingAddress.country"]??"",city:p["billingAddress.city"]??"",line1:p["billingAddress.line1"]??"",line2:p["billingAddress.line2"]??"",name:p["billingAddress.name"]??"",postalCode:p["billingAddress.postalCode"]??"",state:p["billingAddress.state"]??""},lineItems:u.map(({product:g,quantity:M})=>{if(g?.default_price.unit_amount)return{product:g.id,reference:[g.metadata.slug,g.metadata.variant].filter(Boolean).join("-"),quantity:M,amount:g.default_price.unit_amount*M,tax_behavior:g.default_price.tax_behavior==="exclusive"?"exclusive":g.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:g.tax_code?typeof g.tax_code=="string"?g.tax_code:g.tax_code.id:void 0}}).filter(Boolean)}):null,h=e.customer?await vt(e.customer):i.cart.customer,P=f({secretKey:r,tagPrefix:o,cache:"no-cache"});c.time(`paymentIntents.update ${t}`);let A=l&&Object.fromEntries(l.tax_breakdown.map(g=>({taxType:g.tax_rate_details.tax_type,taxPercentage:g.tax_rate_details.percentage_decimal,taxAmount:g.amount})).map((g,M)=>[`taxBreakdown${M}`,JSON.stringify(g)])),R=l?l.amount_total:e.amount,J=R&&h?.discount?.coupon.valid?Pt(R,h.discount):R,st=await P.paymentIntents.update(t,{...e,...J&&{amount:J},metadata:{...p,...d&&{netAmount:d},...R&&{taxedAmount:R},...l?{...nt,...A,taxCalculationId:l.id,taxCalculationExp:l?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:a});return c.timeEnd(`paymentIntents.update ${t}`),st},j=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Et(t):0,Et=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function me({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([V(t),$(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);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 i=r.cart.metadata??{},u=L(i[t])+(n==="INCREASE"?1:-1);u<=0?i[t]="":i[t]=u.toString();let _=j(r)+(o.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:i,amount:_||F},clearTaxCalculation:a})}catch(l){c.error(l)}finally{E(`cart-${e}`)}}var fe=async({cartId:t,email:e})=>{let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){c.error(a)}finally{E(`cart-${t}`)}},ge=async({cartId:t,taxId:e})=>{let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){c.error(a)}finally{E(`cart-${t}`)}};async function ye({cartId:t,shippingRateId:e}){let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);c.time(`cartSaveShipping ${t}`);let a=await N(e);if(c.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{c.time(`updatePaymentIntent ${t}`);let o=await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:j({...n,shippingRate:a})}});return c.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){c.error(o)}finally{E(`cart-${t}`)}}async function he({cartId:t,billingAddress:e}){if(!await $(t))throw new Error(`Cart not found: ${t}`);try{return await I({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(a){c.error(a)}finally{E(`cart-${t}`)}}async function It(){let{stripeAccount:t,storeId:e,secretKey:n}=await m();return await f({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function xe(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function we(t){if(!B)return null;let{storeId:e}=await m();return await B`
2
+ select * from reviews
3
3
  where product_id = ${t.productId} and store_id = ${e}
4
- order by created_at desc
5
- limit ${t.first??100}
4
+ order by created_at desc
5
+ limit ${t.first??100}
6
6
  offset ${t.offset??0}
7
- `}async function he(t){if(!T)return null;let{storeId:e}=await p();return await T`
8
- insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
7
+ `}async function Ce(t){if(!B)return null;let{storeId:e}=await m();return await B`
8
+ insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
9
9
  values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
10
- `}var xe=p;export{se as accountGet,Ct as calculateCartTotalNet,Rt as calculateCartTotalNetWithoutShipping,F as calculateCartTotalPossiblyWithTax,te as cartAdd,ee as cartAddOptimistic,de as cartChangeQuantity,ge as cartCount,yt as cartCreate,B as cartGet,fe as cartSaveBillingAddress,pe as cartSaveEmail,me as cartSaveShipping,le as cartSaveTax,re as cartSetQuantity,gt as cartUpdateQuantity,ie as categoryBrowse,xe as contextGet,oe as fileGet,ue as getAddressSchema,at as getCartWithProductsById,nt as getProductsFromCart,V as getProductsFromMetadata,ce as orderGet,ht as productBrowse,ne as productGet,Q as productGetById,he as productReviewAdd,ye as productReviewBrowse,m as provider,ae as shippingBrowse,N as shippingGet,vt as taxDefaultGet,I as updatePaymentIntent};
10
+ `}var _e=m;export{de as accountGet,_t as calculateCartTotalNet,Et as calculateCartTotalNetWithoutShipping,j as calculateCartTotalPossiblyWithTax,ne as cartAdd,ae as cartAddOptimistic,me as cartChangeQuantity,xe as cartCount,ht as cartCreate,$ as cartGet,he as cartSaveBillingAddress,fe as cartSaveEmail,ye as cartSaveShipping,ge as cartSaveTax,oe as cartSetQuantity,yt as cartUpdateQuantity,ce as categoryBrowse,_e as contextGet,ue as fileGet,le as getAddressSchema,it as getCartWithProductsById,ot as getProductsFromCart,z as getProductsFromMetadata,pe as orderGet,xt as productBrowse,ie as productGet,V as productGetById,Ce as productReviewAdd,we as productReviewBrowse,f as provider,se as shippingBrowse,N as shippingGet,It as taxDefaultGet,I as updatePaymentIntent};
@@ -170,6 +170,8 @@ declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
170
170
  taxCalculationId: z.ZodOptional<z.ZodString>;
171
171
  taxCalculationExp: z.ZodOptional<z.ZodString>;
172
172
  taxId: z.ZodOptional<z.ZodString>;
173
+ couponCode: z.ZodOptional<z.ZodString>;
174
+ taxedAmount: z.ZodOptional<z.ZodString>;
173
175
  "billingAddress.city": z.ZodOptional<z.ZodString>;
174
176
  "billingAddress.country": z.ZodOptional<z.ZodString>;
175
177
  "billingAddress.line1": z.ZodOptional<z.ZodString>;
@@ -189,6 +191,8 @@ declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
189
191
  taxCalculationId?: string | undefined;
190
192
  taxCalculationExp?: string | undefined;
191
193
  taxId?: string | undefined;
194
+ couponCode?: string | undefined;
195
+ taxedAmount?: string | undefined;
192
196
  "billingAddress.city"?: string | undefined;
193
197
  "billingAddress.country"?: string | undefined;
194
198
  "billingAddress.line1"?: string | undefined;
@@ -208,6 +212,8 @@ declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
208
212
  taxCalculationId?: string | undefined;
209
213
  taxCalculationExp?: string | undefined;
210
214
  taxId?: string | undefined;
215
+ couponCode?: string | undefined;
216
+ taxedAmount?: string | undefined;
211
217
  "billingAddress.city"?: string | undefined;
212
218
  "billingAddress.country"?: string | undefined;
213
219
  "billingAddress.line1"?: string | undefined;
@@ -249,6 +255,8 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
249
255
  taxCalculationId?: string | undefined;
250
256
  taxCalculationExp?: string | undefined;
251
257
  taxId?: string | undefined;
258
+ couponCode?: string | undefined;
259
+ taxedAmount?: string | undefined;
252
260
  "billingAddress.city"?: string | undefined;
253
261
  "billingAddress.country"?: string | undefined;
254
262
  "billingAddress.line1"?: string | undefined;
@@ -264,6 +272,7 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
264
272
  taxBreakdown4?: string | undefined;
265
273
  taxBreakdown5?: string | undefined;
266
274
  } & Record<string, string>;
275
+ customer: Stripe.Customer | null;
267
276
  payment_method: Stripe.PaymentMethod | null;
268
277
  taxBreakdown: {
269
278
  taxPercentage: string;
@@ -286,7 +295,6 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
286
295
  confirmation_method: Stripe.PaymentIntent.ConfirmationMethod;
287
296
  created: number;
288
297
  currency: string;
289
- customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
290
298
  description: string | null;
291
299
  invoice: string | Stripe.Invoice | null;
292
300
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
@@ -326,6 +334,8 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
326
334
  taxCalculationId?: string | undefined;
327
335
  taxCalculationExp?: string | undefined;
328
336
  taxId?: string | undefined;
337
+ couponCode?: string | undefined;
338
+ taxedAmount?: string | undefined;
329
339
  "billingAddress.city"?: string | undefined;
330
340
  "billingAddress.country"?: string | undefined;
331
341
  "billingAddress.line1"?: string | undefined;
package/dist/internal.js CHANGED
@@ -1 +1 @@
1
- import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var u=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=t=>Object.entries(t).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function w(t){return t.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=e.object({category:e.string().optional(),order:e.coerce.number().optional(),slug:e.string(),variant:e.string().optional(),stock:e.coerce.number().optional().transform(t=>t===void 0?1/0:t)});function f({default_price:t,marketing_features:r,...n}){return i(t,"Product must have a default price"),i(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function k(t){return t.data.map(f)}function x(t){return t}function N(t){return t.data.map(x)}function T(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var B=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId:e.string().optional(),"billingAddress.city":e.string().optional(),"billingAddress.country":e.string().optional(),"billingAddress.line1":e.string().optional(),"billingAddress.line2":e.string().optional(),"billingAddress.name":e.string().optional(),"billingAddress.postalCode":e.string().optional(),"billingAddress.state":e.string().optional(),netAmount:e.string().optional(),taxBreakdown0:e.string().optional(),taxBreakdown1:e.string().optional(),taxBreakdown2:e.string().optional(),taxBreakdown3:e.string().optional(),taxBreakdown4:e.string().optional(),taxBreakdown5:e.string().optional()}).and(e.record(e.string())),c=e.object({taxType:e.string(),taxPercentage:e.string(),taxAmount:e.number()});function A(t){let r=t.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(t.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let p=c.safeParse(u(String(s)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:r,taxBreakdown:a}}function R({payment_method:t,latest_charge:r,...n}){i(typeof t=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,p])=>{let d=c.safeParse(u(String(p)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,T as getUniqueVariants,B as isProductAvailable,A as mapCart,R as mapOrder,f as mapProduct,k as mapProducts,x as mapShippingRate,N as mapShippingRates,y as objectToStripeQuery,m as sanitizeQueryValue,w as sortProducts};
1
+ import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var d=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=t=>Object.entries(t).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function w(t){return t.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=e.object({category:e.string().optional(),order:e.coerce.number().optional(),slug:e.string(),variant:e.string().optional(),stock:e.coerce.number().optional().transform(t=>t===void 0?1/0:t)});function f({default_price:t,marketing_features:r,...n}){return i(t,"Product must have a default price"),i(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function k(t){return t.data.map(f)}function x(t){return t}function N(t){return t.data.map(x)}function T(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var B=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId:e.string().optional(),couponCode:e.string().optional(),taxedAmount:e.string().optional(),"billingAddress.city":e.string().optional(),"billingAddress.country":e.string().optional(),"billingAddress.line1":e.string().optional(),"billingAddress.line2":e.string().optional(),"billingAddress.name":e.string().optional(),"billingAddress.postalCode":e.string().optional(),"billingAddress.state":e.string().optional(),netAmount:e.string().optional(),taxBreakdown0:e.string().optional(),taxBreakdown1:e.string().optional(),taxBreakdown2:e.string().optional(),taxBreakdown3:e.string().optional(),taxBreakdown4:e.string().optional(),taxBreakdown5:e.string().optional()}).and(e.record(e.string())),c=e.object({taxType:e.string(),taxPercentage:e.string(),taxAmount:e.number()});function A(t){let r=t.payment_method;i(typeof r!="string","Payment method should not be a string");let n=t.customer;i(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=l.parse(t.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:r,taxBreakdown:o}}function R({payment_method:t,latest_charge:r,...n}){i(typeof t=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,T as getUniqueVariants,B as isProductAvailable,A as mapCart,R as mapOrder,f as mapProduct,k as mapProducts,x as mapShippingRate,N as mapShippingRates,y as objectToStripeQuery,m as sanitizeQueryValue,w as sortProducts};
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.29",
4
+ "version": "0.0.31",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [
@@ -48,20 +48,20 @@
48
48
  ],
49
49
  "sideEffects": false,
50
50
  "devDependencies": {
51
- "@neondatabase/serverless": "^0.9.5",
52
- "@types/node": "^22.7.4",
51
+ "@neondatabase/serverless": "^0.10.1",
52
+ "@types/node": "^22.7.5",
53
53
  "@types/react": "npm:types-react@19.0.0-rc.1",
54
54
  "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
55
- "next": "15.0.0-canary.175",
55
+ "next": "15.0.0-canary.179",
56
56
  "prettier": "3.3.3",
57
57
  "react": "19.0.0-rc-d8c90fa4-20241001",
58
58
  "react-dom": "19.0.0-rc-d8c90fa4-20241001",
59
59
  "rimraf": "6.0.1",
60
60
  "server-only": "0.0.1",
61
- "stripe": "^17.0.0",
61
+ "stripe": "^17.1.0",
62
62
  "tsup": "8.3.0",
63
63
  "tsx": "^4.19.1",
64
- "vitest": "^2.1.1",
64
+ "vitest": "^2.1.2",
65
65
  "zod": "^3.23.8"
66
66
  },
67
67
  "peerDependencies": {
@@ -69,7 +69,7 @@
69
69
  "@types/node": "^20.14.8 || ^22.7.4",
70
70
  "@types/react": "npm:types-react@19.0.0-rc.1",
71
71
  "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
72
- "next": "15.0.0-canary.175",
72
+ "next": "15.0.0-canary.179",
73
73
  "react": "19.0.0-rc-d8c90fa4-20241001",
74
74
  "react-dom": "19.0.0-rc-d8c90fa4-20241001",
75
75
  "server-only": "0.0.1",