commerce-kit 0.0.5 → 0.0.6

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
@@ -1 +1,66 @@
1
1
  # commerce-kit
2
+
3
+ `commerce-kit` is a simple TypeScript library designed specifically for e-commerce applications built with Next.js. It provides a range of utilities to interact with products, categories, and orders, seamlessly integrating with Stripe for payment processing.
4
+
5
+ Built by [Your Next Store](https://yournextstore.com).
6
+
7
+ ## Features
8
+
9
+ - **Product Browsing**: Easily fetch and display products.
10
+ - **Category Management**: Manage and retrieve product categories.
11
+ - **Order Handling**: Create and manage customer orders.
12
+ - **Cart Operations**: Add products to cart and retrieve cart details.
13
+ - **Stripe Integration**: Built-in support for payment processing using Stripe.
14
+
15
+ ## Installation
16
+
17
+ Install the package via npm:
18
+
19
+ ```bash
20
+ npm install commerce-kit
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ `commerce-kit` is intended for use with Next.js applications. Here's a simple example of how to use it to fetch and display products:
26
+
27
+ ```tsx
28
+ import * as Commerce from "commerce-kit";
29
+ import { formatMoney } from "commerce-kit/currencies";
30
+ import Image from "next/image";
31
+ import Link from "next/link";
32
+
33
+ export async function ProductList() {
34
+ const products = await Commerce.productBrowse({ first: 6 });
35
+
36
+ return (
37
+ <ul>
38
+ {products.map((product) => (
39
+ <li key={product.id}>
40
+ <Link href={`/product/${product.metadata.slug}`}>
41
+ <article>
42
+ {product.images[0] && (
43
+ <Image src={product.images[0]} width={300} height={300} alt={product.name} />
44
+ )}
45
+ <h2>{product.name}</h2>
46
+ {product.default_price.unit_amount && (
47
+ <p>
48
+ {formatMoney({
49
+ amount: product.default_price.unit_amount,
50
+ currency: product.default_price.currency,
51
+ locale: "en-US",
52
+ })}
53
+ </p>
54
+ )}
55
+ </article>
56
+ </Link>
57
+ </li>
58
+ ))}
59
+ </ul>
60
+ );
61
+ }
62
+ ```
63
+
64
+ ## License
65
+
66
+ This project is licensed under the MIT License – see the [LICENSE](LICENSE.md) file for details.
@@ -0,0 +1,11 @@
1
+ type Money = {
2
+ amount: number;
3
+ currency: string;
4
+ };
5
+ declare const getStripeAmountFromDecimal: ({ amount: major, currency }: Money) => number;
6
+ declare const getDecimalFromStripeAmount: ({ amount: minor, currency }: Money) => number;
7
+ declare const formatMoney: ({ amount: minor, currency, locale, }: Money & {
8
+ locale?: string;
9
+ }) => string;
10
+
11
+ export { formatMoney, getDecimalFromStripeAmount, getStripeAmountFromDecimal };
@@ -0,0 +1 @@
1
+ function o(e,n){if(!e)throw new Error(n)}var s=e=>{o(Number.isInteger(e),"Value must be an integer")};var u=e=>(o(e.length===3,"currency needs to be a 3-letter code"),a[e.toUpperCase()]??2),m=({amount:e,currency:n})=>{let t=10**u(n);return Number.parseInt((e*t).toFixed(0),10)},i=({amount:e,currency:n})=>{s(e);let r=u(n),t=10**r;return Number.parseFloat((e/t).toFixed(r))},p=({amount:e,currency:n,locale:r="en-US"})=>{let t=i({amount:e,currency:n});return new Intl.NumberFormat(r,{style:"currency",currency:n}).format(t)},a={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export{p as formatMoney,i as getDecimalFromStripeAmount,m as getStripeAmountFromDecimal};
package/dist/index.d.ts CHANGED
@@ -1,13 +1,12 @@
1
- import Stripe from 'stripe';
2
- import { z, TypeOf } from 'zod';
3
1
  import { CartMetadata, mapCart } from './internal.js';
4
2
  export { MappedProduct } from './internal.js';
3
+ import Stripe from 'stripe';
4
+ import { z, TypeOf } from 'zod';
5
5
 
6
- declare const findStripeAccount: () => string | Promise<string | undefined> | undefined;
7
6
  type Entity = "Product" | "Category" | "Order";
8
7
  type Provider = ({ tags, revalidate, cache, }: {
9
- tags?: string[];
10
- revalidate?: number;
8
+ tags?: NextFetchRequestConfig["tags"];
9
+ revalidate?: NextFetchRequestConfig["revalidate"];
11
10
  cache?: RequestInit["cache"];
12
11
  }) => Stripe;
13
12
  type Filter<T extends Entity> = {
@@ -23,7 +22,7 @@ type BrowseParams<T extends Entity> = {
23
22
  offset?: number;
24
23
  filter?: Filter<T>;
25
24
  };
26
- type SearchParams<T extends Entity> = {
25
+ type SearchParams<_T extends Entity> = {
27
26
  query: string;
28
27
  };
29
28
  type Cart = NonNullable<Awaited<ReturnType<typeof cartGet>>>;
@@ -481,18 +480,6 @@ declare function orderGet(orderId: string): Promise<{
481
480
  }[];
482
481
  shippingRate: Stripe.Response<Stripe.ShippingRate> | null;
483
482
  } | null>;
484
- declare const sanitizeQueryValue: (slug: string | number | boolean) => string;
485
- declare const objectToStripeQuery: (obj: Record<string, string | number | boolean>) => string;
486
- declare const StripeClient: ({ tags, revalidate, cache, }: {
487
- tags?: string[];
488
- revalidate?: number;
489
- cache?: RequestInit["cache"];
490
- }) => Stripe;
491
- declare const provider: ({ tags, revalidate, cache, }: {
492
- tags?: string[];
493
- revalidate?: number;
494
- cache?: RequestInit["cache"];
495
- }) => Stripe;
496
483
  declare const getProductsFromCart: (metadata: CartMetadata) => (readonly [productId: string, quantity: number])[];
497
484
  type MappedCart = ReturnType<typeof mapCart>;
498
485
  declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Promise<{
@@ -684,6 +671,48 @@ declare const getAddressSchema: (tr: {
684
671
  phone?: string | null | undefined;
685
672
  }>;
686
673
  type AddressSchema = TypeOf<ReturnType<typeof getAddressSchema>>;
674
+ declare const calculateCartTotalPossiblyWithTax: (cart: {
675
+ cart: {
676
+ amount: number;
677
+ metadata?: {
678
+ taxCalculationId?: string;
679
+ };
680
+ };
681
+ lines: Array<{
682
+ product: {
683
+ default_price?: {
684
+ unit_amount?: number | null;
685
+ };
686
+ };
687
+ quantity: number;
688
+ }>;
689
+ shippingRate?: {
690
+ fixed_amount?: {
691
+ amount?: number;
692
+ };
693
+ } | null;
694
+ }) => number;
695
+ declare const calculateCartTotalNetWithoutShipping: (cart: {
696
+ cart: {
697
+ amount: number;
698
+ metadata?: {
699
+ taxCalculationId?: string;
700
+ };
701
+ };
702
+ lines: Array<{
703
+ product: {
704
+ default_price?: {
705
+ unit_amount?: number | null;
706
+ };
707
+ };
708
+ quantity: number;
709
+ }>;
710
+ shippingRate?: {
711
+ fixed_amount?: {
712
+ amount?: number;
713
+ };
714
+ } | null;
715
+ }) => number;
687
716
  declare function cartChangeQuantity({ productId, cartId, operation, clearTaxCalculation, }: {
688
717
  productId: string;
689
718
  cartId: string;
@@ -704,12 +733,16 @@ declare function cartSaveBillingAddress({ cartId, billingAddress, }: {
704
733
  }): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
705
734
  declare function taxDefaultGet(): Promise<Stripe.Response<Stripe.Tax.Settings>>;
706
735
  declare function cartCount(metadata: CartMetadata): number;
707
- declare global {
708
- /**
709
- * ⚠️ Warning: This might be `undefined` but TypeScript doesn't have a syntax to express that.
710
- * @see https://github.com/microsoft/TypeScript/issues/36057
711
- */
712
- function __ynsFindStripeAccount(): string | undefined | Promise<string | undefined>;
713
- }
714
736
 
715
- export { type AddressSchema, type Cart, type MappedCart, type ProductsFromMetadata, type ShippingRate, StripeClient, accountGet, calculateCartTotalNet, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveShipping, cartSaveTax, cartSetQuantity, categoryBrowse, fileGet, findStripeAccount, getAddressSchema, getCartWithProductsById, getProductsFromCart, objectToStripeQuery, orderGet, productBrowse, productGet, productGetById, productSearch, provider, sanitizeQueryValue, shippingBrowse, shippingGet, taxDefaultGet };
737
+ declare const StripeClient: ({ tags, revalidate, cache, }: {
738
+ tags?: NextFetchRequestConfig["tags"];
739
+ revalidate?: NextFetchRequestConfig["revalidate"];
740
+ cache?: RequestInit["cache"];
741
+ }) => Stripe;
742
+ declare const provider: ({ tags, revalidate, cache, }: {
743
+ tags?: NextFetchRequestConfig["tags"];
744
+ revalidate?: NextFetchRequestConfig["revalidate"];
745
+ cache?: RequestInit["cache"];
746
+ }) => Stripe;
747
+
748
+ 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 };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"server-only";import{revalidatePath as W,revalidateTag as b}from"next/cache";import h from"stripe";import{z as x}from"zod";import"server-only";import{z as c}from"zod";function C(t,e){if(!t)throw new Error(e)}var Q=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},P=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},O=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};function R(t){return t.toSorted((e,a)=>{let r=Number(e.metadata.order),n=Number(a.metadata.order);return Number.isNaN(r)&&Number.isNaN(n)||r===n?a.updated-e.updated:Number.isNaN(r)?1:Number.isNaN(n)?-1:r-n})}var et=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional()});function B({default_price:t,marketing_features:e,...a}){return C(t,"Product must have a default price"),C(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(r=>r.name).filter(Boolean),metadata:et.parse(a.metadata)}}function A(t){return t.data.map(B)}function L(t){return t.filter((e,a,r)=>a===r.findIndex(n=>n.metadata.slug===e.metadata.slug))}var N=t=>!t.deleted&&t.active,$=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())),G=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function j(t){let e=t.payment_method;C(typeof e!="string","Payment method is missing from cart");let a=$.parse(t.metadata),r=Object.entries(a).filter(([n])=>n.startsWith("taxBreakdown")).map(([n,o])=>{let i=G.safeParse(O(String(o)));return i.success?i.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:r}}function U({payment_method:t,latest_charge:e,...a}){C(typeof t=="object","Payment method is missing from order"),C(typeof e=="object","Latest charge is missing from order");let r=$.parse(a.metadata),n=Object.entries(r).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,i])=>{let s=G.safeParse(O(String(i)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:n,metadata:r}}var m=()=>{if(global.__ynsFindStripeAccount)return global.__ynsFindStripeAccount()},V=process.env.STRIPE_SECRET_KEY;if(!V)throw new Error("Missing STRIPE_SECRET_KEY");var y=process.env.STRIPE_CURRENCY;if(!y)throw new Error("Missing STRIPE_CURRENCY");var q=1e3;function bt({productId:t,cartId:e}){return e?k.add(l,{productId:t,cartId:e}):k.create(l,{productId:t})}function v(t){return k.get(l,{cartId:t})}function St(){return k.create(l,{})}async function Pt({cart:t,add:e}){if(!e)return t;let a=await E(e);if(!a)return console.warn(`Product not found: ${e}`),t;let n=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),o=t?M(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:o},lines:n}}async function Rt({cartId:t,productId:e,quantity:a}){let[r,n]=await Promise.all([z(e),v(t)]);if(!r)throw new Error(`Product not found: ${e}`);if(!n)throw new Error(`Cart not found: ${t}`);if(y?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${y}`);let o=n.cart.metadata??{};a<=0?o[e]="":o[e]=a.toString();let i=M(n)+(r.default_price.unit_amount??0);try{return await S({paymentIntentId:t,data:{metadata:o,amount:i||q}})}catch(s){console.error(s)}finally{b(`cart-${t}`),W("/cart"),W("/cart-overlay")}}async function z(t){let e=await m(),a=l({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return B(r)}catch(r){if(r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function At({slug:t}){let e=await m(),r=await l({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(n=>!n.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return R(A(r).filter(N))}async function rt(t){let e=await m();if(t.filter?.category){let a=t.filter?.category,n=await l({tags:["product",`category-${a}`],cache:"force-cache"}).products.search({limit:100,query:J({active:!0,'metadata["category"]':a}),expand:["data.default_price"]},{stripeAccount:e});return R(L(A(n)).filter(N).slice(t.offset,t.first))}else{let r=await l({tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return R(L(A(r)).filter(N).slice(t.offset,t.first))}}async function Et(){let t=await m();return await l({tags:["shipping"]}).shippingRates.list({active:!0},{stripeAccount:t})}async function T(t){let e=await m(),a=l({tags:["shipping",`shipping-${t}`]});try{return await a.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function vt(t){let a=(await rt({first:100})).map(n=>n.metadata.category),r=new Set(a);return Array.from(r).filter(Boolean)}async function Tt(t){let e=await m(),a=l({tags:["products","search"]}),r=Y(t.query),n=await a.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 R(A(n).filter(o=>o.active&&!o.deleted))}async function It(t){let e=await m(),a=l({tags:["files",`file-${t}`]});try{return await a.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Bt(){let t=await m(),e=l({tags:["account"]});try{let[a,r]=await Q(e.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),n=r?.settings?.branding.logo??null;return!n||typeof n=="string"?{account:r,logo:null}:{account:r,logo:n}}catch(a){if(console.error(a),a instanceof h.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function at(t){let e=await m(),a=l({tags:["order",`order-${t}`]});try{let r=await a.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return U(r)}catch(r){if(r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Nt(t){let e=await at(t);if(!e)return null;let a=H(e.metadata),r=await Promise.all(a.map(async([i,s])=>({product:await E(i),quantity:s}))),{metadata:{shippingRateId:n}}=e,o=n&&await T(n);return{order:e,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}}var Y=t=>t.toString().replace(/"/g,'\\"'),J=t=>Object.entries(t).map(([e,a])=>`${e}:"${Y(a)}"`).join(" AND ").trim(),$t=({tags:t,revalidate:e,cache:a})=>K({next:{tags:t,revalidate:e},cache:a}),K=({cache:t,next:e}={})=>new h(V,{typescript:!0,apiVersion:"2024-06-20",httpClient:h.createFetchHttpClient((r,n)=>fetch(r,{...n,cache:t??n?.cache,next:e??n?.next})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),l=({tags:t,revalidate:e,cache:a})=>K({next:{tags:t,revalidate:e},cache:a}),E=async t=>{let e=await m(),a=l({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return B(r)}catch(r){if(r instanceof h.errors.StripeError&&r.code==="resource_missing")return null;throw r}},X=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],H=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,P(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),nt=async(t,e)=>{let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(X.includes(n.status))return j(n)}catch(n){if(console.error(n),n instanceof h.errors.StripeError&&n.code==="resource_missing")return null;throw n}};async function F(t){let e=H(t);return await Promise.all(e.map(async([r,n])=>({product:await E(r),quantity:n})))}var Z=async(t,e)=>{let a=await nt(t,e);if(!a)return null;let r=await F(a.metadata),{metadata:{shippingRateId:n}}=a,o=n&&await T(n);return{cart:a,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}},ot=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0,it=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function st({oldCart:t,data:e,mergedMetadata:a,lines:r}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let n=Date.now(),o=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!o||n>=o)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,p=it.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),d=r.length!==t.lines.length||r.some(u=>{let g=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==g?.product.default_price.unit_amount||u.quantity!==g?.quantity});return s&&i!==s||p||d}var qt=t=>x.object({name:x.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:x.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:x.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:x.string({required_error:t.line1Required}).min(1,t.line1Required),line2:x.string().optional().nullable().default(""),postalCode:x.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:x.string().optional().nullable().default(""),phone:x.string().optional().nullable().default(""),taxId:x.string().optional().nullable().default("")}),ct=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:r,taxId:n})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let o=await m(),i=l({tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let s=r?await T(r):null,p=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,d=await dt(),f=y==="usd"||y==="cad"?"exclusive":"inclusive",w=d.defaults.tax_behavior==="inferred_by_currency"?f:d.defaults.tax_behavior??f;return d.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y}: ${f}.`),await i.tax.calculations.create({expand:["line_items"],line_items:t.map(g=>({...g,tax_behavior:g.tax_behavior??w})),currency:y,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":w,tax_code:p??d.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:n?[{type:"eu_vat",value:n}]: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:o})},D={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},S=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let r=await m(),n=await Z(l,t);C(n,`Cart not found: ${t}`);let o=$.parse({...n.cart.metadata,...e.metadata}),i=await F(o),p=!a&&st({oldCart:n,data:e,mergedMetadata:o,lines:i})?await ct({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:i.map(({product:u,quantity:g})=>{if(u?.default_price.unit_amount)return{product:u.id,reference:[u.metadata.slug,u.metadata.variant].filter(Boolean).join("-"),quantity:g,amount:u.default_price.unit_amount*g,tax_behavior:u.default_price.tax_behavior==="exclusive"?"exclusive":u.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:u.tax_code?typeof u.tax_code=="string"?u.tax_code:u.tax_code.id:void 0}}).filter(Boolean)}):null,d=e.amount?e.amount.toString():null;if(p){let u=Object.fromEntries(p.tax_breakdown.map(_=>({taxType:_.tax_rate_details.tax_type,taxPercentage:_.tax_rate_details.percentage_decimal,taxAmount:_.amount})).map((_,tt)=>[`taxBreakdown${tt}`,JSON.stringify(_)]));return await l({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,amount:p.amount_total,metadata:{...o,...d&&{netAmount:d},...D,...u,taxCalculationId:p.id,taxCalculationExp:p?.expires_at}},{stripeAccount:r})}return await l({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,metadata:{...o,...d&&{netAmount:d},...a&&{...D,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:r})},k={async create(t,{productId:e,cartId:a}){let r=await m(),n=t({cache:"no-cache"});try{let o=e?await E(e):null;return await n.paymentIntents.create({currency:y,amount:o?.default_price.unit_amount||q,automatic_payment_methods:{enabled:!0},metadata:{...o&&{[o.id]:"1"}}},{stripeAccount:r})}catch(o){throw console.error(o),o}},async get(t,{cartId:e}){let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(X.includes(n.status)){let o=j(n);if(!o)return null;let i=await F(o.metadata),{metadata:{shippingRateId:s}}=o,p=s&&await T(s);return{cart:o,lines:i.map(({product:d,quantity:f})=>d?{product:d,quantity:f}:null).filter(Boolean),shippingRate:p||null}}}catch(n){if(console.error(n),n instanceof h.errors.StripeError&&n.code==="resource_missing")return null;throw n}},async add(t,{cartId:e,productId:a}){return(async({productId:n,cartId:o,operation:i,clearTaxCalculation:s})=>{let[p,d]=await Promise.all([E(n),Z(t,o)]);if(!p)throw new Error(`Product not found: ${n}`);if(!d)throw new Error(`Cart not found: ${o}`);if(y.toLowerCase()!==p.default_price.currency.toLowerCase())throw new Error(`Product currency ${p.default_price.currency} does not match cart currency ${y}`);let f=d.cart.metadata??{},g=P(f[n])+(i==="INCREASE"?1:-1);g<=0?f[n]="":f[n]=g.toString();let I=ot(d)+(p.default_price.unit_amount??0);try{return await S({paymentIntentId:o,data:{metadata:f,amount:I||q},clearTaxCalculation:s})}catch(_){console.error(_)}finally{b(`cart-${o}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},M=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+ut(t):0,ut=t=>t?t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0;async function kt({productId:t,cartId:e,operation:a,clearTaxCalculation:r}){let[n,o]=await Promise.all([z(t),v(e)]);if(!n)throw new Error(`Product not found: ${t}`);if(!o)throw new Error(`Cart not found: ${e}`);if(y?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${y}`);let i=o.cart.metadata??{},d=P(i[t])+(a==="INCREASE"?1:-1);d<=0?i[t]="":i[t]=d.toString();let f=M(o)+(n.default_price.unit_amount??0);try{return await S({paymentIntentId:e,data:{metadata:i,amount:f||q},clearTaxCalculation:r})}catch(w){console.error(w)}finally{b(`cart-${e}`)}}var Mt=async({cartId:t,taxId:e})=>{let a=await v(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(r){console.error(r)}finally{b(`cart-${t}`)}};async function Ot({cartId:t,shippingRateId:e}){let a=await v(t);if(!a)throw new Error(`Cart not found: ${t}`);let r=await T(e);if(!r)throw new Error(`Shipping rate not found: ${e}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:M({...a,shippingRate:r})}})}catch(n){console.error(n)}finally{b(`cart-${t}`)}}async function Lt({cartId:t,billingAddress:e}){if(!await v(t))throw new Error(`Cart not found: ${t}`);try{return await S({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??""}}})}catch(r){console.error(r)}finally{b(`cart-${t}`)}}async function dt(){let t=await m();return await l({tags:["tax-settings"]}).tax.settings.retrieve({},{stripeAccount:t})}function jt(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,P(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{$t as StripeClient,Bt as accountGet,ot as calculateCartTotalNet,bt as cartAdd,Pt as cartAddOptimistic,kt as cartChangeQuantity,jt as cartCount,St as cartCreate,v as cartGet,Lt as cartSaveBillingAddress,Ot as cartSaveShipping,Mt as cartSaveTax,Rt as cartSetQuantity,vt as categoryBrowse,It as fileGet,m as findStripeAccount,qt as getAddressSchema,Z as getCartWithProductsById,H as getProductsFromCart,J as objectToStripeQuery,Nt as orderGet,rt as productBrowse,At as productGet,z as productGetById,Tt as productSearch,l as provider,Y as sanitizeQueryValue,Et as shippingBrowse,T as shippingGet,dt as taxDefaultGet};
1
+ import"server-only";import"server-only";import{z as c}from"zod";function _(t,e){if(!t)throw new Error(e)}var U=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},R=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},F=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var L=t=>t.toString().replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${L(a)}"`).join(" AND ").trim();function P(t){return t.toSorted((e,a)=>{let r=Number(e.metadata.order),n=Number(a.metadata.order);return Number.isNaN(r)&&Number.isNaN(n)||r===n?a.updated-e.updated:Number.isNaN(r)?1:Number.isNaN(n)?-1:r-n})}var rt=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.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(r=>r.name).filter(Boolean),metadata:rt.parse(a.metadata)}}function A(t){return t.data.map(N)}function j(t){return t.filter((e,a,r)=>a===r.findIndex(n=>n.metadata.slug===e.metadata.slug))}var B=t=>!t.deleted&&t.active,q=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string())),W=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Q(t){let e=t.payment_method;_(typeof e!="string","Payment method is missing from cart");let a=q.parse(t.metadata),r=Object.entries(a).filter(([n])=>n.startsWith("taxBreakdown")).map(([n,o])=>{let i=W.safeParse(F(String(o)));return i.success?i.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:r}}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 r=q.parse(a.metadata),n=Object.entries(r).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,i])=>{let s=W.safeParse(F(String(i)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:n,metadata:r}}import"server-only";import{revalidatePath as Y,revalidateTag as S}from"next/cache";import C from"stripe";import{z as x}from"zod";import"server-only";var m=()=>{if(global.__ynsFindStripeAccount)return global.__ynsFindStripeAccount()};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 at=({tags:t,revalidate:e,cache:a})=>new K(g.StripeSecretKey,{typescript:!0,apiVersion:"2024-06-20",httpClient:K.createFetchHttpClient((n,o)=>fetch(n,{...o,cache:a??o?.cache,next:{tags:t??o?.next?.tags,revalidate:e??o?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),p=({tags:t,revalidate:e,cache:a})=>at({tags:t,revalidate:e,cache:a});var $=1e3;function Lt({productId:t,cartId:e}){return e?k.add(p,{productId:t,cartId:e}):k.create(p,{productId:t})}function E(t){return k.get(p,{cartId:t})}function Ot(){return k.create(p,{})}async function jt({cart:t,add:e}){if(!e)return t;let a=await v(e);if(!a)return console.warn(`Product not found: ${e}`),t;let n=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),o=t?M(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:o},lines:n}}async function Qt({cartId:t,productId:e,quantity:a}){let[r,n]=await Promise.all([X(e),E(t)]);if(!r)throw new Error(`Product not found: ${e}`);if(!n)throw new Error(`Cart not found: ${t}`);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=n.cart.metadata??{};a<=0?o[e]="":o[e]=a.toString();let i=M(n)+(r.default_price.unit_amount??0);try{return await b({paymentIntentId:t,data:{metadata:o,amount:i||$}})}catch(s){console.error(s)}finally{S(`cart-${t}`),Y("/cart"),Y("/cart-overlay")}}async function X(t){let e=await m(),a=p({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.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 Gt({slug:t}){let e=await m(),r=await p({tags:["product",`product-${t}`],cache:"force-cache"}).products.search({query:O({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(n=>!n.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return P(A(r).filter(B))}async function nt(t){let e=await m();if(t.filter?.category){let a=t.filter?.category,n=await p({tags:["product",`category-${a}`],cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':a}),expand:["data.default_price"]},{stripeAccount:e});return P(j(A(n)).filter(B).slice(t.offset,t.first))}else{let r=await p({tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return P(j(A(r)).filter(B).slice(t.offset,t.first))}}async function Ut(){let t=await m();return await p({tags:["shipping"]}).shippingRates.list({active:!0},{stripeAccount:t})}async function T(t){let e=await m(),a=p({tags:["shipping",`shipping-${t}`]});try{return await a.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 Wt(t){let a=(await nt({first:100})).map(n=>n.metadata.category),r=new Set(a);return Array.from(r).filter(Boolean)}async function Vt(t){let e=await m(),a=p({tags:["products","search"]}),r=L(t.query),n=await a.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 P(A(n).filter(o=>o.active&&!o.deleted))}async function zt(t){let e=await m(),a=p({tags:["files",`file-${t}`]});try{return await a.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 Dt(){let t=await m(),e=p({tags:["account"]});try{let[a,r]=await U(e.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),n=r?.settings?.branding.logo??null;return!n||typeof n=="string"?{account:r,logo:null}:{account:r,logo:n}}catch(a){if(console.error(a),a instanceof C.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function ot(t){let e=await m(),a=p({tags:["order",`order-${t}`]});try{let r=await a.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 Kt(t){let e=await ot(t);if(!e)return null;let a=Z(e.metadata),r=await Promise.all(a.map(async([i,s])=>({product:await v(i),quantity:s}))),{metadata:{shippingRateId:n}}=e,o=n&&await T(n);return{order:e,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}}var v=async t=>{let e=await m(),a=p({tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await a.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}},H=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Z=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),it=async(t,e)=>{let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(H.includes(n.status))return Q(n)}catch(n){if(console.error(n),n instanceof C.errors.StripeError&&n.code==="resource_missing")return null;throw n}};async function G(t){let e=Z(t);return await Promise.all(e.map(async([r,n])=>({product:await v(r),quantity:n})))}var tt=async(t,e)=>{let a=await it(t,e);if(!a)return null;let r=await G(a.metadata),{metadata:{shippingRateId:n}}=a,o=n&&await T(n);return{cart:a,lines:r.map(({product:i,quantity:s})=>i?{product:i,quantity:s}:null).filter(Boolean),shippingRate:o||null}},st=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:r})=>e+(a.default_price?.unit_amount??0)*r,0):0,ct=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function ut({oldCart:t,data:e,mergedMetadata:a,lines:r}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let n=Date.now(),o=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!o||n>=o)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,l=ct.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),d=r.length!==t.lines.length||r.some(u=>{let y=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==y?.product.default_price.unit_amount||u.quantity!==y?.quantity});return s&&i!==s||l||d}var Yt=t=>x.object({name:x.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:x.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:x.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:x.string({required_error:t.line1Required}).min(1,t.line1Required),line2:x.string().optional().nullable().default(""),postalCode:x.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:x.string().optional().nullable().default(""),phone:x.string().optional().nullable().default(""),taxId:x.string().optional().nullable().default("")}),dt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:r,taxId:n})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let o=await m(),i=p({tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let s=r?await T(r):null,l=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,d=await lt(),f=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",h=d.defaults.tax_behavior==="inferred_by_currency"?f:d.defaults.tax_behavior??f;return d.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${f}.`),await i.tax.calculations.create({expand:["line_items"],line_items:t.map(y=>({...y,tax_behavior:y.tax_behavior??h})),currency:g.StripeCurrency,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":h,tax_code:l??d.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:n?[{type:"eu_vat",value:n}]: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:o})},J={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},b=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let r=await m(),n=await tt(p,t);_(n,`Cart not found: ${t}`);let o=q.parse({...n.cart.metadata,...e.metadata}),i=await G(o),l=!a&&ut({oldCart:n,data:e,mergedMetadata:o,lines:i})?await dt({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:i.map(({product:u,quantity:y})=>{if(u?.default_price.unit_amount)return{product:u.id,reference:[u.metadata.slug,u.metadata.variant].filter(Boolean).join("-"),quantity:y,amount:u.default_price.unit_amount*y,tax_behavior:u.default_price.tax_behavior==="exclusive"?"exclusive":u.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:u.tax_code?typeof u.tax_code=="string"?u.tax_code:u.tax_code.id:void 0}}).filter(Boolean)}):null,d=e.amount?e.amount.toString():null;if(l){let u=Object.fromEntries(l.tax_breakdown.map(w=>({taxType:w.tax_rate_details.tax_type,taxPercentage:w.tax_rate_details.percentage_decimal,taxAmount:w.amount})).map((w,et)=>[`taxBreakdown${et}`,JSON.stringify(w)]));return await p({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,amount:l.amount_total,metadata:{...o,...d&&{netAmount:d},...J,...u,taxCalculationId:l.id,taxCalculationExp:l?.expires_at}},{stripeAccount:r})}return await p({tags:[],cache:"no-cache"}).paymentIntents.update(t,{...e,metadata:{...o,...d&&{netAmount:d},...a&&{...J,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:r})},k={async create(t,{productId:e,cartId:a}){let r=await m(),n=t({cache:"no-cache"});try{let o=e?await v(e):null;return await n.paymentIntents.create({currency:g.StripeCurrency,amount:o?.default_price.unit_amount||$,automatic_payment_methods:{enabled:!0},metadata:{...o&&{[o.id]:"1"}}},{stripeAccount:r})}catch(o){throw console.error(o),o}},async get(t,{cartId:e}){let a=await m(),r=t({tags:["cart",`cart-${e}`],cache:"force-cache"});try{let n=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(H.includes(n.status)){let o=Q(n);if(!o)return null;let i=await G(o.metadata),{metadata:{shippingRateId:s}}=o,l=s&&await T(s);return{cart:o,lines:i.map(({product:d,quantity:f})=>d?{product:d,quantity:f}:null).filter(Boolean),shippingRate:l||null}}}catch(n){if(console.error(n),n instanceof C.errors.StripeError&&n.code==="resource_missing")return null;throw n}},async add(t,{cartId:e,productId:a}){return(async({productId:n,cartId:o,operation:i,clearTaxCalculation:s})=>{let[l,d]=await Promise.all([v(n),tt(t,o)]);if(!l)throw new Error(`Product not found: ${n}`);if(!d)throw new Error(`Cart not found: ${o}`);if(g.StripeCurrency.toLowerCase()!==l.default_price.currency.toLowerCase())throw new Error(`Product currency ${l.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let f=d.cart.metadata??{},y=R(f[n])+(i==="INCREASE"?1:-1);y<=0?f[n]="":f[n]=y.toString();let I=st(d)+(l.default_price.unit_amount??0);try{return await b({paymentIntentId:o,data:{metadata:f,amount:I||$},clearTaxCalculation:s})}catch(w){console.error(w)}finally{S(`cart-${o}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},M=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:r})=>e+(a.default_price?.unit_amount??0)*r,0):0;async function Jt({productId:t,cartId:e,operation:a,clearTaxCalculation:r}){let[n,o]=await Promise.all([X(t),E(e)]);if(!n)throw new Error(`Product not found: ${t}`);if(!o)throw new Error(`Cart not found: ${e}`);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=o.cart.metadata??{},d=R(i[t])+(a==="INCREASE"?1:-1);d<=0?i[t]="":i[t]=d.toString();let f=M(o)+(n.default_price.unit_amount??0);try{return await b({paymentIntentId:e,data:{metadata:i,amount:f||$},clearTaxCalculation:r})}catch(h){console.error(h)}finally{S(`cart-${e}`)}}var Xt=async({cartId:t,taxId:e})=>{let a=await E(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await b({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(r){console.error(r)}finally{S(`cart-${t}`)}};async function Ht({cartId:t,shippingRateId:e}){let a=await E(t);if(!a)throw new Error(`Cart not found: ${t}`);let r=await T(e);if(!r)throw new Error(`Shipping rate not found: ${e}`);try{return await b({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:M({...a,shippingRate:r})}})}catch(n){console.error(n)}finally{S(`cart-${t}`)}}async function Zt({cartId:t,billingAddress:e}){if(!await E(t))throw new Error(`Cart not found: ${t}`);try{return await b({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(r){console.error(r)}finally{S(`cart-${t}`)}}async function lt(){let t=await m();return await p({tags:["tax-settings"]}).tax.settings.retrieve({},{stripeAccount:t})}function te(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{at as StripeClient,Dt as accountGet,st as calculateCartTotalNet,pt as calculateCartTotalNetWithoutShipping,M as calculateCartTotalPossiblyWithTax,Lt as cartAdd,jt as cartAddOptimistic,Jt as cartChangeQuantity,te as cartCount,Ot as cartCreate,E as cartGet,Zt as cartSaveBillingAddress,Ht as cartSaveShipping,Xt as cartSaveTax,Qt as cartSetQuantity,Wt as categoryBrowse,zt as fileGet,Yt as getAddressSchema,tt as getCartWithProductsById,Z as getProductsFromCart,Kt as orderGet,nt as productBrowse,Gt as productGet,X as productGetById,Vt as productSearch,p as provider,Ut as shippingBrowse,T as shippingGet,lt as taxDefaultGet};
@@ -1,7 +1,13 @@
1
1
  import Stripe from 'stripe';
2
2
  import { z } from 'zod';
3
3
 
4
+ declare const sanitizeQueryValue: (slug: string | number | boolean) => string;
5
+ declare const objectToStripeQuery: (obj: Record<string, string | number | boolean>) => string;
6
+
4
7
  type MappedProduct = ReturnType<typeof mapProduct>;
8
+ /**
9
+ * @internal
10
+ */
5
11
  declare function sortProducts(products: MappedProduct[]): {
6
12
  default_price: Stripe.Price;
7
13
  marketing_features: string[];
@@ -29,6 +35,26 @@ declare function sortProducts(products: MappedProduct[]): {
29
35
  updated: number;
30
36
  url: string | null;
31
37
  }[];
38
+ declare const productMetadataSchema: z.ZodObject<{
39
+ category: z.ZodOptional<z.ZodString>;
40
+ order: z.ZodOptional<z.ZodNumber>;
41
+ slug: z.ZodString;
42
+ variant: z.ZodOptional<z.ZodString>;
43
+ }, "strip", z.ZodTypeAny, {
44
+ slug: string;
45
+ category?: string | undefined;
46
+ order?: number | undefined;
47
+ variant?: string | undefined;
48
+ }, {
49
+ slug: string;
50
+ category?: string | undefined;
51
+ order?: number | undefined;
52
+ variant?: string | undefined;
53
+ }>;
54
+ type ProductMetadata = z.infer<typeof productMetadataSchema>;
55
+ /**
56
+ * @internal
57
+ */
32
58
  declare function mapProduct({ default_price, marketing_features, ...product }: Stripe.Product): {
33
59
  default_price: Stripe.Price;
34
60
  marketing_features: string[];
@@ -56,6 +82,9 @@ declare function mapProduct({ default_price, marketing_features, ...product }: S
56
82
  updated: number;
57
83
  url: string | null;
58
84
  };
85
+ /**
86
+ * @internal
87
+ */
59
88
  declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<Stripe.Product> | Stripe.ApiList<Stripe.Product>>): {
60
89
  default_price: Stripe.Price;
61
90
  marketing_features: string[];
@@ -83,6 +112,9 @@ declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<St
83
112
  updated: number;
84
113
  url: string | null;
85
114
  }[];
115
+ /**
116
+ * @internal
117
+ */
86
118
  declare function getUniqueVariants(products: MappedProduct[]): {
87
119
  default_price: Stripe.Price;
88
120
  marketing_features: string[];
@@ -110,7 +142,13 @@ declare function getUniqueVariants(products: MappedProduct[]): {
110
142
  updated: number;
111
143
  url: string | null;
112
144
  }[];
145
+ /**
146
+ * @internal
147
+ */
113
148
  declare const isProductAvailable: (product: MappedProduct) => boolean;
149
+ /**
150
+ * @internal
151
+ */
114
152
  declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
115
153
  shippingRateId: z.ZodOptional<z.ZodString>;
116
154
  taxCalculationId: z.ZodOptional<z.ZodString>;
@@ -170,6 +208,9 @@ declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
170
208
  taxBreakdown5?: string | undefined;
171
209
  }>, z.ZodRecord<z.ZodString, z.ZodString>>;
172
210
  type CartMetadata = z.infer<typeof cartMetadataSchema>;
211
+ /**
212
+ * @internal
213
+ */
173
214
  declare const cartMetadataTaxBreakdownSchema: z.ZodObject<{
174
215
  taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
175
216
  taxPercentage: z.ZodString;
@@ -183,6 +224,9 @@ declare const cartMetadataTaxBreakdownSchema: z.ZodObject<{
183
224
  taxAmount: number;
184
225
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
185
226
  }>;
227
+ /**
228
+ * @internal
229
+ */
186
230
  declare function mapCart(cart: Stripe.PaymentIntent): {
187
231
  metadata: {
188
232
  shippingRateId?: string | undefined;
@@ -249,6 +293,9 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
249
293
  transfer_data: Stripe.PaymentIntent.TransferData | null;
250
294
  transfer_group: string | null;
251
295
  };
296
+ /**
297
+ * @internal
298
+ */
252
299
  declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.PaymentIntent): {
253
300
  payment_method: Stripe.PaymentMethod | null;
254
301
  latest_charge: Stripe.Charge | null;
@@ -316,4 +363,4 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
316
363
  transfer_group: string | null;
317
364
  };
318
365
 
319
- export { type CartMetadata, type MappedProduct, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, sortProducts };
366
+ export { type CartMetadata, type MappedProduct, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, 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}};function P(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 m=t.object({category:t.string().optional(),order:t.coerce.number().optional(),slug:t.string(),variant:t.string().optional()});function g({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:m.parse(n.metadata)}}function w(e){return e.data.map(g)}function k(e){return e.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var S=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 N(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 d=c.safeParse(p(String(s)));return d.success?d.data:null}).filter(Boolean);return{...e,metadata:n,payment_method:r,taxBreakdown:a}}function B({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,d])=>{let u=c.safeParse(p(String(d)));return u.success?u.data:null}).filter(Boolean);return{...n,payment_method:e,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,k as getUniqueVariants,S as isProductAvailable,N as mapCart,B as mapOrder,g as mapProduct,w as mapProducts,P as sortProducts};
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,'\\"'),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};
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.5",
4
+ "version": "0.0.6",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -14,6 +14,10 @@
14
14
  "import": "./dist/index.js",
15
15
  "types": "./dist/index.d.ts"
16
16
  },
17
+ "./currencies": {
18
+ "import": "./dist/currencies.js",
19
+ "types": "./dist/currencies.d.ts"
20
+ },
17
21
  "./internal": {
18
22
  "import": "./dist/internal.js",
19
23
  "types": "./dist/internal.d.ts"
@@ -26,9 +30,6 @@
26
30
  "LICENSE.md"
27
31
  ],
28
32
  "sideEffects": false,
29
- "dependencies": {
30
- "server-only": "^0.0.1"
31
- },
32
33
  "devDependencies": {
33
34
  "@types/node": "^20.14.8",
34
35
  "@types/react": "npm:types-react@19.0.0-rc.1",
@@ -38,6 +39,7 @@
38
39
  "react": "^19.0.0-rc.1",
39
40
  "react-dom": "^19.0.0-rc.1",
40
41
  "rimraf": "5.0.7",
42
+ "server-only": "0.0.1",
41
43
  "stripe": "^16.5.0",
42
44
  "tsup": "8.1.0",
43
45
  "tsx": "^4.15.7",
@@ -50,6 +52,7 @@
50
52
  "next": "15.0.0-canary.96",
51
53
  "react": "19.0.0-rc-3208e73e-20240730",
52
54
  "react-dom": "19.0.0-rc-3208e73e-20240730",
55
+ "server-only": "0.0.1",
53
56
  "stripe": "^16.5.0",
54
57
  "typescript": "^5.5.4",
55
58
  "zod": "^3.23.8"