commerce-kit 0.0.12 → 0.0.14

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/README.md CHANGED
@@ -61,6 +61,15 @@ export async function ProductList() {
61
61
  }
62
62
  ```
63
63
 
64
+ ## Debugging
65
+
66
+ This library uses a custom logger to output debug information. To control the debug output, use the `LOG_LEVEL` environment variable. The following levels are supported:
67
+
68
+ - **ERROR** – Critical issue for a specific request that needs immediate attention.
69
+ - **WARN** – Something that should be reviewed eventually.
70
+ - **LOG** – Details on regular operations.
71
+ - **DEBUG** – Debug information, including `time` and `timeEnd` function outputs.
72
+
64
73
  ## License
65
74
 
66
75
  This project is licensed under the AGPL Version 3 license – see the LICENSE.md file for details.
package/dist/index.d.ts CHANGED
@@ -1,36 +1,19 @@
1
- import { CartMetadata, mapCart } from './internal.js';
2
- export { MappedProduct } from './internal.js';
1
+ import { CartMetadata, MappedCart } from './internal.js';
2
+ export { MappedProduct, MappedShippingRate } from './internal.js';
3
3
  import Stripe from 'stripe';
4
4
  import { z, TypeOf } from 'zod';
5
5
 
6
- type Entity = "Product" | "Category" | "Order";
7
- type Provider = ({ tags, revalidate, cache, tagPrefix, }: {
8
- tags?: NextFetchRequestConfig["tags"];
9
- revalidate?: NextFetchRequestConfig["revalidate"];
10
- cache?: RequestInit["cache"];
11
- tagPrefix: string | undefined;
12
- }) => Stripe;
13
- type Filter<T extends Entity> = {
14
- Product: {
15
- category?: string;
16
- };
17
- Category: {};
18
- Order: {};
19
- }[T];
20
- type BrowseParams<T extends Entity> = {
21
- first?: number;
22
- last?: number;
23
- offset?: number;
24
- filter?: Filter<T>;
25
- };
26
- type SearchParams<_T extends Entity> = {
27
- query: string;
28
- };
29
6
  type Cart = NonNullable<Awaited<ReturnType<typeof cartGet>>>;
30
7
  declare function cartAdd({ productId, cartId }: {
31
8
  productId: string;
32
9
  cartId?: string;
33
10
  }): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
11
+ declare function cartUpdateQuantity({ productId, cartId, operation, clearTaxCalculation, }: {
12
+ productId: string;
13
+ cartId: string;
14
+ operation: "INCREASE" | "DECREASE";
15
+ clearTaxCalculation?: boolean;
16
+ }): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
34
17
  declare function cartGet(cartId: string): Promise<{
35
18
  cart: {
36
19
  metadata: {
@@ -128,9 +111,12 @@ declare function cartGet(cartId: string): Promise<{
128
111
  };
129
112
  quantity: number;
130
113
  }[];
131
- shippingRate: Stripe.Response<Stripe.ShippingRate> | null;
114
+ shippingRate: Stripe.ShippingRate | null;
132
115
  } | null | undefined>;
133
- declare function cartCreate(): Promise<Stripe.Response<Stripe.PaymentIntent>>;
116
+ declare function cartCreate({ productId }?: {
117
+ productId?: string;
118
+ cartId?: string;
119
+ }): Promise<Stripe.Response<Stripe.PaymentIntent>>;
134
120
  declare function cartAddOptimistic({ cart, add }: {
135
121
  cart: Cart;
136
122
  add: string | undefined;
@@ -231,7 +217,7 @@ declare function cartAddOptimistic({ cart, add }: {
231
217
  };
232
218
  quantity: number;
233
219
  }[];
234
- shippingRate: Stripe.Response<Stripe.ShippingRate> | null;
220
+ shippingRate: Stripe.ShippingRate | null;
235
221
  }>;
236
222
  declare function cartSetQuantity({ cartId, productId, quantity, }: {
237
223
  cartId: string;
@@ -294,38 +280,14 @@ declare function productGet({ slug }: {
294
280
  updated: number;
295
281
  url: string | null;
296
282
  }[]>;
297
- declare function productBrowse(params: BrowseParams<"Product">): Promise<{
298
- default_price: Stripe.Price;
299
- marketing_features: string[];
300
- metadata: {
301
- slug: string;
302
- category?: string | undefined;
303
- order?: number | undefined;
304
- variant?: string | undefined;
283
+ declare function productBrowse(params: {
284
+ first?: number;
285
+ last?: number;
286
+ offset?: number;
287
+ filter?: {
288
+ category?: string;
305
289
  };
306
- id: string;
307
- object: "product";
308
- active: boolean;
309
- created: number;
310
- deleted?: void | undefined;
311
- description: string | null;
312
- images: Array<string>;
313
- livemode: boolean;
314
- name: string;
315
- package_dimensions: Stripe.Product.PackageDimensions | null;
316
- shippable: boolean | null;
317
- statement_descriptor?: string | null;
318
- tax_code: string | Stripe.TaxCode | null;
319
- type: Stripe.Product.Type;
320
- unit_label?: string | null;
321
- updated: number;
322
- url: string | null;
323
- }[]>;
324
- type ShippingRate = Awaited<ReturnType<typeof shippingBrowse>>["data"][0];
325
- declare function shippingBrowse(): Promise<Stripe.Response<Stripe.ApiList<Stripe.ShippingRate>>>;
326
- declare function shippingGet(id: string): Promise<Stripe.Response<Stripe.ShippingRate> | null>;
327
- declare function categoryBrowse(params: BrowseParams<"Category">): Promise<string[]>;
328
- declare function productSearch(params: SearchParams<"Product">): Promise<{
290
+ }): Promise<{
329
291
  default_price: Stripe.Price;
330
292
  marketing_features: string[];
331
293
  metadata: {
@@ -352,6 +314,9 @@ declare function productSearch(params: SearchParams<"Product">): Promise<{
352
314
  updated: number;
353
315
  url: string | null;
354
316
  }[]>;
317
+ declare function shippingBrowse(): Promise<Stripe.ShippingRate[]>;
318
+ declare function shippingGet(id: string): Promise<Stripe.ShippingRate | null>;
319
+ declare function categoryBrowse(): Promise<string[]>;
355
320
  declare function fileGet(id: string): Promise<Stripe.Response<Stripe.FileLink> | null>;
356
321
  declare function accountGet(): Promise<{
357
322
  account: (Stripe.Account & {
@@ -479,10 +444,9 @@ declare function orderGet(orderId: string): Promise<{
479
444
  };
480
445
  quantity: number;
481
446
  }[];
482
- shippingRate: Stripe.Response<Stripe.ShippingRate> | null;
447
+ shippingRate: Stripe.ShippingRate | null;
483
448
  } | null>;
484
449
  declare const getProductsFromCart: (metadata: CartMetadata) => (readonly [productId: string, quantity: number])[];
485
- type MappedCart = ReturnType<typeof mapCart>;
486
450
  declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Promise<{
487
451
  product: {
488
452
  default_price: Stripe.Price;
@@ -514,7 +478,7 @@ declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Prom
514
478
  quantity: number;
515
479
  }[]>;
516
480
  type ProductsFromMetadata = Awaited<ReturnType<typeof getProductsFromMetadata>>;
517
- declare const getCartWithProductsById: (provider: Provider, cartId: string) => Promise<{
481
+ declare const getCartWithProductsById: (cartId: string) => Promise<{
518
482
  cart: {
519
483
  metadata: {
520
484
  shippingRateId?: string | undefined;
@@ -611,7 +575,7 @@ declare const getCartWithProductsById: (provider: Provider, cartId: string) => P
611
575
  };
612
576
  quantity: number;
613
577
  }[];
614
- shippingRate: Stripe.Response<Stripe.ShippingRate> | null;
578
+ shippingRate: Stripe.ShippingRate | null;
615
579
  } | null>;
616
580
  declare const calculateCartTotalNet: (cart: {
617
581
  cart: {
@@ -735,16 +699,12 @@ declare function cartSaveBillingAddress({ cartId, billingAddress, }: {
735
699
  declare function taxDefaultGet(): Promise<Stripe.Response<Stripe.Tax.Settings>>;
736
700
  declare function cartCount(metadata: CartMetadata): number;
737
701
 
738
- declare const StripeClient: ({ tags, revalidate, cache, }: {
739
- tags?: NextFetchRequestConfig["tags"];
740
- revalidate?: NextFetchRequestConfig["revalidate"];
741
- cache?: RequestInit["cache"];
742
- }) => Stripe;
743
- declare const provider: ({ tags, revalidate, cache, tagPrefix, }: {
702
+ declare const provider: ({ tags, revalidate, cache, tagPrefix, secretKey, }: {
744
703
  tags?: NextFetchRequestConfig["tags"];
745
704
  revalidate?: NextFetchRequestConfig["revalidate"];
746
705
  cache?: RequestInit["cache"];
747
706
  tagPrefix: string | undefined;
707
+ secretKey: string | undefined;
748
708
  }) => Stripe;
749
709
 
750
- export { type AddressSchema, type Cart, type MappedCart, type ProductsFromMetadata, type ShippingRate, StripeClient, accountGet, calculateCartTotalNet, calculateCartTotalNetWithoutShipping, calculateCartTotalPossiblyWithTax, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveShipping, cartSaveTax, cartSetQuantity, categoryBrowse, fileGet, getAddressSchema, getCartWithProductsById, getProductsFromCart, orderGet, productBrowse, productGet, productGetById, productSearch, provider, shippingBrowse, shippingGet, taxDefaultGet };
710
+ export { type AddressSchema, type Cart, MappedCart, type ProductsFromMetadata, accountGet, calculateCartTotalNet, calculateCartTotalNetWithoutShipping, calculateCartTotalPossiblyWithTax, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveShipping, cartSaveTax, cartSetQuantity, cartUpdateQuantity, categoryBrowse, fileGet, getAddressSchema, getCartWithProductsById, getProductsFromCart, orderGet, productBrowse, productGet, productGetById, provider, shippingBrowse, shippingGet, taxDefaultGet };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"server-only";import"server-only";import{z as s}from"zod";function _(t,e){if(!t)throw new Error(e)}var W=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},R=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},L=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var O=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),j=t=>Object.entries(t).map(([e,a])=>`${e}:"${O(a)}"`).join(" AND ").trim();function A(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),r=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(r)||n===r?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(r)?-1:n-r})}var at=s.object({category:s.string().optional(),order:s.coerce.number().optional(),slug:s.string(),variant:s.string().optional()});function N({default_price:t,marketing_features:e,...a}){return _(t,"Product must have a default price"),_(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:at.parse(a.metadata)}}function v(t){return t.data.map(N)}function Q(t){return t.filter((e,a,n)=>a===n.findIndex(r=>r.metadata.slug===e.metadata.slug))}var B=t=>!t.deleted&&t.active,$=s.object({shippingRateId:s.string().optional(),taxCalculationId:s.string().optional(),taxCalculationExp:s.string().optional(),taxId:s.string().optional(),"billingAddress.city":s.string().optional(),"billingAddress.country":s.string().optional(),"billingAddress.line1":s.string().optional(),"billingAddress.line2":s.string().optional(),"billingAddress.name":s.string().optional(),"billingAddress.postalCode":s.string().optional(),"billingAddress.state":s.string().optional(),netAmount:s.string().optional(),taxBreakdown0:s.string().optional(),taxBreakdown1:s.string().optional(),taxBreakdown2:s.string().optional(),taxBreakdown3:s.string().optional(),taxBreakdown4:s.string().optional(),taxBreakdown5:s.string().optional()}).and(s.record(s.string())),Y=s.object({taxType:s.string(),taxPercentage:s.string(),taxAmount:s.number()});function G(t){let e=t.payment_method;_(typeof e!="string","Payment method is missing from cart");let a=$.parse(t.metadata),n=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let o=Y.safeParse(L(String(i)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function V({payment_method:t,latest_charge:e,...a}){_(typeof t=="object","Payment method is missing from order"),_(typeof e=="object","Latest charge is missing from order");let n=$.parse(a.metadata),r=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,o])=>{let c=Y.safeParse(L(String(o)));return c.success?c.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:r,metadata:n}}import"server-only";import{revalidatePath as J,revalidateTag as S}from"next/cache";import C from"stripe";import{z as w}from"zod";import"server-only";var f=async()=>{let t={stripeAccount:void 0,storeId:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import K from"stripe";import"server-only";var z=process.env.STRIPE_SECRET_KEY;if(!z)throw new Error("Missing STRIPE_SECRET_KEY");var D=process.env.STRIPE_CURRENCY;if(!D)throw new Error("Missing STRIPE_CURRENCY");var g={StripeSecretKey:z,StripeCurrency:D};var nt=({tags:t,revalidate:e,cache:a})=>new K(g.StripeSecretKey,{typescript:!0,apiVersion:"2024-06-20",httpClient:K.createFetchHttpClient((r,i)=>fetch(r,{...i,cache:a??i?.cache,next:{tags:t??i?.next?.tags,revalidate:e??i?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),it=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],d=({tags:t,revalidate:e,cache:a,tagPrefix:n})=>nt({tags:it(t,n),revalidate:e,cache:a});var q=1e3;function jt({productId:t,cartId:e}){return e?k.add(d,{productId:t,cartId:e}):k.create(d,{productId:t})}function I(t){return k.get(d,{cartId:t})}function Qt(){return k.create(d,{})}async function Gt({cart:t,add:e}){if(!e)return t;let a=await E(e);if(!a)return console.warn(`Product not found: ${e}`),t;let r=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),i=t?M(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:i},lines:r}}async function Ut({cartId:t,productId:e,quantity:a}){let[n,r]=await Promise.all([H(e),I(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!r)throw new Error(`Cart not found: ${t}`);if(g.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let i=r.cart.metadata??{};a<=0?i[e]="":i[e]=a.toString();let o=M(r)+(n.default_price.unit_amount??0);try{return await P({paymentIntentId:t,data:{metadata:i,amount:o||q}})}catch(c){console.error(c)}finally{S(`cart-${t}`),J("/cart"),J("/cart-overlay")}}async function H(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return N(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Wt({slug:t}){let{stripeAccount:e,storeId:a}=await f(),r=await d({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"}).products.search({query:j({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return A(v(r).filter(B))}async function ot(t){let{stripeAccount:e,storeId:a}=await f();if(t.filter?.category){let n=t.filter?.category,i=await d({tagPrefix:a,tags:["product",`category-${n}`],cache:"force-cache"}).products.search({limit:100,query:j({active:!0,'metadata["category"]':n}),expand:["data.default_price"]},{stripeAccount:e});return A(Q(v(i)).filter(B).slice(t.offset,t.first))}else{let r=await d({tagPrefix:a,tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return A(Q(v(r)).filter(B).slice(t.offset,t.first))}}async function Yt(){let{stripeAccount:t,storeId:e}=await f();return await d({tagPrefix:e,tags:["shipping"]}).shippingRates.list({active:!0},{stripeAccount:t})}async function T(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["shipping",`shipping-${t}`]});try{return await n.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Vt(t){let a=(await ot({first:100})).map(r=>r.metadata.category),n=new Set(a);return Array.from(n).filter(Boolean)}async function zt(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["products","search"]}),r=O(t.query),i=await n.products.search({limit:100,query:`name~"${r}" OR description~"${r}" OR metadata["slug"]:"${r}" OR metadata["category"]:"${r}"`,expand:["data.default_price"]},{stripeAccount:e});return A(v(i).filter(o=>o.active&&!o.deleted))}async function Dt(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["files",`file-${t}`]});try{return await n.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Kt(){let{stripeAccount:t,storeId:e}=await f(),a=d({tagPrefix:e,tags:["account"]});try{let[n,r]=await W(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(n){if(console.error(n),n instanceof C.errors.StripeError&&n.code==="resource_missing")return null;throw n}}async function st(t){let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["order",`order-${t}`]});try{let r=await n.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return V(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Jt(t){let e=await st(t);if(!e)return null;let a=tt(e.metadata),n=await Promise.all(a.map(async([o,c])=>({product:await E(o),quantity:c}))),{metadata:{shippingRateId:r}}=e,i=r&&await T(r);return{order:e,lines:n.map(({product:o,quantity:c})=>o?{product:o,quantity:c}:null).filter(Boolean),shippingRate:i||null}}var E=async t=>{let{stripeAccount:e,storeId:a}=await f(),n=d({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return N(r)}catch(r){if(r instanceof C.errors.StripeError&&r.code==="resource_missing")return null;throw r}},Z=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],tt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),ct=async(t,e)=>{let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status))return G(i)}catch(i){if(console.error(i),i instanceof C.errors.StripeError&&i.code==="resource_missing")return null;throw i}};async function U(t){let e=tt(t);return await Promise.all(e.map(async([n,r])=>({product:await E(n),quantity:r})))}var et=async(t,e)=>{let a=await ct(t,e);if(!a)return null;let n=await U(a.metadata),{metadata:{shippingRateId:r}}=a,i=r&&await T(r);return{cart:a,lines:n.map(({product:o,quantity:c})=>o?{product:o,quantity:c}:null).filter(Boolean),shippingRate:i||null}},ut=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0,dt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function pt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let r=Date.now(),i=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!i||r>=i)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,c=e.amount,u=dt.some(y=>!a[y]&&!t.cart.metadata[y]?!1:a[y]!==t.cart.metadata[y]),m=n.length!==t.lines.length||n.some(y=>{let l=t.lines.find(h=>h.product.id===y.product?.id);return y.product?.default_price.unit_amount!==l?.product.default_price.unit_amount||y.quantity!==l?.quantity});return c&&o!==c||u||m}var Xt=t=>w.object({name:w.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:w.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:w.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:w.string({required_error:t.line1Required}).min(1,t.line1Required),line2:w.string().optional().nullable().default(""),postalCode:w.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:w.string().optional().nullable().default(""),phone:w.string().optional().nullable().default(""),taxId:w.string().optional().nullable().default("")}),lt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:r})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:i,storeId:o}=await f(),c=d({tagPrefix:o,tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let u=n?await T(n):null,m=typeof u?.tax_code=="string"?u.tax_code:u?.tax_code?.id,p=await ft(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",y=p.defaults.tax_behavior==="inferred_by_currency"?x:p.defaults.tax_behavior??x;return p.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${x}.`),await c.tax.calculations.create({expand:["line_items"],line_items:t.map(h=>({...h,tax_behavior:h.tax_behavior??y})),currency:g.StripeCurrency,shipping_cost:u?.active&&u?.fixed_amount?{amount:u.fixed_amount.amount,tax_behavior:u.tax_behavior==="inclusive"?"inclusive":u.tax_behavior==="exclusive"?"exclusive":y,tax_code:m??p.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:r?[{type:"eu_vat",value:r}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:i})},X={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},P=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:r}=await f(),i=await et(d,t);_(i,`Cart not found: ${t}`);let o=$.parse({...i.cart.metadata,...e.metadata}),c=await U(o),m=!a&&pt({oldCart:i,data:e,mergedMetadata:o,lines:c})?await lt({cartId:t,taxId:o.taxId??null,shippingRateId:o.shippingRateId??null,billingAddress:{country:o["billingAddress.country"]??"",city:o["billingAddress.city"]??"",line1:o["billingAddress.line1"]??"",line2:o["billingAddress.line2"]??"",name:o["billingAddress.name"]??"",postalCode:o["billingAddress.postalCode"]??"",state:o["billingAddress.state"]??""},lineItems:c.map(({product:l,quantity:h})=>{if(l?.default_price.unit_amount)return{product:l.id,reference:[l.metadata.slug,l.metadata.variant].filter(Boolean).join("-"),quantity:h,amount:l.default_price.unit_amount*h,tax_behavior:l.default_price.tax_behavior==="exclusive"?"exclusive":l.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:l.tax_code?typeof l.tax_code=="string"?l.tax_code:l.tax_code.id:void 0}}).filter(Boolean)}):null,p=e.amount?e.amount.toString():null;if(m){let l=Object.fromEntries(m.tax_breakdown.map(b=>({taxType:b.tax_rate_details.tax_type,taxPercentage:b.tax_rate_details.percentage_decimal,taxAmount:b.amount})).map((b,rt)=>[`taxBreakdown${rt}`,JSON.stringify(b)]));return await d({tagPrefix:r,tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,amount:m.amount_total,metadata:{...o,...p&&{netAmount:p},...X,...l,taxCalculationId:m.id,taxCalculationExp:m?.expires_at}},{stripeAccount:n})}return await d({tagPrefix:r,tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,metadata:{...o,...p&&{netAmount:p},...a&&{...X,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n})},k={async create(t,{productId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,cache:"no-cache"});try{let i=e?await E(e):null;return await r.paymentIntents.create({currency:g.StripeCurrency,amount:i?.default_price.unit_amount||q,automatic_payment_methods:{enabled:!0},metadata:{...i&&{[i.id]:"1"}}},{stripeAccount:a})}catch(i){throw console.error(i),i}},async get(t,{cartId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status)){let o=G(i);if(!o)return null;let c=await U(o.metadata),{metadata:{shippingRateId:u}}=o,m=u&&await T(u);return{cart:o,lines:c.map(({product:p,quantity:x})=>p?{product:p,quantity:x}:null).filter(Boolean),shippingRate:m||null}}}catch(i){if(console.error(i),i instanceof C.errors.StripeError&&i.code==="resource_missing")return null;throw i}},async add(t,{cartId:e,productId:a}){return(async({productId:r,cartId:i,operation:o,clearTaxCalculation:c})=>{let[u,m]=await Promise.all([E(r),et(t,i)]);if(!u)throw new Error(`Product not found: ${r}`);if(!m)throw new Error(`Cart not found: ${i}`);if(g.StripeCurrency.toLowerCase()!==u.default_price.currency.toLowerCase())throw new Error(`Product currency ${u.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let p=m.cart.metadata??{},l=R(p[r])+(o==="INCREASE"?1:-1);l<=0?p[r]="":p[r]=l.toString();let h=ut(m)+(u.default_price.unit_amount??0);try{return await P({paymentIntentId:i,data:{metadata:p,amount:h||q},clearTaxCalculation:c})}catch(F){console.error(F)}finally{S(`cart-${i}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},M=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+mt(t):0,mt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function Ht({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[r,i]=await Promise.all([H(t),I(e)]);if(!r)throw new Error(`Product not found: ${t}`);if(!i)throw new Error(`Cart not found: ${e}`);if(g.StripeCurrency?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=i.cart.metadata??{},m=R(o[t])+(a==="INCREASE"?1:-1);m<=0?o[t]="":o[t]=m.toString();let p=M(i)+(r.default_price.unit_amount??0);try{return await P({paymentIntentId:e,data:{metadata:o,amount:p||q},clearTaxCalculation:n})}catch(x){console.error(x)}finally{S(`cart-${e}`)}}var Zt=async({cartId:t,taxId:e})=>{let a=await I(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await P({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){console.error(n)}finally{S(`cart-${t}`)}};async function te({cartId:t,shippingRateId:e}){let a=await I(t);if(!a)throw new Error(`Cart not found: ${t}`);let n=await T(e);if(!n)throw new Error(`Shipping rate not found: ${e}`);try{return await P({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:M({...a,shippingRate:n})}})}catch(r){console.error(r)}finally{S(`cart-${t}`)}}async function ee({cartId:t,billingAddress:e}){if(!await I(t))throw new Error(`Cart not found: ${t}`);try{return await P({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??""}}})}catch(n){console.error(n)}finally{S(`cart-${t}`)}}async function ft(){let{stripeAccount:t,storeId:e}=await f();return await d({tagPrefix:e,tags:["tax-settings"]}).tax.settings.retrieve({},{stripeAccount:t})}function re(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{nt as StripeClient,Kt as accountGet,ut as calculateCartTotalNet,mt as calculateCartTotalNetWithoutShipping,M as calculateCartTotalPossiblyWithTax,jt as cartAdd,Gt as cartAddOptimistic,Ht as cartChangeQuantity,re as cartCount,Qt as cartCreate,I as cartGet,ee as cartSaveBillingAddress,te as cartSaveShipping,Zt as cartSaveTax,Ut as cartSetQuantity,Vt as categoryBrowse,Dt as fileGet,Xt as getAddressSchema,et as getCartWithProductsById,tt as getProductsFromCart,Jt as orderGet,ot as productBrowse,Wt as productGet,H as productGetById,zt as productSearch,d as provider,Yt as shippingBrowse,T as shippingGet,ft as taxDefaultGet};
1
+ import"server-only";import"server-only";import{z as c}from"zod";function 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]}},B=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},K=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,a])=>`${e}:"${ct(a)}"`).join(" AND ").trim();function k(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),i=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(i)||n===i?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(i)?-1:n-i})}var ut=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional()});function M({default_price:t,marketing_features:e,...a}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:ut.parse(a.metadata)}}function G(t){return t.data.map(M)}function Y(t){return t}function z(t){return t.data.map(Y)}function U(t){return t.filter((e,a,n)=>a===n.findIndex(i=>i.metadata.slug===e.metadata.slug))}var q=t=>!t.deleted&&t.active,W=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 Q(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let a=W.parse(t.metadata),n=Object.entries(a).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,r])=>{let o=J.safeParse(K(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function X({payment_method:t,latest_charge:e,...a}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let n=W.parse(a.metadata),i=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let s=J.safeParse(K(String(o)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:n}}import"server-only";import{revalidatePath as tt,revalidateTag as A}from"next/cache";import b from"stripe";import{z as _}from"zod";import"server-only";var f=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import Z from"stripe";import"server-only";var pt=process.env.STRIPE_SECRET_KEY,H=process.env.STRIPE_CURRENCY;if(!H)throw new Error("Missing STRIPE_CURRENCY");var x={StripeSecretKey:pt,StripeCurrency:H};var P={DEBUG:0,LOG:1,WARN:2,ERROR:3},dt="LOG",lt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in P?process.env.LOG_LEVEL:dt,E=P[lt],u={time(t){E>P.DEBUG||console.time(t)},timeEnd(t){E>P.DEBUG||console.timeEnd(t)},log(...t){E>P.LOG||console.log(...t)},dir(t,e){E>P.LOG||console.dir(t,e)},warn(...t){E>P.WARN||console.warn(...t)},error(...t){E>P.ERROR||console.error(...t)}};var mt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],l=({tags:t,revalidate:e,cache:a,tagPrefix:n,secretKey:i})=>{let r=i??x.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");u.log(`Using Stripe secret key from ${i?"parameter":"env"}.`);let o=mt(t,n);return new Z(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:Z.createFetchHttpClient((y,p)=>fetch(y,{...p,cache:a??p?.cache,next:{tags:o??p?.next?.tags,revalidate:e??p?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};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:()=>{}}};var O=1e3;function re({productId:t,cartId:e}){return e?ft({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):gt({productId:t})}async function ft({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[i,r]=await Promise.all([$(t),it(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(x.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let o=r.cart.metadata??{},p=B(o[t])+(a==="INCREASE"?1:-1);p<=0?o[t]="":o[t]=p.toString();let g=wt(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:g||O},clearTaxCalculation:n})}catch(d){u.error(d)}finally{A(`cart-${e}`)}}async function L(t){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(at.includes(r.status)){let o=Q(r);if(!o)return null;let s=await D(o.metadata),{metadata:{shippingRateId:y}}=o,p=y&&await N(y);return{cart:o,lines:s.map(({product:g,quantity:d})=>g?{product:g,quantity:d}:null).filter(Boolean),shippingRate:p||null}}}catch(r){if(u.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function gt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,cache:"no-cache"});try{let r=t?await $(t):null;return await i.paymentIntents.create({currency:x.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 ae({cart:t,add:e}){if(!e)return t;let a=await $(e);if(!a)return u.warn(`Product not found: ${e}`),t;let i=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),r=t?F(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:i}}async function ne({cartId:t,productId:e,quantity:a}){let[n,i]=await Promise.all([rt(e),L(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!i)throw new Error(`Cart not found: ${t}`);if(x.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let r=i.cart.metadata??{};a<=0?r[e]="":r[e]=a.toString();let o=F(i)+(n.default_price.unit_amount??0);try{return await I({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{A(`cart-${t}`),tt("/cart"),tt("/cart-overlay")}}async function rt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,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 b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),r=await l({secretKey:n,tagPrefix:a,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 k(G(r).filter(q))}async function yt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await f();if(t.filter?.category){let i=t.filter?.category,o=await l({secretKey:n,tagPrefix:a,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 k(U(G(o)).filter(q).slice(t.offset,t.first))}else{let r=await l({secretKey:n,tagPrefix:a,tags:w.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return k(U(G(r)).filter(q).slice(t.offset,t.first))}}async function oe(){let{stripeAccount:t,storeId:e,secretKey:a}=await f(),i=await l({secretKey:a,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return z(i)}async function N(t){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,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 b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se(){let e=(await yt({first:100})).map(n=>n.metadata.category).filter(Boolean),a=new Set(e);return Array.from(a)}async function ce(t){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,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 b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ue(){let{stripeAccount:t,storeId:e,secretKey:a}=await f(),n=l({secretKey:a,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await V(n.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 b.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function ht(t){let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,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 b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function pe(t){let e=await ht(t);if(!e)return null;let a=nt(e.metadata),n=await Promise.all(a.map(async([o,s])=>({product:await $(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await N(i);return{order:e,lines:n.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:r||null}}var $=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,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 b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},at=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],nt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,B(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),xt=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await f(),i=l({secretKey:n,tagPrefix:a,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(at.includes(r.status))return Q(r)}catch(r){if(u.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function D(t){let e=nt(t);return await Promise.all(e.map(async([n,i])=>({product:await $(n),quantity:i})))}var it=async t=>{let e=await xt(t);if(!e)return null;let a=await D(e.metadata),{metadata:{shippingRateId:n}}=e,i=n&&await N(n);return{cart:e,lines:a.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||null}},wt=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0,Ct=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function _t({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),r=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,y=Ct.some(h=>!a[h]&&!t.cart.metadata[h]?!1:a[h]!==t.cart.metadata[h]),p=n.length!==t.lines.length||n.some(h=>{let R=t.lines.find(m=>m.product.id===h.product?.id);return h.product?.default_price.unit_amount!==R?.product.default_price.unit_amount||h.quantity!==R?.quantity});return s&&o!==s||y||p}var de=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("")}),St=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:r,storeId:o,secretKey:s}=await f(),y=l({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let p=n?await N(n):null,g=typeof p?.tax_code=="string"?p.tax_code:p?.tax_code?.id,d=await bt(),h=x.StripeCurrency==="usd"||x.StripeCurrency==="cad"?"exclusive":"inclusive",R=d.defaults.tax_behavior==="inferred_by_currency"?h:d.defaults.tax_behavior??h;d.defaults.tax_behavior||u.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${x.StripeCurrency}: ${h}.`),u.time("createTaxCalculation ${cartId}");let m=await y.tax.calculations.create({expand:["line_items"],line_items:t.map(v=>({...v,tax_behavior:v.tax_behavior??R})),currency:x.StripeCurrency,shipping_cost:p?.active&&p?.fixed_amount?{amount:p.fixed_amount.amount,tax_behavior:p.tax_behavior==="inclusive"?"inclusive":p.tax_behavior==="exclusive"?"exclusive":R,tax_code:g??d.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}"),m},et={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},I=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:i,secretKey:r}=await f(),o=await it(t);S(o,`Cart not found: ${t}`);let s=W.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let y=await D(s);u.timeEnd("getProductsFromMetadata");let g=!a&&_t({oldCart:o,data:e,mergedMetadata:s,lines:y})?await St({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:m,quantity:v})=>{if(m?.default_price.unit_amount)return{product:m.id,reference:[m.metadata.slug,m.metadata.variant].filter(Boolean).join("-"),quantity:v,amount:m.default_price.unit_amount*v,tax_behavior:m.default_price.tax_behavior==="exclusive"?"exclusive":m.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:m.tax_code?typeof m.tax_code=="string"?m.tax_code:m.tax_code.id:void 0}}).filter(Boolean)}):null,d=e.amount?e.amount.toString():null;if(g){let m=Object.fromEntries(g.tax_breakdown.map(T=>({taxType:T.tax_rate_details.tax_type,taxPercentage:T.tax_rate_details.percentage_decimal,taxAmount:T.amount})).map((T,st)=>[`taxBreakdown${st}`,JSON.stringify(T)])),v=l({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let ot=await v.paymentIntents.update(t,{...e,amount:g.amount_total,metadata:{...s,...d&&{netAmount:d},...et,...m,taxCalculationId:g.id,taxCalculationExp:g?.expires_at}},{stripeAccount:n});return u.timeEnd(`paymentIntents.update ${t}`),ot}let h=l({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let R=await h.paymentIntents.update(t,{...e,metadata:{...s,...d&&{netAmount:d},...a&&{...et,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n});return u.timeEnd(`paymentIntents.update ${t}`),R},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Pt(t):0,Pt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function le({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[i,r]=await Promise.all([rt(t),L(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(x.StripeCurrency?.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let o=r.cart.metadata??{},p=B(o[t])+(a==="INCREASE"?1:-1);p<=0?o[t]="":o[t]=p.toString();let g=F(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:g||O},clearTaxCalculation:n})}catch(d){u.error(d)}finally{A(`cart-${e}`)}}var me=async({cartId:t,taxId:e})=>{let a=await L(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){u.error(n)}finally{A(`cart-${t}`)}};async function fe({cartId:t,shippingRateId:e}){let a=await L(t);if(!a)throw new Error(`Cart not found: ${t}`);u.time(`cartSaveShipping ${t}`);let n=await N(e);if(u.timeEnd(`cartSaveShipping ${t}`),!n)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await I({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:F({...a,shippingRate:n})}});return u.timeEnd(`updatePaymentIntent ${t}`),i}catch(i){u.error(i)}finally{A(`cart-${t}`)}}async function ge({cartId:t,billingAddress:e}){if(!await L(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??""}}})}catch(n){u.error(n)}finally{A(`cart-${t}`)}}async function bt(){let{stripeAccount:t,storeId:e,secretKey:a}=await f();return await l({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ye(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,B(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{ue as accountGet,wt as calculateCartTotalNet,Pt as calculateCartTotalNetWithoutShipping,F as calculateCartTotalPossiblyWithTax,re as cartAdd,ae as cartAddOptimistic,le as cartChangeQuantity,ye as cartCount,gt as cartCreate,L as cartGet,ge as cartSaveBillingAddress,fe as cartSaveShipping,me as cartSaveTax,ne as cartSetQuantity,ft as cartUpdateQuantity,se as categoryBrowse,ce as fileGet,de as getAddressSchema,it as getCartWithProductsById,nt as getProductsFromCart,pe as orderGet,yt as productBrowse,ie as productGet,rt as productGetById,l as provider,oe as shippingBrowse,N as shippingGet,bt as taxDefaultGet};
@@ -112,6 +112,15 @@ declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<St
112
112
  updated: number;
113
113
  url: string | null;
114
114
  }[];
115
+ /**
116
+ * @internal
117
+ */
118
+ declare function mapShippingRate(shippingRate: Stripe.ShippingRate): Stripe.ShippingRate;
119
+ type MappedShippingRate = ReturnType<typeof mapShippingRate>;
120
+ /**
121
+ * @internal
122
+ */
123
+ declare function mapShippingRates(shippingRates: Stripe.ApiList<Stripe.ShippingRate>): Stripe.ShippingRate[];
115
124
  /**
116
125
  * @internal
117
126
  */
@@ -293,6 +302,7 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
293
302
  transfer_data: Stripe.PaymentIntent.TransferData | null;
294
303
  transfer_group: string | null;
295
304
  };
305
+ type MappedCart = ReturnType<typeof mapCart>;
296
306
  /**
297
307
  * @internal
298
308
  */
@@ -363,4 +373,4 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
363
373
  transfer_group: string | null;
364
374
  };
365
375
 
366
- export { type CartMetadata, type MappedProduct, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, objectToStripeQuery, sanitizeQueryValue, sortProducts };
376
+ export { type CartMetadata, type MappedCart, type MappedProduct, type MappedShippingRate, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, mapShippingRate, mapShippingRates, objectToStripeQuery, sanitizeQueryValue, sortProducts };
package/dist/internal.js CHANGED
@@ -1 +1 @@
1
- import"server-only";import{z as t}from"zod";function i(e,r){if(!e)throw new Error(r)}var p=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}};var m=e=>e.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=e=>Object.entries(e).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function k(e){return e.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=t.object({category:t.string().optional(),order:t.coerce.number().optional(),slug:t.string(),variant:t.string().optional()});function f({default_price:e,marketing_features:r,...n}){return i(e,"Product must have a default price"),i(typeof e=="object","Product default price must be an object"),{...n,default_price:e,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function N(e){return e.data.map(f)}function T(e){return e.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var B=e=>!e.deleted&&e.active,l=t.object({shippingRateId:t.string().optional(),taxCalculationId:t.string().optional(),taxCalculationExp:t.string().optional(),taxId:t.string().optional(),"billingAddress.city":t.string().optional(),"billingAddress.country":t.string().optional(),"billingAddress.line1":t.string().optional(),"billingAddress.line2":t.string().optional(),"billingAddress.name":t.string().optional(),"billingAddress.postalCode":t.string().optional(),"billingAddress.state":t.string().optional(),netAmount:t.string().optional(),taxBreakdown0:t.string().optional(),taxBreakdown1:t.string().optional(),taxBreakdown2:t.string().optional(),taxBreakdown3:t.string().optional(),taxBreakdown4:t.string().optional(),taxBreakdown5:t.string().optional()}).and(t.record(t.string())),c=t.object({taxType:t.string(),taxPercentage:t.string(),taxAmount:t.number()});function h(e){let r=e.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(e.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let u=c.safeParse(p(String(s)));return u.success?u.data:null}).filter(Boolean);return{...e,metadata:n,payment_method:r,taxBreakdown:a}}function A({payment_method:e,latest_charge:r,...n}){i(typeof e=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let d=c.safeParse(p(String(u)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:e,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,T as getUniqueVariants,B as isProductAvailable,h as mapCart,A as mapOrder,f as mapProduct,N as mapProducts,b as objectToStripeQuery,m as sanitizeQueryValue,k as sortProducts};
1
+ import"server-only";import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var u=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=t=>Object.entries(t).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function k(t){return t.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=e.object({category:e.string().optional(),order:e.coerce.number().optional(),slug:e.string(),variant:e.string().optional()});function f({default_price:t,marketing_features:r,...n}){return i(t,"Product must have a default price"),i(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function N(t){return t.data.map(f)}function x(t){return t}function T(t){return t.data.map(x)}function B(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var A=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId:e.string().optional(),"billingAddress.city":e.string().optional(),"billingAddress.country":e.string().optional(),"billingAddress.line1":e.string().optional(),"billingAddress.line2":e.string().optional(),"billingAddress.name":e.string().optional(),"billingAddress.postalCode":e.string().optional(),"billingAddress.state":e.string().optional(),netAmount:e.string().optional(),taxBreakdown0:e.string().optional(),taxBreakdown1:e.string().optional(),taxBreakdown2:e.string().optional(),taxBreakdown3:e.string().optional(),taxBreakdown4:e.string().optional(),taxBreakdown5:e.string().optional()}).and(e.record(e.string())),c=e.object({taxType:e.string(),taxPercentage:e.string(),taxAmount:e.number()});function R(t){let r=t.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(t.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let p=c.safeParse(u(String(s)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:r,taxBreakdown:a}}function M({payment_method:t,latest_charge:r,...n}){i(typeof t=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,p])=>{let d=c.safeParse(u(String(p)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,B as getUniqueVariants,A as isProductAvailable,R as mapCart,M as mapOrder,f as mapProduct,N as mapProducts,x as mapShippingRate,T as mapShippingRates,y as objectToStripeQuery,m as sanitizeQueryValue,k as sortProducts};
package/dist/yns.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  type YnsFindStripeAccountResult = {
2
2
  stripeAccount: string | undefined;
3
3
  storeId: string | undefined;
4
+ secretKey: string | undefined;
4
5
  };
5
6
  declare global {
6
7
  /**
@@ -9,6 +10,6 @@ declare global {
9
10
  */
10
11
  function __ynsFindStripeAccount(): YnsFindStripeAccountResult | undefined | Promise<YnsFindStripeAccountResult | undefined>;
11
12
  }
12
- declare const findStripeAccount: () => Promise<YnsFindStripeAccountResult>;
13
+ declare const getYnsContext: () => Promise<YnsFindStripeAccountResult>;
13
14
 
14
- export { findStripeAccount };
15
+ export { getYnsContext };
package/dist/yns.js CHANGED
@@ -1 +1 @@
1
- import"server-only";var i=async()=>{let n={stripeAccount:void 0,storeId:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??n:n};export{i as findStripeAccount};
1
+ import"server-only";var i=async()=>{let n={stripeAccount:void 0,storeId:void 0,secretKey:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??n:n};export{i 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.12",
4
+ "version": "0.0.14",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [