commerce-kit 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { formatMoney } from './currencies.js';
2
2
  export { MappedCart, MappedProduct, MappedShippingRate } from './internal.js';
3
- export { B as BaseProvider, C as Cart, a as CartAddParams, b as CartClearParams, c as CartGetParams, d as CartItem, e as CartUpdateParams, O as Order, f as OrderGetParams, g as OrderListParams, h as OrderListResult, P as Product, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, l as ProductSearchParams, m as ProductSearchResult, S as StripeProviderConfig, Y as YnsProviderConfig } from './provider-CvZe8Dqo.js';
3
+ export { B as BaseProvider, C as Cart, a as CartAddParams, b as CartClearParams, c as CartGetParams, d as CartItem, e as CartRemoveParams, f as CartUpdateParams, O as Order, g as OrderGetParams, h as OrderListParams, i as OrderListResult, P as Product, j as ProductBrowseParams, k as ProductBrowseResult, l as ProductGetParams, m as ProductSearchParams, n as ProductSearchResult, S as StripeProviderConfig, Y as YnsProduct, o as YnsProviderConfig } from './provider-nJuubkrT.js';
4
4
  export { Commerce } from './yns.js';
5
5
  import 'stripe';
6
6
  import 'zod';
package/dist/index.js CHANGED
@@ -1,238 +1 @@
1
- var C=Object.defineProperty;var p=(e,r)=>()=>(e&&(r=e(e=0)),r);var w=(e,r)=>{for(var t in r)C(e,t,{get:r[t],enumerable:!0})};function g(e){return!e||e.length===0?c:`
2
- query ProductQuery($slug: String!) {
3
- product(slug: $slug) {
4
- ${e.join(`
5
- `)}
6
- }
7
- }
8
- `}function y(e){return!e||e.length===0?d:`
9
- query ProductsQuery(
10
- $offset: Int
11
- $limit: Int
12
- $category: String
13
- $query: String
14
- $active: Boolean
15
- $excludeBundles: Boolean
16
- $orderBy: String
17
- $orderDirection: String
18
- ) {
19
- products(
20
- offset: $offset
21
- limit: $limit
22
- category: $category
23
- query: $query
24
- active: $active
25
- excludeBundles: $excludeBundles
26
- orderBy: $orderBy
27
- orderDirection: $orderDirection
28
- ) {
29
- data {
30
- ${e.join(`
31
- `)}
32
- }
33
- meta {
34
- count
35
- offset
36
- limit
37
- hasMore
38
- }
39
- }
40
- }
41
- `}var m,d,c,R,P,v=p(()=>{"use strict";m=`
42
- fragment ProductFragment on Product {
43
- id
44
- name
45
- slug
46
- summary
47
- images
48
- active
49
- type
50
- createdAt
51
- updatedAt
52
- category {
53
- id
54
- name
55
- slug
56
- description
57
- image
58
- }
59
- variants {
60
- id
61
- price
62
- originalPrice
63
- prePromotionPrice
64
- stock
65
- shippable
66
- attributes
67
- combinations {
68
- id
69
- variantValue {
70
- id
71
- value
72
- colorValue
73
- variantType {
74
- id
75
- label
76
- type
77
- }
78
- }
79
- }
80
- }
81
- collections {
82
- id
83
- name
84
- slug
85
- description
86
- image
87
- active
88
- }
89
- bundleProducts {
90
- id
91
- quantity
92
- position
93
- variant {
94
- id
95
- price
96
- originalPrice
97
- stock
98
- }
99
- }
100
- bundleDiscountPercentage
101
- }
102
- `,d=`
103
- query ProductsQuery(
104
- $offset: Int
105
- $limit: Int
106
- $category: String
107
- $query: String
108
- $active: Boolean
109
- $excludeBundles: Boolean
110
- $orderBy: String
111
- $orderDirection: String
112
- ) {
113
- products(
114
- offset: $offset
115
- limit: $limit
116
- category: $category
117
- query: $query
118
- active: $active
119
- excludeBundles: $excludeBundles
120
- orderBy: $orderBy
121
- orderDirection: $orderDirection
122
- ) {
123
- data {
124
- ...ProductFragment
125
- }
126
- meta {
127
- count
128
- offset
129
- limit
130
- hasMore
131
- }
132
- }
133
- }
134
- ${m}
135
- `,c=`
136
- query ProductQuery($slug: String!) {
137
- product(slug: $slug) {
138
- ...ProductFragment
139
- }
140
- }
141
- ${m}
142
- `,R=`
143
- fragment CartFragment on Cart {
144
- id
145
- customerId
146
- storeId
147
- shippingId
148
- couponId
149
- billingAddressId
150
- shippingAddressId
151
- stripePaymentIntentId
152
- checkoutSessionId
153
- addonData
154
- createdAt
155
- updatedAt
156
- customer {
157
- id
158
- email
159
- userId
160
- user {
161
- id
162
- email
163
- name
164
- }
165
- }
166
- coupon {
167
- code
168
- type
169
- value
170
- startDate
171
- endDate
172
- }
173
- lineItems {
174
- id
175
- cartId
176
- productVariantId
177
- subscriptionId
178
- quantity
179
- createdAt
180
- updatedAt
181
- productVariant {
182
- id
183
- price
184
- originalPrice
185
- stock
186
- shippable
187
- attributes
188
- }
189
- subscription {
190
- id
191
- name
192
- price
193
- interval
194
- intervalCount
195
- }
196
- }
197
- billingAddress {
198
- id
199
- name
200
- company
201
- line1
202
- line2
203
- city
204
- state
205
- postalCode
206
- country
207
- phone
208
- type
209
- }
210
- shippingAddress {
211
- id
212
- name
213
- company
214
- line1
215
- line2
216
- city
217
- state
218
- postalCode
219
- country
220
- phone
221
- type
222
- }
223
- shipping {
224
- id
225
- name
226
- price
227
- minValue
228
- maxValue
229
- }
230
- }
231
- `,P=`
232
- query CartQuery($id: String!) {
233
- cart(id: $id) {
234
- ...CartFragment
235
- }
236
- }
237
- ${R}
238
- `});var f={};w(f,{YnsProvider:()=>n,createYnsProvider:()=>T});function T(e){return new n(e)}var n,h=p(()=>{"use strict";v();n=class{config;constructor(r){this.config=r}async graphqlRequest(r,t){let o=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:r,variables:t})});if(!o.ok)throw new Error(`YNS GraphQL request failed: ${o.status} ${o.statusText}`);let i=await o.json();if(i.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(i.errors)}`);return i.data}async restRequest(r,t="GET",o){let i=await fetch(`${this.config.endpoint}/api${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:o?JSON.stringify(o):void 0});if(!i.ok)throw new Error(`YNS REST request failed: ${i.status} ${i.statusText}`);return i.json()}mapYnsProduct(r){return{id:r.id,name:r.name,slug:r.slug,summary:r.summary,images:r.images||[],active:r.active,price:r.variants?.[0]?.price?Number.parseFloat(r.variants[0].price):0,currency:"USD",stock:r.variants?.[0]?.stock,category:r.category,variants:r.variants?.map(t=>({id:t.id,price:Number.parseFloat(t.price),stock:t.stock,attributes:t.attributes}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(i=>({id:i.id,productId:i.productVariant?.id||"",variantId:i.productVariantId,quantity:i.quantity,price:Number.parseFloat(i.productVariant?.price||"0")}))||[],o=t.reduce((i,a)=>i+a.price*a.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:o,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}async productBrowse(r){let t=r.fields?y(r.fields):d,o={offset:r.offset||0,limit:r.first||r.offset||10,category:r.category,query:r.query,active:r.active,excludeBundles:!1,orderBy:r.orderBy,orderDirection:r.orderDirection},i=await this.graphqlRequest(t,o);return{data:i.products.data.map(a=>this.mapYnsProduct(a)),meta:i.products.meta}}async productGet(r){if(!r.slug&&!r.id)throw new Error("Either slug or id is required for productGet");let t=r.fields?g(r.fields):c,o={slug:r.slug},i=await this.graphqlRequest(t,o);return i.product?this.mapYnsProduct(i.product):null}async cartAdd(r){let t={variantId:r.variantId,cartId:r.cartId,subscriptionId:r.subscriptionId};return await this.restRequest("/cart","POST",t)}async cartUpdate(r){let t={variantId:r.variantId,quantity:r.quantity};return await this.restRequest(`/cart/${r.cartId}`,"PUT",t)}async cartClear(r){return await this.restRequest(`/cart/${r.cartId}`,"DELETE")}async cartGet(r){let t=await this.graphqlRequest(P,{id:r.cartId});return t.cart?this.mapYnsCart(t.cart):null}}});function s(e,r){if(!e)throw new Error(r)}var l=e=>{s(Number.isInteger(e),"Value must be an integer")};var I=e=>(s(e.length===3,"currency needs to be a 3-letter code"),b[e.toUpperCase()]??2);var $=({amount:e,currency:r})=>{l(e);let t=I(r),o=10**t;return Number.parseFloat((e/o).toFixed(t))},S=({amount:e,currency:r,locale:t="en-US"})=>{let o=$({amount:e,currency:r});return new Intl.NumberFormat(t,{style:"currency",currency:r}).format(o)},b={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};var u=class{config;provider;providerPromise;constructor(r){if(this.config=r||this.detectFromEnv(),!this.config.endpoint||!this.config.token)throw new Error("YNS configuration required. Provide endpoint and token in constructor or set YNS_ENDPOINT and YNS_TOKEN environment variables.")}detectFromEnv(){return{endpoint:process.env.YNS_ENDPOINT||"",token:process.env.YNS_TOKEN||""}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createYnsProvider:r}=await Promise.resolve().then(()=>(h(),f));return r(this.config)}catch(r){throw new Error(`Failed to initialize YNS provider: ${r instanceof Error?r.message:"Unknown error"}`)}}get product(){return{browse:async(r={})=>(await this.getProvider()).productBrowse(r),get:async r=>(await this.getProvider()).productGet(r),search:async r=>{let t=await this.getProvider();if(!t.productSearch)throw new Error("Product search is not supported by YNS provider");return t.productSearch(r)}}}get cart(){return{add:async r=>(await this.getProvider()).cartAdd(r),update:async r=>(await this.getProvider()).cartUpdate(r),clear:async r=>(await this.getProvider()).cartClear(r),get:async r=>(await this.getProvider()).cartGet(r)}}get order(){return{get:async r=>{let t=await this.getProvider();if(!t.orderGet)throw new Error("Order retrieval is not supported by YNS provider");return t.orderGet(r)},list:async(r={})=>{let t=await this.getProvider();if(!t.orderList)throw new Error("Order listing is not supported by YNS provider");return t.orderList(r)}}}};export{u as Commerce,S as formatMoney};
1
+ var v=Object.defineProperty;var f=(i,r)=>()=>(i&&(r=i(i=0)),r);var g=(i,r)=>{for(var t in r)v(i,t,{get:r[t],enumerable:!0})};var l={};g(l,{YnsProvider:()=>d,createYnsProvider:()=>S});function S(i){return new d(i)}var d,m=f(()=>{"use strict";d=class{config;constructor(r){this.config=r}async graphqlRequest(r,t){let e=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:r,variables:t})});if(!e.ok)throw new Error(`YNS GraphQL request failed: ${e.status} ${e.statusText}`);let o=await e.json();if(o.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(o.errors)}`);return o.data}async restRequest(r,t="GET",e){let o=await fetch(`${this.config.endpoint}/api${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:e?JSON.stringify(e):void 0});if(!o.ok){let s=o.headers.get("content-type"),n=`YNS REST request failed: ${o.status} ${o.statusText}`;if(s?.includes("application/json"))try{let p=await o.json();n=p.error||p.message||n}catch{}throw new Error(n)}let a=o.headers.get("content-type");if(!a?.includes("application/json"))throw new Error(`YNS API returned ${a} instead of JSON for ${r}`);return o.json()}mapYnsProduct(r){return{id:r.id,name:r.name,slug:r.slug,summary:r.summary,images:r.images||[],active:r.active,price:r.variants?.[0]?.price?Number.parseFloat(r.variants[0].price):0,currency:"USD",stock:r.variants?.[0]?.stock,category:r.category,variants:r.variants?.map(t=>({id:t.id,price:Number.parseFloat(t.price),stock:t.stock,attributes:t.attributes}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(o=>({id:o.id,productId:o.productVariant?.id||"",variantId:o.productVariantId,quantity:o.quantity,price:Number.parseFloat(o.productVariant?.price||"0")}))||[],e=t.reduce((o,a)=>o+a.price*a.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:e,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}async productBrowse(r){if(r.graphql){let t={offset:r.offset||0,limit:r.first||10,category:r.category,query:r.query,active:r.active,orderBy:r.orderBy,orderDirection:r.orderDirection},e=await this.graphqlRequest(r.graphql,t);return{data:e.products.data.map(o=>this.mapYnsProduct(o)),meta:e.products.meta}}else{let t=new URLSearchParams;r.first&&t.append("limit",r.first.toString()),r.offset&&t.append("offset",r.offset.toString()),r.category&&t.append("category",r.category),r.query&&t.append("q",r.query),r.active!==void 0&&t.append("active",r.active.toString()),r.orderBy&&t.append("orderBy",r.orderBy),r.orderDirection&&t.append("orderDirection",r.orderDirection);let e=`/products${t.toString()?`?${t.toString()}`:""}`,o=await this.restRequest(e);return{data:o.data.map(a=>this.mapYnsProduct(a)),meta:o.meta}}}async productGet(r){if(!r.slug&&!r.id)throw new Error("Either slug or id is required for productGet");if(r.graphql){let t={slug:r.slug,id:r.id},e=await this.graphqlRequest(r.graphql,t);return e.product?this.mapYnsProduct(e.product):null}else{let t=`/products/${r.id||r.slug}`,e=await this.restRequest(t);return e?this.mapYnsProduct(e):null}}async cartAdd(r){let t=r.quantity;if(r.cartId)try{let a=await this.cartGet({cartId:r.cartId});if(a){let s=a.items.find(n=>n.variantId===r.variantId);s&&(t=s.quantity+r.quantity)}}catch{}let e={variantId:r.variantId,cartId:r.cartId,quantity:t,subscriptionId:r.subscriptionId},o=await this.restRequest("/cart","POST",e);return this.mapYnsCart(o)}async cartUpdate(r){let t={variantId:r.variantId,cartId:r.cartId,quantity:r.quantity},e=await this.restRequest("/cart","POST",t);return this.mapYnsCart(e)}async cartRemove(r){let t=`/cart/${r.cartId}/items/${r.variantId}`,e=await this.restRequest(t,"DELETE");return this.mapYnsCart(e)}async cartClear(r){let t=await this.restRequest(`/cart/${r.cartId}`,"DELETE");return this.mapYnsCart(t)}async cartGet(r){let t=await this.restRequest(`/cart/${r.cartId}`);return t?this.mapYnsCart(t):null}}});function c(i,r){if(!i)throw new Error(r)}var P=i=>{c(Number.isInteger(i),"Value must be an integer")};var h=i=>(c(i.length===3,"currency needs to be a 3-letter code"),C[i.toUpperCase()]??2);var y=({amount:i,currency:r})=>{P(i);let t=h(r),e=10**t;return Number.parseFloat((i/e).toFixed(t))},w=({amount:i,currency:r,locale:t="en-US"})=>{let e=y({amount:i,currency:r});return new Intl.NumberFormat(t,{style:"currency",currency:r}).format(e)},C={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};var u=class{config;provider;providerPromise;constructor(r){if(this.config=r||this.detectFromEnv(),!this.config.endpoint||!this.config.token)throw new Error("YNS configuration required. Provide endpoint and token in constructor or set YNS_ENDPOINT and YNS_TOKEN environment variables.")}detectFromEnv(){return{endpoint:process.env.YNS_ENDPOINT||"",token:process.env.YNS_TOKEN||""}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createYnsProvider:r}=await Promise.resolve().then(()=>(m(),l));return r(this.config)}catch(r){throw new Error(`Failed to initialize YNS provider: ${r instanceof Error?r.message:"Unknown error"}`)}}get product(){return{browse:async(r={})=>(await this.getProvider()).productBrowse(r),get:async r=>(await this.getProvider()).productGet(r),search:async r=>{let t=await this.getProvider();if(!t.productSearch)throw new Error("Product search is not supported by YNS provider");return t.productSearch(r)}}}get cart(){return{add:async r=>(await this.getProvider()).cartAdd(r),update:async r=>(await this.getProvider()).cartUpdate(r),remove:async r=>(await this.getProvider()).cartRemove(r),clear:async r=>(await this.getProvider()).cartClear(r),get:async r=>(await this.getProvider()).cartGet(r)}}get order(){return{get:async r=>{let t=await this.getProvider();if(!t.orderGet)throw new Error("Order retrieval is not supported by YNS provider");return t.orderGet(r)},list:async(r={})=>{let t=await this.getProvider();if(!t.orderList)throw new Error("Order listing is not supported by YNS provider");return t.orderList(r)}}}};export{u as Commerce,w as formatMoney};
@@ -10,7 +10,7 @@ type MappedProduct = ReturnType<typeof mapProduct>;
10
10
  */
11
11
  declare function sortProducts(products: MappedProduct[]): {
12
12
  default_price: Stripe.Price;
13
- marketing_features: string[];
13
+ marketing_features: (string | undefined)[];
14
14
  metadata: {
15
15
  slug: string;
16
16
  stock: number;
@@ -53,7 +53,7 @@ type ProductMetadata = z.infer<typeof ProductMetadataSchema>;
53
53
  */
54
54
  declare function mapProduct({ default_price, marketing_features, ...product }: Stripe.Product): {
55
55
  default_price: Stripe.Price;
56
- marketing_features: string[];
56
+ marketing_features: (string | undefined)[];
57
57
  metadata: {
58
58
  slug: string;
59
59
  stock: number;
@@ -126,7 +126,7 @@ declare function filterValidProducts(products: Stripe.Response<Stripe.ApiSearchR
126
126
  */
127
127
  declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<Stripe.Product> | Stripe.ApiList<Stripe.Product>>): {
128
128
  default_price: Stripe.Price;
129
- marketing_features: string[];
129
+ marketing_features: (string | undefined)[];
130
130
  metadata: {
131
131
  slug: string;
132
132
  stock: number;
@@ -168,7 +168,7 @@ declare function mapShippingRates(shippingRates: Stripe.ApiList<Stripe.ShippingR
168
168
  */
169
169
  declare function getUniqueVariants(products: MappedProduct[]): {
170
170
  default_price: Stripe.Price;
171
- marketing_features: string[];
171
+ marketing_features: (string | undefined)[];
172
172
  metadata: {
173
173
  slug: string;
174
174
  stock: number;
@@ -262,11 +262,11 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
262
262
  } & Record<string, string>;
263
263
  customer: Stripe.Customer | null;
264
264
  payment_method: Stripe.PaymentMethod | null;
265
- taxBreakdown: {
265
+ taxBreakdown: ({
266
266
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
267
267
  taxPercentage: string;
268
268
  taxAmount: number;
269
- }[];
269
+ } | null)[];
270
270
  id: string;
271
271
  object: "payment_intent";
272
272
  amount: number;
@@ -313,11 +313,11 @@ type MappedCart = ReturnType<typeof mapCart>;
313
313
  declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.PaymentIntent): {
314
314
  payment_method: Stripe.PaymentMethod | null;
315
315
  latest_charge: Stripe.Charge | null;
316
- taxBreakdown: {
316
+ taxBreakdown: ({
317
317
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
318
318
  taxPercentage: string;
319
319
  taxAmount: number;
320
- }[];
320
+ } | null)[];
321
321
  metadata: {
322
322
  shippingRateId?: string | undefined;
323
323
  taxCalculationId?: string | undefined;
@@ -2,15 +2,10 @@ interface BaseProvider {
2
2
  productBrowse(params: ProductBrowseParams): Promise<ProductBrowseResult>;
3
3
  productGet(params: ProductGetParams): Promise<Product | null>;
4
4
  productSearch?(params: ProductSearchParams): Promise<ProductSearchResult>;
5
- cartAdd(params: CartAddParams): Promise<{
6
- cartId: string;
7
- }>;
8
- cartUpdate(params: CartUpdateParams): Promise<{
9
- cartId: string;
10
- }>;
11
- cartClear(params: CartClearParams): Promise<{
12
- cartId: string;
13
- }>;
5
+ cartAdd(params: CartAddParams): Promise<Cart>;
6
+ cartUpdate(params: CartUpdateParams): Promise<Cart>;
7
+ cartRemove(params: CartRemoveParams): Promise<Cart>;
8
+ cartClear(params: CartClearParams): Promise<Cart>;
14
9
  cartGet(params: CartGetParams): Promise<Cart | null>;
15
10
  orderGet?(params: OrderGetParams): Promise<Order | null>;
16
11
  orderList?(params: OrderListParams): Promise<OrderListResult>;
@@ -68,13 +63,13 @@ interface ProductBrowseParams {
68
63
  active?: boolean;
69
64
  orderBy?: string;
70
65
  orderDirection?: "asc" | "desc";
71
- fields?: string[];
66
+ graphql?: string;
72
67
  _provider?: "stripe" | "yns";
73
68
  }
74
69
  interface ProductGetParams {
75
70
  slug?: string;
76
71
  id?: string;
77
- fields?: string[];
72
+ graphql?: string;
78
73
  _provider?: "stripe" | "yns";
79
74
  }
80
75
  interface ProductSearchParams {
@@ -85,15 +80,14 @@ interface ProductSearchParams {
85
80
  }
86
81
  interface CartAddParams {
87
82
  variantId: string;
83
+ quantity: number;
88
84
  cartId?: string;
89
- quantity?: number;
90
85
  subscriptionId?: string;
91
86
  _provider?: "stripe" | "yns";
92
87
  }
93
- interface CartUpdateParams {
88
+ interface CartRemoveParams {
94
89
  cartId: string;
95
90
  variantId: string;
96
- quantity: number;
97
91
  _provider?: "stripe" | "yns";
98
92
  }
99
93
  interface CartClearParams {
@@ -104,6 +98,12 @@ interface CartGetParams {
104
98
  cartId: string;
105
99
  _provider?: "stripe" | "yns";
106
100
  }
101
+ interface CartUpdateParams {
102
+ cartId: string;
103
+ variantId: string;
104
+ quantity: number;
105
+ _provider?: "stripe" | "yns";
106
+ }
107
107
  interface OrderGetParams {
108
108
  orderId: string;
109
109
  _provider?: "stripe" | "yns";
@@ -136,5 +136,18 @@ interface OrderListResult {
136
136
  hasMore: boolean;
137
137
  };
138
138
  }
139
+ interface YnsProduct extends Product {
140
+ category?: {
141
+ id: string;
142
+ name: string;
143
+ slug: string;
144
+ };
145
+ variants: Array<{
146
+ id: string;
147
+ price: number;
148
+ stock?: number;
149
+ attributes?: string;
150
+ }>;
151
+ }
139
152
 
140
- export type { BaseProvider as B, Cart as C, Order as O, Product as P, StripeProviderConfig as S, YnsProviderConfig as Y, CartAddParams as a, CartClearParams as b, CartGetParams as c, CartItem as d, CartUpdateParams as e, OrderGetParams as f, OrderListParams as g, OrderListResult as h, ProductBrowseParams as i, ProductBrowseResult as j, ProductGetParams as k, ProductSearchParams as l, ProductSearchResult as m };
153
+ export type { BaseProvider as B, Cart as C, Order as O, Product as P, StripeProviderConfig as S, YnsProduct as Y, CartAddParams as a, CartClearParams as b, CartGetParams as c, CartItem as d, CartRemoveParams as e, CartUpdateParams as f, OrderGetParams as g, OrderListParams as h, OrderListResult as i, ProductBrowseParams as j, ProductBrowseResult as k, ProductGetParams as l, ProductSearchParams as m, ProductSearchResult as n, YnsProviderConfig as o };
package/dist/stripe.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as StripeProviderConfig, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, P as Product, a as CartAddParams, e as CartUpdateParams, b as CartClearParams, c as CartGetParams, C as Cart } from './provider-CvZe8Dqo.js';
1
+ import { S as StripeProviderConfig, j as ProductBrowseParams, k as ProductBrowseResult, l as ProductGetParams, P as Product, a as CartAddParams, C as Cart, f as CartUpdateParams, e as CartRemoveParams, b as CartClearParams, c as CartGetParams } from './provider-nJuubkrT.js';
2
2
 
3
3
  /**
4
4
  * Stripe Commerce client - zero-config constructor
@@ -50,23 +50,21 @@ declare class Commerce {
50
50
  */
51
51
  get cart(): {
52
52
  /**
53
- * Add item to cart
53
+ * Add item to cart (additive behavior)
54
54
  */
55
- add: (params: CartAddParams) => Promise<{
56
- cartId: string;
57
- }>;
55
+ add: (params: CartAddParams) => Promise<Cart>;
58
56
  /**
59
- * Update item in cart
57
+ * Update item in cart (absolute behavior)
60
58
  */
61
- update: (params: CartUpdateParams) => Promise<{
62
- cartId: string;
63
- }>;
59
+ update: (params: CartUpdateParams) => Promise<Cart>;
64
60
  /**
65
- * Clear cart
61
+ * Remove item from cart
66
62
  */
67
- clear: (params: CartClearParams) => Promise<{
68
- cartId: string;
69
- }>;
63
+ remove: (params: CartRemoveParams) => Promise<Cart>;
64
+ /**
65
+ * Clear entire cart
66
+ */
67
+ clear: (params: CartClearParams) => Promise<Cart>;
70
68
  /**
71
69
  * Get cart details
72
70
  */
package/dist/stripe.js CHANGED
@@ -1 +1 @@
1
- var xt=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var wt=(t,e)=>{for(var a in e)xt(t,a,{get:e[a],enumerable:!0})};var Ct,Pt,y,M=P(()=>{"use strict";Ct=process.env.STRIPE_SECRET_KEY,Pt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:Ct,StripeCurrency:Pt}});function _(t,e){if(!t)throw new Error(e)}var q,J,K=P(()=>{"use strict";q=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},J=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}}});var vt,O,W=P(()=>{"use strict";vt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${vt(a)}"`).join(" AND ").trim()});import{z as i}from"zod";function B(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),o=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(o)||n===o?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(o)?-1:n-o})}function $({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:St.parse(a.metadata)}}function _t(t){return!!(t.active&&!t.deleted&&t.default_price)}function N(t){return{...t,data:t.data.filter(_t)}}function L(t){return t.data.map($)}function U(t){return t.filter((e,a,n)=>a===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}function Y(t){let e=t.payment_method;_(typeof e!="string","Payment method should not be a string");let a=t.customer;_(typeof a!="string"&&!a?.deleted,"Customer should not be a string");let n=F.parse(t.metadata),o=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,s])=>{let d=It.safeParse(J(String(s)));return d.success?d.data:null}).filter(Boolean);return{...t,metadata:n,customer:a,payment_method:e,taxBreakdown:o}}var St,X,F,It,H=P(()=>{"use strict";K();W();St=i.object({category:i.string().optional(),order:i.coerce.number().optional(),slug:i.string(),variant:i.string().optional(),stock:i.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:i.string().optional(),preview:i.string().optional()});X=t=>!t.deleted&&t.active,F=i.object({shippingRateId:i.string().optional(),taxCalculationId:i.string().optional(),taxCalculationExp:i.string().optional(),taxId:i.string().optional(),couponCode:i.string().optional(),taxedAmount:i.string().optional(),"billingAddress.city":i.string().optional(),"billingAddress.country":i.string().optional(),"billingAddress.line1":i.string().optional(),"billingAddress.line2":i.string().optional(),"billingAddress.name":i.string().optional(),"billingAddress.postalCode":i.string().optional(),"billingAddress.state":i.string().optional(),netAmount:i.string().optional(),taxBreakdown0:i.string().optional(),taxBreakdown1:i.string().optional(),taxBreakdown2:i.string().optional(),taxBreakdown3:i.string().optional(),taxBreakdown4:i.string().optional(),taxBreakdown5:i.string().optional()}).and(i.record(i.string(),i.string())),It=i.object({taxType:i.string(),taxPercentage:i.string(),taxAmount:i.number()})});var S,Et,Rt,R,m,Z=P(()=>{"use strict";S={DEBUG:0,LOG:1,WARN:2,ERROR:3},Et="LOG",Rt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in S?process.env.LOG_LEVEL:Et,R=S[Rt],m={time(t){R>S.DEBUG||console.time(t)},timeEnd(t){R>S.DEBUG||console.timeEnd(t)},log(...t){R>S.LOG||console.log(...t)},dir(t,e){R>S.LOG||console.dir(t,e)},warn(...t){R>S.WARN||console.warn(...t)},error(...t){R>S.ERROR||console.error(...t)}}});var w,v,tt=P(()=>{"use strict";w=t=>t.filter(Boolean),v={accountGetById:{tags:({accountId:t})=>w(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>w(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>w(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>w(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>w(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>w(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>w(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}}});import et from"stripe";var bt,f,rt=P(()=>{"use strict";M();bt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],f=({tags:t,revalidate:e,cache:a,tagPrefix:n,secretKey:o})=>{let r=o??y.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let s=bt(t,n);return new et(r,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:et.createFetchHttpClient(((l,c)=>fetch(l,{...c,cache:a??c?.cache,next:{tags:s??c?.next?.tags,revalidate:e??c?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var h,at=P(()=>{"use strict";h=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t}});import{revalidateTag as At}from"next/cache";import b from"stripe";import{z as ue}from"zod";function it({productId:t,cartId:e}){return e?j({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):Tt({productId:t})}async function j({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([Q(t),pt(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(o.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(y.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let s=r.cart.metadata??{},c=q(s[t])+(a==="INCREASE"?1:-1);c<=0?s[t]="":s[t]=c.toString();let C=Nt(r)+(o.default_price.unit_amount??0);try{return await qt({paymentIntentId:e,data:{metadata:s,amount:C||ot},clearTaxCalculation:n})}catch(g){m.error(g)}finally{At(`cart-${e}`)}}async function st(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(dt.includes(r.status)){let s=Y(r);if(!s)return null;let d=await z(s.metadata),{metadata:{shippingRateId:l}}=s,c=l&&await V(l);return{cart:s,lines:d.map(({product:C,quantity:g})=>C?{product:C,quantity:g}:null).filter(Boolean),shippingRate:c||null}}}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Tt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await Q(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await o.paymentIntents.create({currency:y.StripeCurrency,amount:r?.default_price.unit_amount||ot,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw m.error(r),r}}async function D(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ct({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),r=await f({secretKey:n,tagPrefix:a,tags:v.productGetBySlug.tags({productSlug: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(s=>!s.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(r.data.map(s=>D(s.id))),B(L(N(r)))}async function ut(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h();if(t.filter?.category){let s=t.filter?.category,l=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({category:s}),cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':s}),expand:["data.default_price"]},{stripeAccount:e});return B(U(L(N(l)))).slice(t.offset||0,t.first)}let r=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return B(U(L(N(r))).filter(X)).slice(t.offset||0,t.first)}async function V(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function z(t){let e=Bt(t);return await Promise.all(e.map(async([n,o])=>({product:await Q(n),quantity:o})))}function Gt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp,10)*1e3:null;if(!r||o>=r)return!0;let s=t.cart.metadata.netAmount||t.cart.amount,d=e.amount,l=Lt.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),c=n.length!==t.lines.length||n.some(u=>{let x=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==x?.product.default_price.unit_amount||u.quantity!==x?.quantity});return d&&s!==d||l||c}async function lt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let r=await o.customers.retrieve(t,{},{stripeAccount:e});return r.deleted?null:r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function Mt(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}async function Kt(){let{stripeAccount:t,storeId:e,secretKey:a}=await h();return await f({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}var ot,Q,dt,Bt,$t,pt,Nt,Lt,kt,nt,qt,mt=P(()=>{"use strict";M();H();Z();tt();rt();W();K();at();ot=1e3;Q=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},dt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Bt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,q(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),$t=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),s=typeof r.customer=="string"?await lt(r.customer):null;if(dt.includes(r.status))return Y({...r,customer:s})}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};pt=async t=>{let e=await $t(t);if(!e)return null;let a=await z(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await V(n);return{cart:e,lines:a.map(({product:r,quantity:s})=>r?{product:r,quantity:s}:null).filter(Boolean),shippingRate:o||null}},Nt=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,Lt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];kt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:s,secretKey:d}=await h(),l=f({secretKey:d,tagPrefix:s,tags:v.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let c=n?await V(n):null,C=typeof c?.tax_code=="string"?c.tax_code:c?.tax_code?.id,g=await Kt(),u=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",x=g.defaults.tax_behavior==="inferred_by_currency"?u:g.defaults.tax_behavior??u;g.defaults.tax_behavior||m.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${u}.`),m.time(`createTaxCalculation ${a}`);let I=await l.tax.calculations.create({expand:["line_items"],line_items:t.map(A=>({...A,tax_behavior:A.tax_behavior??x})),currency:y.StripeCurrency,shipping_cost:c?.active&&c?.fixed_amount?{amount:c.fixed_amount.amount,tax_behavior:c.tax_behavior==="inclusive"?"inclusive":c.tax_behavior==="exclusive"?"exclusive":x,tax_code:C??g.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return m.timeEnd(`createTaxCalculation ${a}`),console.log(JSON.stringify(I).length),I},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};qt=async({paymentIntentId:t,data:e,customerOverride:a,clearTaxCalculation:n})=>{let{stripeAccount:o,storeId:r,secretKey:s}=await h(),d=await pt(t);_(d,`Cart not found: ${t}`);let l=e.amount?e.amount.toString():null,c=F.parse({...d.cart.metadata,...e.metadata});m.time("getProductsFromMetadata");let C=await z(c);m.timeEnd("getProductsFromMetadata");let g=!n&&Gt({oldCart:d,data:e,mergedMetadata:c,lines:C});console.log({shouldRecalculateTax:g});let u=g?await kt({cartId:t,taxId:c.taxId??null,shippingRateId:c.shippingRateId??null,billingAddress:{country:c["billingAddress.country"]??"",city:c["billingAddress.city"]??"",line1:c["billingAddress.line1"]??"",line2:c["billingAddress.line2"]??"",name:c["billingAddress.name"]??"",postalCode:c["billingAddress.postalCode"]??"",state:c["billingAddress.state"]??""},lineItems:C.map(({product:p,quantity:T})=>{if(p?.default_price.unit_amount)return{product:p.id,reference:[p.metadata.slug,p.metadata.variant].filter(Boolean).join("-"),quantity:T,amount:p.default_price.unit_amount*T,tax_behavior:p.default_price.tax_behavior==="exclusive"?"exclusive":p.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:p.tax_code?typeof p.tax_code=="string"?p.tax_code:p.tax_code.id:void 0}}).filter(Boolean)}):null,x=a??(e.customer?await lt(e.customer):d.cart.customer);console.log({customer:x});let I=f({secretKey:s,tagPrefix:r,cache:"no-cache"});m.time(`paymentIntents.update ${t}`);let A=u&&Object.fromEntries(u.tax_breakdown.map(p=>({taxType:p.tax_rate_details.tax_type,taxPercentage:p.tax_rate_details.percentage_decimal,taxAmount:p.amount})).map((p,T)=>[`taxBreakdown${T}`,JSON.stringify(p)])),E=u?u.amount_total:e.amount,k=E&&x?.discount?.coupon.valid?Mt(E,x.discount):E;console.log({"discount.coupon.amount_off":x?.discount?.coupon.amount_off,"discount.coupon.percent_off":x?.discount?.coupon.percent_off,discountedAmount:k,taxedAmount:E,"taxCalculation.amount_total":u?.amount_total,"data.amount":e.amount,netAmount:l});let ht=await I.paymentIntents.update(t,{...e,...k&&{amount:k},metadata:{...c,...l&&{netAmount:l},...E&&{taxedAmount:E},...u?{...nt,...A,taxCalculationId:u.id,taxCalculationExp:u?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return m.timeEnd(`paymentIntents.update ${t}`),ht}});var ft={};wt(ft,{StripeProvider:()=>G,createStripeProvider:()=>Wt});function Wt(t){return new G(t)}var G,gt=P(()=>{"use strict";mt();G=class{constructor(e){this.config=e}mapStripeProduct(e){let a=e.default_price?.unit_amount||0,n=e.default_price?.currency||"usd";return{id:e.id,name:e.name,slug:e.metadata?.slug,summary:e.description,images:e.images||[],active:e.active,price:a/100,currency:n.toUpperCase(),stock:Number.parseInt(e.metadata?.stock||"0",10),stripeId:e.id,metadata:e.metadata||{}}}async productBrowse(e){let a=await ut({first:e.first||10,...e}),n=a.data.map(o=>this.mapStripeProduct(o));return{data:n,meta:{count:a.totalCount||n.length,offset:e.offset||0,limit:e.first||10,hasMore:n.length===(e.first||10)}}}async productGet(e){if(e.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),e.slug){let a=await ct({slug:e.slug});return a?this.mapStripeProduct(a):null}if(e.id){let a=await D(e.id);return a?this.mapStripeProduct(a):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(e){return{cartId:(await it({productId:e.variantId,cartId:e.cartId}))?.id||e.cartId||""}}async cartUpdate(e){let a=e.quantity>0?"INCREASE":"DECREASE";return{cartId:(await j({cartId:e.cartId,productId:e.variantId,operation:a}))?.id||e.cartId}}async cartClear(e){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartGet(e){let a=await st(e.cartId);if(!a)return null;let n=a.lines.map(r=>({id:r.product?.id||"",productId:r.product?.id||"",variantId:r.product?.id,quantity:r.quantity,price:(r.product?.default_price?.unit_amount||0)/100})),o=n.reduce((r,s)=>r+s.price*s.quantity,0);return{id:a.cart.id,customerId:a.cart.customer,items:n,total:o,currency:a.cart.currency?.toUpperCase()||"USD",createdAt:new Date(a.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}}});var yt=class{config;provider;providerPromise;constructor(e){if(this.config=e||this.detectFromEnv(),!this.config.secretKey&&!process.env.STRIPE_SECRET_KEY)throw new Error("Stripe configuration required. Provide secretKey in constructor or set STRIPE_SECRET_KEY environment variable.")}detectFromEnv(){return{secretKey:process.env.STRIPE_SECRET_KEY,tagPrefix:process.env.STRIPE_TAG_PREFIX}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createStripeProvider:e}=await Promise.resolve().then(()=>(gt(),ft));return e(this.config)}catch(e){throw new Error(`Failed to initialize Stripe provider: ${e instanceof Error?e.message:"Unknown error"}`)}}get product(){return{browse:async(e={})=>(await this.getProvider()).productBrowse(e),get:async e=>(await this.getProvider()).productGet(e)}}get cart(){return{add:async e=>(await this.getProvider()).cartAdd(e),update:async e=>(await this.getProvider()).cartUpdate(e),clear:async e=>(await this.getProvider()).cartClear(e),get:async e=>(await this.getProvider()).cartGet(e)}}};export{yt as Commerce};
1
+ var xt=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var wt=(t,e)=>{for(var a in e)xt(t,a,{get:e[a],enumerable:!0})};var Ct,Pt,y,q=P(()=>{"use strict";Ct=process.env.STRIPE_SECRET_KEY,Pt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:Ct,StripeCurrency:Pt}});function _(t,e){if(!t)throw new Error(e)}var M,J,K=P(()=>{"use strict";M=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},J=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}}});var vt,O,W=P(()=>{"use strict";vt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${vt(a)}"`).join(" AND ").trim()});import{z as s}from"zod";function B(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})}function $({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:St.parse(a.metadata)}}function _t(t){return!!(t.active&&!t.deleted&&t.default_price)}function N(t){return{...t,data:t.data.filter(_t)}}function G(t){return t.data.map($)}function F(t){return t.filter((e,a,n)=>a===n.findIndex(i=>i.metadata.slug===e.metadata.slug))}function Y(t){let e=t.payment_method;_(typeof e!="string","Payment method should not be a string");let a=t.customer;_(typeof a!="string"&&!a?.deleted,"Customer should not be a string");let n=U.parse(t.metadata),i=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let d=It.safeParse(J(String(o)));return d.success?d.data:null}).filter(Boolean);return{...t,metadata:n,customer:a,payment_method:e,taxBreakdown:i}}var St,X,U,It,H=P(()=>{"use strict";K();W();St=s.object({category:s.string().optional(),order:s.coerce.number().optional(),slug:s.string(),variant:s.string().optional(),stock:s.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:s.string().optional(),preview:s.string().optional()});X=t=>!t.deleted&&t.active,U=s.object({shippingRateId:s.string().optional(),taxCalculationId:s.string().optional(),taxCalculationExp:s.string().optional(),taxId:s.string().optional(),couponCode:s.string().optional(),taxedAmount:s.string().optional(),"billingAddress.city":s.string().optional(),"billingAddress.country":s.string().optional(),"billingAddress.line1":s.string().optional(),"billingAddress.line2":s.string().optional(),"billingAddress.name":s.string().optional(),"billingAddress.postalCode":s.string().optional(),"billingAddress.state":s.string().optional(),netAmount:s.string().optional(),taxBreakdown0:s.string().optional(),taxBreakdown1:s.string().optional(),taxBreakdown2:s.string().optional(),taxBreakdown3:s.string().optional(),taxBreakdown4:s.string().optional(),taxBreakdown5:s.string().optional()}).and(s.record(s.string(),s.string())),It=s.object({taxType:s.string(),taxPercentage:s.string(),taxAmount:s.number()})});var S,Rt,Et,E,m,Z=P(()=>{"use strict";S={DEBUG:0,LOG:1,WARN:2,ERROR:3},Rt="LOG",Et=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in S?process.env.LOG_LEVEL:Rt,E=S[Et],m={time(t){E>S.DEBUG||console.time(t)},timeEnd(t){E>S.DEBUG||console.timeEnd(t)},log(...t){E>S.LOG||console.log(...t)},dir(t,e){E>S.LOG||console.dir(t,e)},warn(...t){E>S.WARN||console.warn(...t)},error(...t){E>S.ERROR||console.error(...t)}}});var w,v,tt=P(()=>{"use strict";w=t=>t.filter(Boolean),v={accountGetById:{tags:({accountId:t})=>w(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>w(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>w(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>w(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>w(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>w(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>w(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}}});import et from"stripe";var bt,f,rt=P(()=>{"use strict";q();bt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],f=({tags:t,revalidate:e,cache:a,tagPrefix:n,secretKey:i})=>{let r=i??y.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let o=bt(t,n);return new et(r,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:et.createFetchHttpClient(((p,c)=>fetch(p,{...c,cache:a??c?.cache,next:{tags:o??c?.next?.tags,revalidate:e??c?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var h,at=P(()=>{"use strict";h=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t}});import{revalidateTag as At}from"next/cache";import b from"stripe";import{z as ue}from"zod";function ot({productId:t,cartId:e}){return e?j({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):Tt({productId:t})}async function j({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[i,r]=await Promise.all([V(t),pt(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(i.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(y.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let o=r.cart.metadata??{},c=M(o[t])+(a==="INCREASE"?1:-1);c<=0?o[t]="":o[t]=c.toString();let C=Nt(r)+(i.default_price.unit_amount??0);try{return await Mt({paymentIntentId:e,data:{metadata:o,amount:C||it},clearTaxCalculation:n})}catch(g){m.error(g)}finally{At(`cart-${e}`)}}async function st(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(dt.includes(r.status)){let o=Y(r);if(!o)return null;let d=await z(o.metadata),{metadata:{shippingRateId:p}}=o,c=p&&await Q(p);return{cart:o,lines:d.map(({product:C,quantity:g})=>C?{product:C,quantity:g}:null).filter(Boolean),shippingRate:c||null}}}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Tt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await V(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await i.paymentIntents.create({currency:y.StripeCurrency,amount:r?.default_price.unit_amount||it,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw m.error(r),r}}async function D(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ct({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),r=await f({secretKey:n,tagPrefix:a,tags:v.productGetBySlug.tags({productSlug: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(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(r.data.map(o=>D(o.id))),B(G(N(r)))}async function ut(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h();if(t.filter?.category){let o=t.filter?.category,p=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return B(F(G(N(p)))).slice(t.offset||0,t.first)}let r=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return B(F(G(N(r))).filter(X)).slice(t.offset||0,t.first)}async function Q(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,tags:v.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await i.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function z(t){let e=Bt(t);return await Promise.all(e.map(async([n,i])=>({product:await V(n),quantity:i})))}function Lt({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,10)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,d=e.amount,p=Gt.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),c=n.length!==t.lines.length||n.some(u=>{let x=t.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==x?.product.default_price.unit_amount||u.quantity!==x?.quantity});return d&&o!==d||p||c}async function lt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let r=await i.customers.retrieve(t,{},{stripeAccount:e});return r.deleted?null:r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function qt(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}async function Kt(){let{stripeAccount:t,storeId:e,secretKey:a}=await h();return await f({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}var it,V,dt,Bt,$t,pt,Nt,Gt,kt,nt,Mt,mt=P(()=>{"use strict";q();H();Z();tt();rt();W();K();at();it=1e3;V=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},dt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Bt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,M(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),$t=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),o=typeof r.customer=="string"?await lt(r.customer):null;if(dt.includes(r.status))return Y({...r,customer:o})}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};pt=async t=>{let e=await $t(t);if(!e)return null;let a=await z(e.metadata),{metadata:{shippingRateId:n}}=e,i=n&&await Q(n);return{cart:e,lines:a.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||null}},Nt=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,Gt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];kt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:o,secretKey:d}=await h(),p=f({secretKey:d,tagPrefix:o,tags:v.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let c=n?await Q(n):null,C=typeof c?.tax_code=="string"?c.tax_code:c?.tax_code?.id,g=await Kt(),u=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",x=g.defaults.tax_behavior==="inferred_by_currency"?u:g.defaults.tax_behavior??u;g.defaults.tax_behavior||m.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${u}.`),m.time(`createTaxCalculation ${a}`);let I=await p.tax.calculations.create({expand:["line_items"],line_items:t.map(A=>({...A,tax_behavior:A.tax_behavior??x})),currency:y.StripeCurrency,shipping_cost:c?.active&&c?.fixed_amount?{amount:c.fixed_amount.amount,tax_behavior:c.tax_behavior==="inclusive"?"inclusive":c.tax_behavior==="exclusive"?"exclusive":x,tax_code:C??g.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 m.timeEnd(`createTaxCalculation ${a}`),console.log(JSON.stringify(I).length),I},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};Mt=async({paymentIntentId:t,data:e,customerOverride:a,clearTaxCalculation:n})=>{let{stripeAccount:i,storeId:r,secretKey:o}=await h(),d=await pt(t);_(d,`Cart not found: ${t}`);let p=e.amount?e.amount.toString():null,c=U.parse({...d.cart.metadata,...e.metadata});m.time("getProductsFromMetadata");let C=await z(c);m.timeEnd("getProductsFromMetadata");let g=!n&&Lt({oldCart:d,data:e,mergedMetadata:c,lines:C});console.log({shouldRecalculateTax:g});let u=g?await kt({cartId:t,taxId:c.taxId??null,shippingRateId:c.shippingRateId??null,billingAddress:{country:c["billingAddress.country"]??"",city:c["billingAddress.city"]??"",line1:c["billingAddress.line1"]??"",line2:c["billingAddress.line2"]??"",name:c["billingAddress.name"]??"",postalCode:c["billingAddress.postalCode"]??"",state:c["billingAddress.state"]??""},lineItems:C.map(({product:l,quantity:T})=>{if(l?.default_price.unit_amount)return{product:l.id,reference:[l.metadata.slug,l.metadata.variant].filter(Boolean).join("-"),quantity:T,amount:l.default_price.unit_amount*T,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,x=a??(e.customer?await lt(e.customer):d.cart.customer);console.log({customer:x});let I=f({secretKey:o,tagPrefix:r,cache:"no-cache"});m.time(`paymentIntents.update ${t}`);let A=u&&Object.fromEntries(u.tax_breakdown.map(l=>({taxType:l.tax_rate_details.tax_type,taxPercentage:l.tax_rate_details.percentage_decimal,taxAmount:l.amount})).map((l,T)=>[`taxBreakdown${T}`,JSON.stringify(l)])),R=u?u.amount_total:e.amount,k=R&&x?.discount?.coupon.valid?qt(R,x.discount):R;console.log({"discount.coupon.amount_off":x?.discount?.coupon.amount_off,"discount.coupon.percent_off":x?.discount?.coupon.percent_off,discountedAmount:k,taxedAmount:R,"taxCalculation.amount_total":u?.amount_total,"data.amount":e.amount,netAmount:p});let ht=await I.paymentIntents.update(t,{...e,...k&&{amount:k},metadata:{...c,...p&&{netAmount:p},...R&&{taxedAmount:R},...u?{...nt,...A,taxCalculationId:u.id,taxCalculationExp:u?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:i});return m.timeEnd(`paymentIntents.update ${t}`),ht}});var ft={};wt(ft,{StripeProvider:()=>L,createStripeProvider:()=>Wt});function Wt(t){return new L(t)}var L,gt=P(()=>{"use strict";mt();L=class{constructor(e){this.config=e}mapStripeProduct(e){let a=e.default_price?.unit_amount||0,n=e.default_price?.currency||"usd";return{id:e.id,name:e.name,slug:e.metadata?.slug,summary:e.description,images:e.images||[],active:e.active,price:a/100,currency:n.toUpperCase(),stock:Number.parseInt(e.metadata?.stock||"0",10),stripeId:e.id,metadata:e.metadata||{}}}async productBrowse(e){let a=await ut({first:e.first||10,...e}),n=a.data.map(i=>this.mapStripeProduct(i));return{data:n,meta:{count:a.totalCount||n.length,offset:e.offset||0,limit:e.first||10,hasMore:n.length===(e.first||10)}}}async productGet(e){if(e.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),e.slug){let a=await ct({slug:e.slug});return a?this.mapStripeProduct(a):null}if(e.id){let a=await D(e.id);return a?this.mapStripeProduct(a):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(e){let a=e.quantity;if(e.cartId)try{let o=await this.cartGet({cartId:e.cartId});if(o){let d=o.items.find(p=>p.variantId===e.variantId);d&&(a=d.quantity+e.quantity)}}catch{}let i=(await ot({productId:e.variantId,cartId:e.cartId}))?.id||e.cartId||"",r=await this.cartGet({cartId:i});if(!r)throw new Error("Failed to retrieve cart after adding item");return r}async cartUpdate(e){let a=await j({cartId:e.cartId,productId:e.variantId,operation:"SET",quantity:e.quantity}),n=await this.cartGet({cartId:a?.id||e.cartId});if(!n)throw new Error("Failed to retrieve cart after update");return n}async cartClear(e){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartRemove(e){return await this.cartUpdate({cartId:e.cartId,variantId:e.variantId,quantity:0})}async cartGet(e){let a=await st(e.cartId);if(!a)return null;let n=a.lines.map(r=>({id:r.product?.id||"",productId:r.product?.id||"",variantId:r.product?.id,quantity:r.quantity,price:(r.product?.default_price?.unit_amount||0)/100})),i=n.reduce((r,o)=>r+o.price*o.quantity,0);return{id:a.cart.id,customerId:a.cart.customer,items:n,total:i,currency:a.cart.currency?.toUpperCase()||"USD",createdAt:new Date(a.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}}});var yt=class{config;provider;providerPromise;constructor(e){if(this.config=e||this.detectFromEnv(),!this.config.secretKey&&!process.env.STRIPE_SECRET_KEY)throw new Error("Stripe configuration required. Provide secretKey in constructor or set STRIPE_SECRET_KEY environment variable.")}detectFromEnv(){return{secretKey:process.env.STRIPE_SECRET_KEY,tagPrefix:process.env.STRIPE_TAG_PREFIX}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createStripeProvider:e}=await Promise.resolve().then(()=>(gt(),ft));return e(this.config)}catch(e){throw new Error(`Failed to initialize Stripe provider: ${e instanceof Error?e.message:"Unknown error"}`)}}get product(){return{browse:async(e={})=>(await this.getProvider()).productBrowse(e),get:async e=>(await this.getProvider()).productGet(e)}}get cart(){return{add:async e=>(await this.getProvider()).cartAdd(e),update:async e=>(await this.getProvider()).cartUpdate(e),remove:async e=>(await this.getProvider()).cartRemove(e),clear:async e=>(await this.getProvider()).cartClear(e),get:async e=>(await this.getProvider()).cartGet(e)}}};export{yt as Commerce};
package/dist/yns.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Y as YnsProviderConfig, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, P as Product, l as ProductSearchParams, m as ProductSearchResult, a as CartAddParams, e as CartUpdateParams, b as CartClearParams, c as CartGetParams, C as Cart, f as OrderGetParams, O as Order, g as OrderListParams, h as OrderListResult } from './provider-CvZe8Dqo.js';
1
+ import { o as YnsProviderConfig, j as ProductBrowseParams, k as ProductBrowseResult, l as ProductGetParams, P as Product, m as ProductSearchParams, n as ProductSearchResult, a as CartAddParams, C as Cart, f as CartUpdateParams, e as CartRemoveParams, b as CartClearParams, c as CartGetParams, g as OrderGetParams, O as Order, h as OrderListParams, i as OrderListResult } from './provider-nJuubkrT.js';
2
2
 
3
3
  /**
4
4
  * YNS Commerce client - zero-config constructor with GraphQL support
@@ -55,27 +55,29 @@ declare class Commerce {
55
55
  search: (params: ProductSearchParams) => Promise<ProductSearchResult>;
56
56
  };
57
57
  /**
58
- * Cart operations - YNS specific
58
+ * Cart operations - Simplified API
59
59
  */
60
60
  get cart(): {
61
61
  /**
62
- * Add item to cart
62
+ * Add items to cart (additive behavior)
63
+ * If cartId is provided, adds to existing quantity
64
+ * If no cartId, creates new cart
63
65
  */
64
- add: (params: CartAddParams) => Promise<{
65
- cartId: string;
66
- }>;
66
+ add: (params: CartAddParams) => Promise<Cart>;
67
67
  /**
68
- * Update item in cart
68
+ * Update item in cart (absolute behavior)
69
+ * Sets quantity to exact number
70
+ * Requires cartId
69
71
  */
70
- update: (params: CartUpdateParams) => Promise<{
71
- cartId: string;
72
- }>;
72
+ update: (params: CartUpdateParams) => Promise<Cart>;
73
73
  /**
74
- * Clear cart
74
+ * Remove specific item from cart
75
75
  */
76
- clear: (params: CartClearParams) => Promise<{
77
- cartId: string;
78
- }>;
76
+ remove: (params: CartRemoveParams) => Promise<Cart>;
77
+ /**
78
+ * Clear entire cart
79
+ */
80
+ clear: (params: CartClearParams) => Promise<Cart>;
79
81
  /**
80
82
  * Get cart details
81
83
  */
package/dist/yns.js CHANGED
@@ -1,238 +1 @@
1
- var h=Object.defineProperty;var c=(i,r)=>()=>(i&&(r=i(i=0)),r);var f=(i,r)=>{for(var t in r)h(i,t,{get:r[t],enumerable:!0})};function l(i){return!i||i.length===0?d:`
2
- query ProductQuery($slug: String!) {
3
- product(slug: $slug) {
4
- ${i.join(`
5
- `)}
6
- }
7
- }
8
- `}function P(i){return!i||i.length===0?n:`
9
- query ProductsQuery(
10
- $offset: Int
11
- $limit: Int
12
- $category: String
13
- $query: String
14
- $active: Boolean
15
- $excludeBundles: Boolean
16
- $orderBy: String
17
- $orderDirection: String
18
- ) {
19
- products(
20
- offset: $offset
21
- limit: $limit
22
- category: $category
23
- query: $query
24
- active: $active
25
- excludeBundles: $excludeBundles
26
- orderBy: $orderBy
27
- orderDirection: $orderDirection
28
- ) {
29
- data {
30
- ${i.join(`
31
- `)}
32
- }
33
- meta {
34
- count
35
- offset
36
- limit
37
- hasMore
38
- }
39
- }
40
- }
41
- `}var u,n,d,$,p,g=c(()=>{"use strict";u=`
42
- fragment ProductFragment on Product {
43
- id
44
- name
45
- slug
46
- summary
47
- images
48
- active
49
- type
50
- createdAt
51
- updatedAt
52
- category {
53
- id
54
- name
55
- slug
56
- description
57
- image
58
- }
59
- variants {
60
- id
61
- price
62
- originalPrice
63
- prePromotionPrice
64
- stock
65
- shippable
66
- attributes
67
- combinations {
68
- id
69
- variantValue {
70
- id
71
- value
72
- colorValue
73
- variantType {
74
- id
75
- label
76
- type
77
- }
78
- }
79
- }
80
- }
81
- collections {
82
- id
83
- name
84
- slug
85
- description
86
- image
87
- active
88
- }
89
- bundleProducts {
90
- id
91
- quantity
92
- position
93
- variant {
94
- id
95
- price
96
- originalPrice
97
- stock
98
- }
99
- }
100
- bundleDiscountPercentage
101
- }
102
- `,n=`
103
- query ProductsQuery(
104
- $offset: Int
105
- $limit: Int
106
- $category: String
107
- $query: String
108
- $active: Boolean
109
- $excludeBundles: Boolean
110
- $orderBy: String
111
- $orderDirection: String
112
- ) {
113
- products(
114
- offset: $offset
115
- limit: $limit
116
- category: $category
117
- query: $query
118
- active: $active
119
- excludeBundles: $excludeBundles
120
- orderBy: $orderBy
121
- orderDirection: $orderDirection
122
- ) {
123
- data {
124
- ...ProductFragment
125
- }
126
- meta {
127
- count
128
- offset
129
- limit
130
- hasMore
131
- }
132
- }
133
- }
134
- ${u}
135
- `,d=`
136
- query ProductQuery($slug: String!) {
137
- product(slug: $slug) {
138
- ...ProductFragment
139
- }
140
- }
141
- ${u}
142
- `,$=`
143
- fragment CartFragment on Cart {
144
- id
145
- customerId
146
- storeId
147
- shippingId
148
- couponId
149
- billingAddressId
150
- shippingAddressId
151
- stripePaymentIntentId
152
- checkoutSessionId
153
- addonData
154
- createdAt
155
- updatedAt
156
- customer {
157
- id
158
- email
159
- userId
160
- user {
161
- id
162
- email
163
- name
164
- }
165
- }
166
- coupon {
167
- code
168
- type
169
- value
170
- startDate
171
- endDate
172
- }
173
- lineItems {
174
- id
175
- cartId
176
- productVariantId
177
- subscriptionId
178
- quantity
179
- createdAt
180
- updatedAt
181
- productVariant {
182
- id
183
- price
184
- originalPrice
185
- stock
186
- shippable
187
- attributes
188
- }
189
- subscription {
190
- id
191
- name
192
- price
193
- interval
194
- intervalCount
195
- }
196
- }
197
- billingAddress {
198
- id
199
- name
200
- company
201
- line1
202
- line2
203
- city
204
- state
205
- postalCode
206
- country
207
- phone
208
- type
209
- }
210
- shippingAddress {
211
- id
212
- name
213
- company
214
- line1
215
- line2
216
- city
217
- state
218
- postalCode
219
- country
220
- phone
221
- type
222
- }
223
- shipping {
224
- id
225
- name
226
- price
227
- minValue
228
- maxValue
229
- }
230
- }
231
- `,p=`
232
- query CartQuery($id: String!) {
233
- cart(id: $id) {
234
- ...CartFragment
235
- }
236
- }
237
- ${$}
238
- `});var m={};f(m,{YnsProvider:()=>s,createYnsProvider:()=>w});function w(i){return new s(i)}var s,v=c(()=>{"use strict";g();s=class{config;constructor(r){this.config=r}async graphqlRequest(r,t){let o=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:r,variables:t})});if(!o.ok)throw new Error(`YNS GraphQL request failed: ${o.status} ${o.statusText}`);let e=await o.json();if(e.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(e.errors)}`);return e.data}async restRequest(r,t="GET",o){let e=await fetch(`${this.config.endpoint}/api${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:o?JSON.stringify(o):void 0});if(!e.ok)throw new Error(`YNS REST request failed: ${e.status} ${e.statusText}`);return e.json()}mapYnsProduct(r){return{id:r.id,name:r.name,slug:r.slug,summary:r.summary,images:r.images||[],active:r.active,price:r.variants?.[0]?.price?Number.parseFloat(r.variants[0].price):0,currency:"USD",stock:r.variants?.[0]?.stock,category:r.category,variants:r.variants?.map(t=>({id:t.id,price:Number.parseFloat(t.price),stock:t.stock,attributes:t.attributes}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(e=>({id:e.id,productId:e.productVariant?.id||"",variantId:e.productVariantId,quantity:e.quantity,price:Number.parseFloat(e.productVariant?.price||"0")}))||[],o=t.reduce((e,a)=>e+a.price*a.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:o,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}async productBrowse(r){let t=r.fields?P(r.fields):n,o={offset:r.offset||0,limit:r.first||r.offset||10,category:r.category,query:r.query,active:r.active,excludeBundles:!1,orderBy:r.orderBy,orderDirection:r.orderDirection},e=await this.graphqlRequest(t,o);return{data:e.products.data.map(a=>this.mapYnsProduct(a)),meta:e.products.meta}}async productGet(r){if(!r.slug&&!r.id)throw new Error("Either slug or id is required for productGet");let t=r.fields?l(r.fields):d,o={slug:r.slug},e=await this.graphqlRequest(t,o);return e.product?this.mapYnsProduct(e.product):null}async cartAdd(r){let t={variantId:r.variantId,cartId:r.cartId,subscriptionId:r.subscriptionId};return await this.restRequest("/cart","POST",t)}async cartUpdate(r){let t={variantId:r.variantId,quantity:r.quantity};return await this.restRequest(`/cart/${r.cartId}`,"PUT",t)}async cartClear(r){return await this.restRequest(`/cart/${r.cartId}`,"DELETE")}async cartGet(r){let t=await this.graphqlRequest(p,{id:r.cartId});return t.cart?this.mapYnsCart(t.cart):null}}});var y=class{config;provider;providerPromise;constructor(r){if(this.config=r||this.detectFromEnv(),!this.config.endpoint||!this.config.token)throw new Error("YNS configuration required. Provide endpoint and token in constructor or set YNS_ENDPOINT and YNS_TOKEN environment variables.")}detectFromEnv(){return{endpoint:process.env.YNS_ENDPOINT||"",token:process.env.YNS_TOKEN||""}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createYnsProvider:r}=await Promise.resolve().then(()=>(v(),m));return r(this.config)}catch(r){throw new Error(`Failed to initialize YNS provider: ${r instanceof Error?r.message:"Unknown error"}`)}}get product(){return{browse:async(r={})=>(await this.getProvider()).productBrowse(r),get:async r=>(await this.getProvider()).productGet(r),search:async r=>{let t=await this.getProvider();if(!t.productSearch)throw new Error("Product search is not supported by YNS provider");return t.productSearch(r)}}}get cart(){return{add:async r=>(await this.getProvider()).cartAdd(r),update:async r=>(await this.getProvider()).cartUpdate(r),clear:async r=>(await this.getProvider()).cartClear(r),get:async r=>(await this.getProvider()).cartGet(r)}}get order(){return{get:async r=>{let t=await this.getProvider();if(!t.orderGet)throw new Error("Order retrieval is not supported by YNS provider");return t.orderGet(r)},list:async(r={})=>{let t=await this.getProvider();if(!t.orderList)throw new Error("Order listing is not supported by YNS provider");return t.orderList(r)}}}};export{y as Commerce};
1
+ var v=Object.defineProperty;var l=(a,r)=>()=>(a&&(r=a(a=0)),r);var h=(a,r)=>{for(var t in r)v(a,t,{get:r[t],enumerable:!0})};var u={};h(u,{YnsProvider:()=>d,createYnsProvider:()=>g});function g(a){return new d(a)}var d,p=l(()=>{"use strict";d=class{config;constructor(r){this.config=r}async graphqlRequest(r,t){let e=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:r,variables:t})});if(!e.ok)throw new Error(`YNS GraphQL request failed: ${e.status} ${e.statusText}`);let i=await e.json();if(i.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(i.errors)}`);return i.data}async restRequest(r,t="GET",e){let i=await fetch(`${this.config.endpoint}/api${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:e?JSON.stringify(e):void 0});if(!i.ok){let n=i.headers.get("content-type"),s=`YNS REST request failed: ${i.status} ${i.statusText}`;if(n?.includes("application/json"))try{let c=await i.json();s=c.error||c.message||s}catch{}throw new Error(s)}let o=i.headers.get("content-type");if(!o?.includes("application/json"))throw new Error(`YNS API returned ${o} instead of JSON for ${r}`);return i.json()}mapYnsProduct(r){return{id:r.id,name:r.name,slug:r.slug,summary:r.summary,images:r.images||[],active:r.active,price:r.variants?.[0]?.price?Number.parseFloat(r.variants[0].price):0,currency:"USD",stock:r.variants?.[0]?.stock,category:r.category,variants:r.variants?.map(t=>({id:t.id,price:Number.parseFloat(t.price),stock:t.stock,attributes:t.attributes}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(i=>({id:i.id,productId:i.productVariant?.id||"",variantId:i.productVariantId,quantity:i.quantity,price:Number.parseFloat(i.productVariant?.price||"0")}))||[],e=t.reduce((i,o)=>i+o.price*o.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:e,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}async productBrowse(r){if(r.graphql){let t={offset:r.offset||0,limit:r.first||10,category:r.category,query:r.query,active:r.active,orderBy:r.orderBy,orderDirection:r.orderDirection},e=await this.graphqlRequest(r.graphql,t);return{data:e.products.data.map(i=>this.mapYnsProduct(i)),meta:e.products.meta}}else{let t=new URLSearchParams;r.first&&t.append("limit",r.first.toString()),r.offset&&t.append("offset",r.offset.toString()),r.category&&t.append("category",r.category),r.query&&t.append("q",r.query),r.active!==void 0&&t.append("active",r.active.toString()),r.orderBy&&t.append("orderBy",r.orderBy),r.orderDirection&&t.append("orderDirection",r.orderDirection);let e=`/products${t.toString()?`?${t.toString()}`:""}`,i=await this.restRequest(e);return{data:i.data.map(o=>this.mapYnsProduct(o)),meta:i.meta}}}async productGet(r){if(!r.slug&&!r.id)throw new Error("Either slug or id is required for productGet");if(r.graphql){let t={slug:r.slug,id:r.id},e=await this.graphqlRequest(r.graphql,t);return e.product?this.mapYnsProduct(e.product):null}else{let t=`/products/${r.id||r.slug}`,e=await this.restRequest(t);return e?this.mapYnsProduct(e):null}}async cartAdd(r){let t=r.quantity;if(r.cartId)try{let o=await this.cartGet({cartId:r.cartId});if(o){let n=o.items.find(s=>s.variantId===r.variantId);n&&(t=n.quantity+r.quantity)}}catch{}let e={variantId:r.variantId,cartId:r.cartId,quantity:t,subscriptionId:r.subscriptionId},i=await this.restRequest("/cart","POST",e);return this.mapYnsCart(i)}async cartUpdate(r){let t={variantId:r.variantId,cartId:r.cartId,quantity:r.quantity},e=await this.restRequest("/cart","POST",t);return this.mapYnsCart(e)}async cartRemove(r){let t=`/cart/${r.cartId}/items/${r.variantId}`,e=await this.restRequest(t,"DELETE");return this.mapYnsCart(e)}async cartClear(r){let t=await this.restRequest(`/cart/${r.cartId}`,"DELETE");return this.mapYnsCart(t)}async cartGet(r){let t=await this.restRequest(`/cart/${r.cartId}`);return t?this.mapYnsCart(t):null}}});var P=class{config;provider;providerPromise;constructor(r){if(this.config=r||this.detectFromEnv(),!this.config.endpoint||!this.config.token)throw new Error("YNS configuration required. Provide endpoint and token in constructor or set YNS_ENDPOINT and YNS_TOKEN environment variables.")}detectFromEnv(){return{endpoint:process.env.YNS_ENDPOINT||"",token:process.env.YNS_TOKEN||""}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createYnsProvider:r}=await Promise.resolve().then(()=>(p(),u));return r(this.config)}catch(r){throw new Error(`Failed to initialize YNS provider: ${r instanceof Error?r.message:"Unknown error"}`)}}get product(){return{browse:async(r={})=>(await this.getProvider()).productBrowse(r),get:async r=>(await this.getProvider()).productGet(r),search:async r=>{let t=await this.getProvider();if(!t.productSearch)throw new Error("Product search is not supported by YNS provider");return t.productSearch(r)}}}get cart(){return{add:async r=>(await this.getProvider()).cartAdd(r),update:async r=>(await this.getProvider()).cartUpdate(r),remove:async r=>(await this.getProvider()).cartRemove(r),clear:async r=>(await this.getProvider()).cartClear(r),get:async r=>(await this.getProvider()).cartGet(r)}}get order(){return{get:async r=>{let t=await this.getProvider();if(!t.orderGet)throw new Error("Order retrieval is not supported by YNS provider");return t.orderGet(r)},list:async(r={})=>{let t=await this.getProvider();if(!t.orderList)throw new Error("Order listing is not supported by YNS provider");return t.orderList(r)}}}};export{P as Commerce};
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.2.0",
4
+ "version": "0.4.0",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [