commerce-kit 0.0.25 → 0.0.27

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
@@ -1,6 +1,5 @@
1
1
  import { CartMetadata, MappedCart } from './internal.js';
2
2
  export { MappedProduct, MappedShippingRate } from './internal.js';
3
- import { Config } from './browser.js';
4
3
  import Stripe from 'stripe';
5
4
  import { z, TypeOf } from 'zod';
6
5
 
@@ -744,7 +743,6 @@ declare const contextGet: () => Promise<{
744
743
  storeId: string | undefined;
745
744
  secretKey: string | undefined;
746
745
  publishableKey: string | undefined;
747
- config: Config;
748
746
  }>;
749
747
 
750
748
  declare const provider: ({ tags, revalidate, cache, tagPrefix, secretKey, }: {
package/dist/index.js CHANGED
@@ -1,35 +1,10 @@
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
-
3
- ## Header 2
4
-
5
- ### Header 3
6
-
7
- #### Header 4
8
-
9
- ##### Header 5
10
-
11
- ###### Header 6
12
-
13
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
14
-
15
- > This is a quote
16
-
17
- * This is a list item
18
- * This is another list item
19
- * This is a third list item
20
-
21
- \`\`\`js
22
- function hello() {
23
- console.log('Hello world!');
24
- }
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 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`
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-06-20",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`
27
2
  select * from reviews
28
3
  where product_id = ${t.productId} and store_id = ${e}
29
4
  order by created_at desc
30
5
  limit ${t.first??100}
31
6
  offset ${t.offset??0}
32
- `}async function ye(t){if(!T)return null;let{storeId:e}=await l();return await T`
7
+ `}async function he(t){if(!T)return null;let{storeId:e}=await p();return await T`
33
8
  insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
34
9
  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,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};
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};
package/dist/yns.d.ts CHANGED
@@ -1,19 +1,14 @@
1
- import { Config } from './browser.js';
2
- import 'zod';
3
-
4
1
  type YnsFindStripeAccountResult = {
5
2
  stripeAccount: string | undefined;
6
3
  storeId: string | undefined;
7
4
  secretKey: string | undefined;
8
5
  publishableKey: string | undefined;
9
- config: Config | undefined;
10
6
  };
11
7
  type YnsContextResult = {
12
8
  stripeAccount: string | undefined;
13
9
  storeId: string | undefined;
14
10
  secretKey: string | undefined;
15
11
  publishableKey: string | undefined;
16
- config: Config;
17
12
  };
18
13
  declare global {
19
14
  /**
package/dist/yns.js CHANGED
@@ -1,26 +1 @@
1
- var i=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
-
3
- ## Header 2
4
-
5
- ### Header 3
6
-
7
- #### Header 4
8
-
9
- ##### Header 5
10
-
11
- ###### Header 6
12
-
13
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
14
-
15
- > This is a quote
16
-
17
- * This is a list item
18
- * This is another list item
19
- * This is a third list item
20
-
21
- \`\`\`js
22
- function hello() {
23
- console.log('Hello world!');
24
- }
25
- \`\`\`
26
- `}}},n={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0,config:t},e=await global?.__ynsFindStripeAccount?.();return e?{...e,config:e.config??t}:n};export{i as getYnsContext};
1
+ var t=async()=>{let e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??e};export{t as getYnsContext};
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.25",
4
+ "version": "0.0.27",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [
@@ -35,10 +35,6 @@
35
35
  "import": "./dist/yns.js",
36
36
  "types": "./dist/yns.d.ts"
37
37
  },
38
- "./browser": {
39
- "import": "./dist/browser.js",
40
- "types": "./dist/browser.d.ts"
41
- },
42
38
  "./db": {
43
39
  "import": "./dist/db.js",
44
40
  "types": "./dist/db.d.ts"
package/dist/browser.d.ts DELETED
@@ -1,263 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- declare const configSchema: z.ZodObject<{
4
- hero: z.ZodObject<{
5
- show: z.ZodBoolean;
6
- title: z.ZodString;
7
- description: z.ZodString;
8
- button: z.ZodObject<{
9
- label: z.ZodString;
10
- path: z.ZodString;
11
- }, "strip", z.ZodTypeAny, {
12
- path: string;
13
- label: string;
14
- }, {
15
- path: string;
16
- label: string;
17
- }>;
18
- image: z.ZodObject<{
19
- src: z.ZodString;
20
- alt: z.ZodString;
21
- }, "strip", z.ZodTypeAny, {
22
- src: string;
23
- alt: string;
24
- }, {
25
- src: string;
26
- alt: string;
27
- }>;
28
- }, "strip", z.ZodTypeAny, {
29
- show: boolean;
30
- title: string;
31
- description: string;
32
- button: {
33
- path: string;
34
- label: string;
35
- };
36
- image: {
37
- src: string;
38
- alt: string;
39
- };
40
- }, {
41
- show: boolean;
42
- title: string;
43
- description: string;
44
- button: {
45
- path: string;
46
- label: string;
47
- };
48
- image: {
49
- src: string;
50
- alt: string;
51
- };
52
- }>;
53
- categorySection: z.ZodObject<{
54
- show: z.ZodBoolean;
55
- }, "strip", z.ZodTypeAny, {
56
- show: boolean;
57
- }, {
58
- show: boolean;
59
- }>;
60
- nav: z.ZodObject<{
61
- title: z.ZodString;
62
- searchBar: z.ZodObject<{
63
- show: z.ZodBoolean;
64
- }, "strip", z.ZodTypeAny, {
65
- show: boolean;
66
- }, {
67
- show: boolean;
68
- }>;
69
- links: z.ZodArray<z.ZodObject<{
70
- label: z.ZodString;
71
- href: z.ZodString;
72
- }, "strip", z.ZodTypeAny, {
73
- label: string;
74
- href: string;
75
- }, {
76
- label: string;
77
- href: string;
78
- }>, "many">;
79
- }, "strip", z.ZodTypeAny, {
80
- title: string;
81
- searchBar: {
82
- show: boolean;
83
- };
84
- links: {
85
- label: string;
86
- href: string;
87
- }[];
88
- }, {
89
- title: string;
90
- searchBar: {
91
- show: boolean;
92
- };
93
- links: {
94
- label: string;
95
- href: string;
96
- }[];
97
- }>;
98
- footer: z.ZodObject<{
99
- name: z.ZodString;
100
- tagline: z.ZodString;
101
- newsletter: z.ZodObject<{
102
- show: z.ZodBoolean;
103
- }, "strip", z.ZodTypeAny, {
104
- show: boolean;
105
- }, {
106
- show: boolean;
107
- }>;
108
- credits: z.ZodBoolean;
109
- sections: z.ZodArray<z.ZodObject<{
110
- header: z.ZodString;
111
- links: z.ZodArray<z.ZodObject<{
112
- label: z.ZodString;
113
- href: z.ZodString;
114
- }, "strip", z.ZodTypeAny, {
115
- label: string;
116
- href: string;
117
- }, {
118
- label: string;
119
- href: string;
120
- }>, "many">;
121
- }, "strip", z.ZodTypeAny, {
122
- links: {
123
- label: string;
124
- href: string;
125
- }[];
126
- header: string;
127
- }, {
128
- links: {
129
- label: string;
130
- href: string;
131
- }[];
132
- header: string;
133
- }>, "many">;
134
- }, "strip", z.ZodTypeAny, {
135
- name: string;
136
- tagline: string;
137
- newsletter: {
138
- show: boolean;
139
- };
140
- credits: boolean;
141
- sections: {
142
- links: {
143
- label: string;
144
- href: string;
145
- }[];
146
- header: string;
147
- }[];
148
- }, {
149
- name: string;
150
- tagline: string;
151
- newsletter: {
152
- show: boolean;
153
- };
154
- credits: boolean;
155
- sections: {
156
- links: {
157
- label: string;
158
- href: string;
159
- }[];
160
- header: string;
161
- }[];
162
- }>;
163
- pages: z.ZodRecord<z.ZodString, z.ZodObject<{
164
- content: z.ZodString;
165
- }, "strip", z.ZodTypeAny, {
166
- content: string;
167
- }, {
168
- content: string;
169
- }>>;
170
- }, "strip", z.ZodTypeAny, {
171
- hero: {
172
- show: boolean;
173
- title: string;
174
- description: string;
175
- button: {
176
- path: string;
177
- label: string;
178
- };
179
- image: {
180
- src: string;
181
- alt: string;
182
- };
183
- };
184
- categorySection: {
185
- show: boolean;
186
- };
187
- nav: {
188
- title: string;
189
- searchBar: {
190
- show: boolean;
191
- };
192
- links: {
193
- label: string;
194
- href: string;
195
- }[];
196
- };
197
- footer: {
198
- name: string;
199
- tagline: string;
200
- newsletter: {
201
- show: boolean;
202
- };
203
- credits: boolean;
204
- sections: {
205
- links: {
206
- label: string;
207
- href: string;
208
- }[];
209
- header: string;
210
- }[];
211
- };
212
- pages: Record<string, {
213
- content: string;
214
- }>;
215
- }, {
216
- hero: {
217
- show: boolean;
218
- title: string;
219
- description: string;
220
- button: {
221
- path: string;
222
- label: string;
223
- };
224
- image: {
225
- src: string;
226
- alt: string;
227
- };
228
- };
229
- categorySection: {
230
- show: boolean;
231
- };
232
- nav: {
233
- title: string;
234
- searchBar: {
235
- show: boolean;
236
- };
237
- links: {
238
- label: string;
239
- href: string;
240
- }[];
241
- };
242
- footer: {
243
- name: string;
244
- tagline: string;
245
- newsletter: {
246
- show: boolean;
247
- };
248
- credits: boolean;
249
- sections: {
250
- links: {
251
- label: string;
252
- href: string;
253
- }[];
254
- header: string;
255
- }[];
256
- };
257
- pages: Record<string, {
258
- content: string;
259
- }>;
260
- }>;
261
- type Config = z.infer<typeof configSchema>;
262
-
263
- export { type Config, configSchema };
package/dist/browser.js DELETED
@@ -1 +0,0 @@
1
- import{z as t}from"zod";var o=t.object({hero:t.object({show:t.boolean(),title:t.string(),description:t.string(),button:t.object({label:t.string(),path:t.string()}),image:t.object({src:t.string(),alt:t.string()})}),categorySection:t.object({show:t.boolean()}),nav:t.object({title:t.string(),searchBar:t.object({show:t.boolean()}),links:t.array(t.object({label:t.string(),href:t.string()}))}),footer:t.object({name:t.string(),tagline:t.string(),newsletter:t.object({show:t.boolean()}),credits:t.boolean(),sections:t.array(t.object({header:t.string(),links:t.array(t.object({label:t.string(),href:t.string()}))}))}),pages:t.record(t.string(),t.object({content:t.string()}))});export{o as configSchema};