commerce-kit 0.0.24 → 0.0.25

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 +3 -3
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var V=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},N=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,'\\"'),j=t=>Object.entries(t).map(([e,n])=>`${e}:"${ct(n)}"`).join(" AND ").trim();function q(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 ut=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 M({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 G(t){return t.data.map(M)}function H(t){return t}function z(t){return t.data.map(H)}function D(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())),J=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Y(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=J.safeParse(U(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:e,taxBreakdown:a}}function X({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=J.safeParse(U(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import{revalidatePath as tt,revalidateTag as E}from"next/cache";import v from"stripe";import{z as _}from"zod";var l=async()=>{let t={hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]},pages:{"/about":{content:`# Header 1
1
+ import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var H=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},N=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,'\\"'),j=t=>Object.entries(t).map(([e,n])=>`${e}:"${ct(n)}"`).join(" AND ").trim();function q(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 ut=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 M({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 G(t){return t.data.map(M)}function z(t){return t}function J(t){return t.data.map(z)}function D(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())),X=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Y(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=X.safeParse(U(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=X.safeParse(U(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import{revalidatePath as et,revalidateTag as E}from"next/cache";import v from"stripe";import{z as _}from"zod";var l=async()=>{let t={hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]},pages:{"/about":{content:`# Header 1
2
2
 
3
3
  ## Header 2
4
4
 
@@ -23,7 +23,7 @@ function hello() {
23
23
  console.log('Hello world!');
24
24
  }
25
25
  \`\`\`
26
- `}}},e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0,config:t},n=await global?.__ynsFindStripeAccount?.();return n?{...n,config:n.config??t}:e};import Z from"stripe";var dt=process.env.STRIPE_SECRET_KEY,lt=process.env.STRIPE_CURRENCY,g={StripeSecretKey:dt,StripeCurrency:lt};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 Z(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:Z.createFetchHttpClient((y,d)=>fetch(y,{...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},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:mt,I=b[ft],u={time(t){I>b.DEBUG||console.time(t)},timeEnd(t){I>b.DEBUG||console.timeEnd(t)},log(...t){I>b.LOG||console.log(...t)},dir(t,e){I>b.LOG||console.dir(t,e)},warn(...t){I>b.WARN||console.warn(...t)},error(...t){I>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 gt}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=gt(process.env.DATABASE_URL));var O=1e3;function te({productId:t,cartId:e}){return e?ht({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function ht({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),it(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=N(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let h=_t(r)+(i.default_price.unit_amount??0);try{return await A({paymentIntentId:e,data:{metadata:o,amount:h||O},clearTaxCalculation:a})}catch(p){u.error(p)}finally{E(`cart-${e}`)}}async function B(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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(nt.includes(r.status)){let o=Y(r);if(!o)return null;let s=await Q(o.metadata),{metadata:{shippingRateId:y}}=o,d=y&&await L(y);return{cart:o,lines:s.map(({product:h,quantity:p})=>h?{product:h,quantity:p}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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([rt(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 A({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{E(`cart-${t}`),tt("/cart"),tt("/cart-overlay")}}async function rt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 M(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ne({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),r=await m({secretKey:a,tagPrefix:n,tags:w.productGetBySlug.tags({productSlug: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(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return q(G(r).filter(W))}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l();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:j({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return q(D(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 q(D(G(r)).filter(W).slice(t.offset,t.first))}}async function ae(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return z(i)}async function L(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie(){let e=(await xt({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 l(),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 v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),a=m({secretKey:n,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await V(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 v.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 X(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(t){let e=await wt(t);if(!e)return null;let n=at(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await L(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 l(),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 M(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}},nt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],at=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Ct=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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(nt.includes(r.status))return Y(r)}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function Q(t){let e=at(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var it=async t=>{let e=await Ct(t);if(!e)return null;let n=await Q(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await L(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||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"];function bt({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,y=St.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 R=t.lines.find(f=>f.product.id===x.product?.id);return x.product?.default_price.unit_amount!==R?.product.default_price.unit_amount||x.quantity!==R?.quantity});return s&&o!==s||y||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("")}),vt=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 l(),y=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await L(a):null,h=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,p=await Pt(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",R=p.defaults.tax_behavior==="inferred_by_currency"?x:p.defaults.tax_behavior??x;p.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 y.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??R})),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":R,tax_code:h??p.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:""},A=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await l(),o=await it(t);S(o,`Cart not found: ${t}`);let s=K.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let y=await Q(s);u.timeEnd("getProductsFromMetadata");let h=!n&&bt({oldCart:o,data:e,mergedMetadata:s,lines:y})?await vt({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:y.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,p=e.amount?e.amount.toString():null;if(h){let f=Object.fromEntries(h.tax_breakdown.map($=>({taxType:$.tax_rate_details.tax_type,taxPercentage:$.tax_rate_details.percentage_decimal,taxAmount:$.amount})).map(($,st)=>[`taxBreakdown${st}`,JSON.stringify($)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let ot=await P.paymentIntents.update(t,{...e,amount:h.amount_total,metadata:{...s,...p&&{netAmount:p},...et,...f,taxCalculationId:h.id,taxCalculationExp:h?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),ot}let x=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let R=await x.paymentIntents.update(t,{...e,metadata:{...s,...p&&{netAmount:p},...n&&{...et,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),R},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([rt(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=N(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let h=F(r)+(i.default_price.unit_amount??0);try{return await A({paymentIntentId:e,data:{metadata:o,amount:h||O},clearTaxCalculation:a})}catch(p){u.error(p)}finally{E(`cart-${e}`)}}var le=async({cartId:t,email:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await A({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}},pe=async({cartId:t,taxId:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await A({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 L(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await A({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 A({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 Pt(){let{stripeAccount:t,storeId:e,secretKey:n}=await l();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,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function he(t){if(!T)return null;let{storeId:e}=await l();return await T`
26
+ `}}},e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0,config:t},n=await global?.__ynsFindStripeAccount?.();return n?{...n,config:n.config??t}:e};import tt from"stripe";var dt=process.env.STRIPE_SECRET_KEY,lt=process.env.STRIPE_CURRENCY,g={StripeSecretKey:dt,StripeCurrency:lt};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-06-20",httpClient:tt.createFetchHttpClient((y,d)=>fetch(y,{...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},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:mt,I=b[ft],u={time(t){I>b.DEBUG||console.time(t)},timeEnd(t){I>b.DEBUG||console.timeEnd(t)},log(...t){I>b.LOG||console.log(...t)},dir(t,e){I>b.LOG||console.dir(t,e)},warn(...t){I>b.WARN||console.warn(...t)},error(...t){I>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 gt}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=gt(process.env.DATABASE_URL));var O=1e3;function te({productId:t,cartId:e}){return e?ht({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function ht({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),it(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=N(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let h=_t(r)+(i.default_price.unit_amount??0);try{return await A({paymentIntentId:e,data:{metadata:o,amount:h||O},clearTaxCalculation:a})}catch(p){u.error(p)}finally{E(`cart-${e}`)}}async function B(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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(nt.includes(r.status)){let o=Y(r);if(!o)return null;let s=await V(o.metadata),{metadata:{shippingRateId:y}}=o,d=y&&await L(y);return{cart:o,lines:s.map(({product:h,quantity:p})=>h?{product:h,quantity:p}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 A({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{E(`cart-${t}`),et("/cart"),et("/cart-overlay")}}async function Q(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 M(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ne({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),r=await m({secretKey:a,tagPrefix:n,tags:w.productGetBySlug.tags({productSlug: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(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))),q(G(r).filter(W))}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l();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:j({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return q(D(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 q(D(G(r)).filter(W).slice(t.offset,t.first))}}async function ae(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return J(i)}async function L(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie(){let e=(await xt({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 l(),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 v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),a=m({secretKey:n,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await H(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 v.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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 v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(t){let e=await wt(t);if(!e)return null;let n=at(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await L(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 l(),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 M(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}},nt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],at=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Ct=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),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(nt.includes(r.status))return Y(r)}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function V(t){let e=at(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var it=async t=>{let e=await Ct(t);if(!e)return null;let n=await V(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await L(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||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"];function bt({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,y=St.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 R=t.lines.find(f=>f.product.id===x.product?.id);return x.product?.default_price.unit_amount!==R?.product.default_price.unit_amount||x.quantity!==R?.quantity});return s&&o!==s||y||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("")}),vt=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 l(),y=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await L(a):null,h=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,p=await Pt(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",R=p.defaults.tax_behavior==="inferred_by_currency"?x:p.defaults.tax_behavior??x;p.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 y.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??R})),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":R,tax_code:h??p.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},rt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},A=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await l(),o=await it(t);S(o,`Cart not found: ${t}`);let s=K.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let y=await V(s);u.timeEnd("getProductsFromMetadata");let h=!n&&bt({oldCart:o,data:e,mergedMetadata:s,lines:y})?await vt({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:y.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,p=e.amount?e.amount.toString():null;if(h){let f=Object.fromEntries(h.tax_breakdown.map($=>({taxType:$.tax_rate_details.tax_type,taxPercentage:$.tax_rate_details.percentage_decimal,taxAmount:$.amount})).map(($,st)=>[`taxBreakdown${st}`,JSON.stringify($)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let ot=await P.paymentIntents.update(t,{...e,amount:h.amount_total,metadata:{...s,...p&&{netAmount:p},...rt,...f,taxCalculationId:h.id,taxCalculationExp:h?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),ot}let x=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let R=await x.paymentIntents.update(t,{...e,metadata:{...s,...p&&{netAmount:p},...n&&{...rt,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),R},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=N(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let h=F(r)+(i.default_price.unit_amount??0);try{return await A({paymentIntentId:e,data:{metadata:o,amount:h||O},clearTaxCalculation:a})}catch(p){u.error(p)}finally{E(`cart-${e}`)}}var le=async({cartId:t,email:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await A({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}},pe=async({cartId:t,taxId:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await A({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 L(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await A({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 A({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 Pt(){let{stripeAccount:t,storeId:e,secretKey:n}=await l();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,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function he(t){if(!T)return null;let{storeId:e}=await l();return await T`
27
27
  select * from reviews
28
28
  where product_id = ${t.productId} and store_id = ${e}
29
29
  order by created_at desc
@@ -32,4 +32,4 @@ function hello() {
32
32
  `}async function ye(t){if(!T)return null;let{storeId:e}=await l();return await T`
33
33
  insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
34
34
  values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
35
- `}var xe=l;export{se as accountGet,_t 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,le as cartSaveEmail,me as cartSaveShipping,pe as cartSaveTax,re as cartSetQuantity,ht as cartUpdateQuantity,ie as categoryBrowse,xe as contextGet,oe as fileGet,ue as getAddressSchema,it as getCartWithProductsById,at as getProductsFromCart,Q as getProductsFromMetadata,ce as orderGet,xt as productBrowse,ne as productGet,rt as productGetById,ye as productReviewAdd,he as productReviewBrowse,m as provider,ae as shippingBrowse,L as shippingGet,Pt as taxDefaultGet};
35
+ `}var xe=l;export{se as accountGet,_t 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,le as cartSaveEmail,me as cartSaveShipping,pe as cartSaveTax,re as cartSetQuantity,ht as cartUpdateQuantity,ie as categoryBrowse,xe as contextGet,oe as fileGet,ue as getAddressSchema,it as getCartWithProductsById,at as getProductsFromCart,V as getProductsFromMetadata,ce as orderGet,xt as productBrowse,ne as productGet,Q as productGetById,ye as productReviewAdd,he as productReviewBrowse,m as provider,ae as shippingBrowse,L as shippingGet,Pt 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.24",
4
+ "version": "0.0.25",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [
@@ -53,7 +53,7 @@
53
53
  "sideEffects": false,
54
54
  "devDependencies": {
55
55
  "@neondatabase/serverless": "^0.9.5",
56
- "@types/node": "^22.5.4",
56
+ "@types/node": "^22.5.5",
57
57
  "@types/react": "npm:types-react@19.0.0-rc.1",
58
58
  "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
59
59
  "next": "15.0.0-canary.146",
@@ -62,10 +62,10 @@
62
62
  "react-dom": "19.0.0-rc-fb9a90fa48-20240614",
63
63
  "rimraf": "6.0.1",
64
64
  "server-only": "0.0.1",
65
- "stripe": "^16.10.0",
65
+ "stripe": "^16.11.0",
66
66
  "tsup": "8.2.4",
67
- "tsx": "^4.19.0",
68
- "vitest": "^2.0.5",
67
+ "tsx": "^4.19.1",
68
+ "vitest": "^2.1.1",
69
69
  "zod": "^3.23.8"
70
70
  },
71
71
  "peerDependencies": {