commerce-kit 0.6.1-experimental.8 → 0.7.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/LICENSE.md +650 -0
- package/README.md +234 -0
- package/dist/currencies.d.ts +11 -0
- package/dist/currencies.js +1 -0
- package/dist/index.d.ts +6 -26
- package/dist/index.js +1 -2
- package/dist/internal.d.ts +383 -0
- package/dist/internal.js +1 -0
- package/dist/provider-CeP9uHnB.d.ts +166 -0
- package/dist/stripe.d.ts +75 -0
- package/dist/stripe.js +1 -0
- package/dist/yns-context.d.ts +22 -0
- package/dist/yns-context.js +1 -0
- package/dist/yns.d.ts +101 -0
- package/dist/yns.js +1 -0
- package/package.json +44 -22
- package/dist/api-types.d.ts +0 -4955
- package/dist/api-types.js +0 -2
- package/dist/api-types.js.map +0 -1
- package/dist/chunk-PNKB6P4V.js +0 -1
- package/dist/chunk-PNKB6P4V.js.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import Stripe from 'stripe';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
declare const sanitizeQueryValue: (slug: string | number | boolean) => string;
|
|
5
|
+
declare const objectToStripeQuery: (obj: Record<string, string | number | boolean>) => string;
|
|
6
|
+
|
|
7
|
+
type MappedProduct = ReturnType<typeof mapProduct>;
|
|
8
|
+
/**
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
declare function sortProducts(products: MappedProduct[]): {
|
|
12
|
+
default_price: Stripe.Price;
|
|
13
|
+
marketing_features: (string | undefined)[];
|
|
14
|
+
metadata: {
|
|
15
|
+
slug: string;
|
|
16
|
+
stock: number;
|
|
17
|
+
category?: string | undefined;
|
|
18
|
+
order?: number | undefined;
|
|
19
|
+
variant?: string | undefined;
|
|
20
|
+
digitalAsset?: string | undefined;
|
|
21
|
+
preview?: string | undefined;
|
|
22
|
+
};
|
|
23
|
+
id: string;
|
|
24
|
+
object: "product";
|
|
25
|
+
active: boolean;
|
|
26
|
+
created: number;
|
|
27
|
+
deleted?: void | undefined;
|
|
28
|
+
description: string | null;
|
|
29
|
+
images: Array<string>;
|
|
30
|
+
livemode: boolean;
|
|
31
|
+
name: string;
|
|
32
|
+
package_dimensions: Stripe.Product.PackageDimensions | null;
|
|
33
|
+
shippable: boolean | null;
|
|
34
|
+
statement_descriptor?: string | null;
|
|
35
|
+
tax_code: string | Stripe.TaxCode | null;
|
|
36
|
+
type: Stripe.Product.Type;
|
|
37
|
+
unit_label?: string | null;
|
|
38
|
+
updated: number;
|
|
39
|
+
url: string | null;
|
|
40
|
+
}[];
|
|
41
|
+
declare const ProductMetadataSchema: z.ZodObject<{
|
|
42
|
+
category: z.ZodOptional<z.ZodString>;
|
|
43
|
+
order: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
44
|
+
slug: z.ZodString;
|
|
45
|
+
variant: z.ZodOptional<z.ZodString>;
|
|
46
|
+
stock: z.ZodPipe<z.ZodOptional<z.ZodCoercedNumber<unknown>>, z.ZodTransform<number, number | undefined>>;
|
|
47
|
+
digitalAsset: z.ZodOptional<z.ZodString>;
|
|
48
|
+
preview: z.ZodOptional<z.ZodString>;
|
|
49
|
+
}, z.core.$strip>;
|
|
50
|
+
type ProductMetadata = z.infer<typeof ProductMetadataSchema>;
|
|
51
|
+
/**
|
|
52
|
+
* @internal
|
|
53
|
+
*/
|
|
54
|
+
declare function mapProduct({ default_price, marketing_features, ...product }: Stripe.Product): {
|
|
55
|
+
default_price: Stripe.Price;
|
|
56
|
+
marketing_features: (string | undefined)[];
|
|
57
|
+
metadata: {
|
|
58
|
+
slug: string;
|
|
59
|
+
stock: number;
|
|
60
|
+
category?: string | undefined;
|
|
61
|
+
order?: number | undefined;
|
|
62
|
+
variant?: string | undefined;
|
|
63
|
+
digitalAsset?: string | undefined;
|
|
64
|
+
preview?: string | undefined;
|
|
65
|
+
};
|
|
66
|
+
id: string;
|
|
67
|
+
object: "product";
|
|
68
|
+
active: boolean;
|
|
69
|
+
created: number;
|
|
70
|
+
deleted?: void | undefined;
|
|
71
|
+
description: string | null;
|
|
72
|
+
images: Array<string>;
|
|
73
|
+
livemode: boolean;
|
|
74
|
+
name: string;
|
|
75
|
+
package_dimensions: Stripe.Product.PackageDimensions | null;
|
|
76
|
+
shippable: boolean | null;
|
|
77
|
+
statement_descriptor?: string | null;
|
|
78
|
+
tax_code: string | Stripe.TaxCode | null;
|
|
79
|
+
type: Stripe.Product.Type;
|
|
80
|
+
unit_label?: string | null;
|
|
81
|
+
updated: number;
|
|
82
|
+
url: string | null;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* @internal
|
|
86
|
+
*/
|
|
87
|
+
declare function filterValidProduct(product: Stripe.Product): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* @internal
|
|
90
|
+
*/
|
|
91
|
+
declare function filterValidProducts(products: Stripe.Response<Stripe.ApiSearchResult<Stripe.Product> | Stripe.ApiList<Stripe.Product>>): {
|
|
92
|
+
data: Stripe.Product[];
|
|
93
|
+
object: "search_result";
|
|
94
|
+
has_more: boolean;
|
|
95
|
+
url: string;
|
|
96
|
+
next_page: string | null;
|
|
97
|
+
total_count?: number;
|
|
98
|
+
lastResponse: {
|
|
99
|
+
headers: {
|
|
100
|
+
[key: string]: string;
|
|
101
|
+
};
|
|
102
|
+
requestId: string;
|
|
103
|
+
statusCode: number;
|
|
104
|
+
apiVersion?: string;
|
|
105
|
+
idempotencyKey?: string;
|
|
106
|
+
stripeAccount?: string;
|
|
107
|
+
};
|
|
108
|
+
} | {
|
|
109
|
+
data: Stripe.Product[];
|
|
110
|
+
object: "list";
|
|
111
|
+
has_more: boolean;
|
|
112
|
+
url: string;
|
|
113
|
+
lastResponse: {
|
|
114
|
+
headers: {
|
|
115
|
+
[key: string]: string;
|
|
116
|
+
};
|
|
117
|
+
requestId: string;
|
|
118
|
+
statusCode: number;
|
|
119
|
+
apiVersion?: string;
|
|
120
|
+
idempotencyKey?: string;
|
|
121
|
+
stripeAccount?: string;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* @internal
|
|
126
|
+
*/
|
|
127
|
+
declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<Stripe.Product> | Stripe.ApiList<Stripe.Product>>): {
|
|
128
|
+
default_price: Stripe.Price;
|
|
129
|
+
marketing_features: (string | undefined)[];
|
|
130
|
+
metadata: {
|
|
131
|
+
slug: string;
|
|
132
|
+
stock: number;
|
|
133
|
+
category?: string | undefined;
|
|
134
|
+
order?: number | undefined;
|
|
135
|
+
variant?: string | undefined;
|
|
136
|
+
digitalAsset?: string | undefined;
|
|
137
|
+
preview?: string | undefined;
|
|
138
|
+
};
|
|
139
|
+
id: string;
|
|
140
|
+
object: "product";
|
|
141
|
+
active: boolean;
|
|
142
|
+
created: number;
|
|
143
|
+
deleted?: void | undefined;
|
|
144
|
+
description: string | null;
|
|
145
|
+
images: Array<string>;
|
|
146
|
+
livemode: boolean;
|
|
147
|
+
name: string;
|
|
148
|
+
package_dimensions: Stripe.Product.PackageDimensions | null;
|
|
149
|
+
shippable: boolean | null;
|
|
150
|
+
statement_descriptor?: string | null;
|
|
151
|
+
tax_code: string | Stripe.TaxCode | null;
|
|
152
|
+
type: Stripe.Product.Type;
|
|
153
|
+
unit_label?: string | null;
|
|
154
|
+
updated: number;
|
|
155
|
+
url: string | null;
|
|
156
|
+
}[];
|
|
157
|
+
/**
|
|
158
|
+
* @internal
|
|
159
|
+
*/
|
|
160
|
+
declare function mapShippingRate(shippingRate: Stripe.ShippingRate): Stripe.ShippingRate;
|
|
161
|
+
type MappedShippingRate = ReturnType<typeof mapShippingRate>;
|
|
162
|
+
/**
|
|
163
|
+
* @internal
|
|
164
|
+
*/
|
|
165
|
+
declare function mapShippingRates(shippingRates: Stripe.ApiList<Stripe.ShippingRate>): Stripe.ShippingRate[];
|
|
166
|
+
/**
|
|
167
|
+
* @internal
|
|
168
|
+
*/
|
|
169
|
+
declare function getUniqueVariants(products: MappedProduct[]): {
|
|
170
|
+
default_price: Stripe.Price;
|
|
171
|
+
marketing_features: (string | undefined)[];
|
|
172
|
+
metadata: {
|
|
173
|
+
slug: string;
|
|
174
|
+
stock: number;
|
|
175
|
+
category?: string | undefined;
|
|
176
|
+
order?: number | undefined;
|
|
177
|
+
variant?: string | undefined;
|
|
178
|
+
digitalAsset?: string | undefined;
|
|
179
|
+
preview?: string | undefined;
|
|
180
|
+
};
|
|
181
|
+
id: string;
|
|
182
|
+
object: "product";
|
|
183
|
+
active: boolean;
|
|
184
|
+
created: number;
|
|
185
|
+
deleted?: void | undefined;
|
|
186
|
+
description: string | null;
|
|
187
|
+
images: Array<string>;
|
|
188
|
+
livemode: boolean;
|
|
189
|
+
name: string;
|
|
190
|
+
package_dimensions: Stripe.Product.PackageDimensions | null;
|
|
191
|
+
shippable: boolean | null;
|
|
192
|
+
statement_descriptor?: string | null;
|
|
193
|
+
tax_code: string | Stripe.TaxCode | null;
|
|
194
|
+
type: Stripe.Product.Type;
|
|
195
|
+
unit_label?: string | null;
|
|
196
|
+
updated: number;
|
|
197
|
+
url: string | null;
|
|
198
|
+
}[];
|
|
199
|
+
/**
|
|
200
|
+
* @internal
|
|
201
|
+
*/
|
|
202
|
+
declare const isProductAvailable: (product: MappedProduct) => boolean;
|
|
203
|
+
/**
|
|
204
|
+
* @internal
|
|
205
|
+
*/
|
|
206
|
+
declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
|
|
207
|
+
shippingRateId: z.ZodOptional<z.ZodString>;
|
|
208
|
+
taxCalculationId: z.ZodOptional<z.ZodString>;
|
|
209
|
+
taxCalculationExp: z.ZodOptional<z.ZodString>;
|
|
210
|
+
taxId: z.ZodOptional<z.ZodString>;
|
|
211
|
+
couponCode: z.ZodOptional<z.ZodString>;
|
|
212
|
+
taxedAmount: z.ZodOptional<z.ZodString>;
|
|
213
|
+
"billingAddress.city": z.ZodOptional<z.ZodString>;
|
|
214
|
+
"billingAddress.country": z.ZodOptional<z.ZodString>;
|
|
215
|
+
"billingAddress.line1": z.ZodOptional<z.ZodString>;
|
|
216
|
+
"billingAddress.line2": z.ZodOptional<z.ZodString>;
|
|
217
|
+
"billingAddress.name": z.ZodOptional<z.ZodString>;
|
|
218
|
+
"billingAddress.postalCode": z.ZodOptional<z.ZodString>;
|
|
219
|
+
"billingAddress.state": z.ZodOptional<z.ZodString>;
|
|
220
|
+
netAmount: z.ZodOptional<z.ZodString>;
|
|
221
|
+
taxBreakdown0: z.ZodOptional<z.ZodString>;
|
|
222
|
+
taxBreakdown1: z.ZodOptional<z.ZodString>;
|
|
223
|
+
taxBreakdown2: z.ZodOptional<z.ZodString>;
|
|
224
|
+
taxBreakdown3: z.ZodOptional<z.ZodString>;
|
|
225
|
+
taxBreakdown4: z.ZodOptional<z.ZodString>;
|
|
226
|
+
taxBreakdown5: z.ZodOptional<z.ZodString>;
|
|
227
|
+
}, z.core.$strip>, z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
228
|
+
type CartMetadata = z.infer<typeof cartMetadataSchema>;
|
|
229
|
+
/**
|
|
230
|
+
* @internal
|
|
231
|
+
*/
|
|
232
|
+
declare const cartMetadataTaxBreakdownSchema: z.ZodObject<{
|
|
233
|
+
taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
|
|
234
|
+
taxPercentage: z.ZodString;
|
|
235
|
+
taxAmount: z.ZodNumber;
|
|
236
|
+
}, z.core.$strip>;
|
|
237
|
+
/**
|
|
238
|
+
* @internal
|
|
239
|
+
*/
|
|
240
|
+
declare function mapCart(cart: Stripe.PaymentIntent): {
|
|
241
|
+
metadata: {
|
|
242
|
+
shippingRateId?: string | undefined;
|
|
243
|
+
taxCalculationId?: string | undefined;
|
|
244
|
+
taxCalculationExp?: string | undefined;
|
|
245
|
+
taxId?: string | undefined;
|
|
246
|
+
couponCode?: string | undefined;
|
|
247
|
+
taxedAmount?: string | undefined;
|
|
248
|
+
"billingAddress.city"?: string | undefined;
|
|
249
|
+
"billingAddress.country"?: string | undefined;
|
|
250
|
+
"billingAddress.line1"?: string | undefined;
|
|
251
|
+
"billingAddress.line2"?: string | undefined;
|
|
252
|
+
"billingAddress.name"?: string | undefined;
|
|
253
|
+
"billingAddress.postalCode"?: string | undefined;
|
|
254
|
+
"billingAddress.state"?: string | undefined;
|
|
255
|
+
netAmount?: string | undefined;
|
|
256
|
+
taxBreakdown0?: string | undefined;
|
|
257
|
+
taxBreakdown1?: string | undefined;
|
|
258
|
+
taxBreakdown2?: string | undefined;
|
|
259
|
+
taxBreakdown3?: string | undefined;
|
|
260
|
+
taxBreakdown4?: string | undefined;
|
|
261
|
+
taxBreakdown5?: string | undefined;
|
|
262
|
+
} & Record<string, string>;
|
|
263
|
+
customer: Stripe.Customer | null;
|
|
264
|
+
payment_method: Stripe.PaymentMethod | null;
|
|
265
|
+
taxBreakdown: ({
|
|
266
|
+
taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
|
|
267
|
+
taxPercentage: string;
|
|
268
|
+
taxAmount: number;
|
|
269
|
+
} | null)[];
|
|
270
|
+
id: string;
|
|
271
|
+
object: "payment_intent";
|
|
272
|
+
amount: number;
|
|
273
|
+
amount_capturable: number;
|
|
274
|
+
amount_details?: Stripe.PaymentIntent.AmountDetails;
|
|
275
|
+
amount_received: number;
|
|
276
|
+
application: string | Stripe.Application | null;
|
|
277
|
+
application_fee_amount: number | null;
|
|
278
|
+
automatic_payment_methods: Stripe.PaymentIntent.AutomaticPaymentMethods | null;
|
|
279
|
+
canceled_at: number | null;
|
|
280
|
+
cancellation_reason: Stripe.PaymentIntent.CancellationReason | null;
|
|
281
|
+
capture_method: Stripe.PaymentIntent.CaptureMethod;
|
|
282
|
+
client_secret: string | null;
|
|
283
|
+
confirmation_method: Stripe.PaymentIntent.ConfirmationMethod;
|
|
284
|
+
created: number;
|
|
285
|
+
currency: string;
|
|
286
|
+
description: string | null;
|
|
287
|
+
excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
|
|
288
|
+
last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
|
|
289
|
+
latest_charge: string | Stripe.Charge | null;
|
|
290
|
+
livemode: boolean;
|
|
291
|
+
next_action: Stripe.PaymentIntent.NextAction | null;
|
|
292
|
+
on_behalf_of: string | Stripe.Account | null;
|
|
293
|
+
payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
|
|
294
|
+
payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
|
|
295
|
+
payment_method_types: Array<string>;
|
|
296
|
+
presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
|
|
297
|
+
processing: Stripe.PaymentIntent.Processing | null;
|
|
298
|
+
receipt_email: string | null;
|
|
299
|
+
review: string | Stripe.Review | null;
|
|
300
|
+
setup_future_usage: Stripe.PaymentIntent.SetupFutureUsage | null;
|
|
301
|
+
shipping: Stripe.PaymentIntent.Shipping | null;
|
|
302
|
+
source: string | Stripe.CustomerSource | Stripe.DeletedCustomerSource | null;
|
|
303
|
+
statement_descriptor: string | null;
|
|
304
|
+
statement_descriptor_suffix: string | null;
|
|
305
|
+
status: Stripe.PaymentIntent.Status;
|
|
306
|
+
transfer_data: Stripe.PaymentIntent.TransferData | null;
|
|
307
|
+
transfer_group: string | null;
|
|
308
|
+
};
|
|
309
|
+
type MappedCart = ReturnType<typeof mapCart>;
|
|
310
|
+
/**
|
|
311
|
+
* @internal
|
|
312
|
+
*/
|
|
313
|
+
declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.PaymentIntent): {
|
|
314
|
+
payment_method: Stripe.PaymentMethod | null;
|
|
315
|
+
latest_charge: Stripe.Charge | null;
|
|
316
|
+
taxBreakdown: ({
|
|
317
|
+
taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
|
|
318
|
+
taxPercentage: string;
|
|
319
|
+
taxAmount: number;
|
|
320
|
+
} | null)[];
|
|
321
|
+
metadata: {
|
|
322
|
+
shippingRateId?: string | undefined;
|
|
323
|
+
taxCalculationId?: string | undefined;
|
|
324
|
+
taxCalculationExp?: string | undefined;
|
|
325
|
+
taxId?: string | undefined;
|
|
326
|
+
couponCode?: string | undefined;
|
|
327
|
+
taxedAmount?: string | undefined;
|
|
328
|
+
"billingAddress.city"?: string | undefined;
|
|
329
|
+
"billingAddress.country"?: string | undefined;
|
|
330
|
+
"billingAddress.line1"?: string | undefined;
|
|
331
|
+
"billingAddress.line2"?: string | undefined;
|
|
332
|
+
"billingAddress.name"?: string | undefined;
|
|
333
|
+
"billingAddress.postalCode"?: string | undefined;
|
|
334
|
+
"billingAddress.state"?: string | undefined;
|
|
335
|
+
netAmount?: string | undefined;
|
|
336
|
+
taxBreakdown0?: string | undefined;
|
|
337
|
+
taxBreakdown1?: string | undefined;
|
|
338
|
+
taxBreakdown2?: string | undefined;
|
|
339
|
+
taxBreakdown3?: string | undefined;
|
|
340
|
+
taxBreakdown4?: string | undefined;
|
|
341
|
+
taxBreakdown5?: string | undefined;
|
|
342
|
+
} & Record<string, string>;
|
|
343
|
+
id: string;
|
|
344
|
+
object: "payment_intent";
|
|
345
|
+
amount: number;
|
|
346
|
+
amount_capturable: number;
|
|
347
|
+
amount_details?: Stripe.PaymentIntent.AmountDetails;
|
|
348
|
+
amount_received: number;
|
|
349
|
+
application: string | Stripe.Application | null;
|
|
350
|
+
application_fee_amount: number | null;
|
|
351
|
+
automatic_payment_methods: Stripe.PaymentIntent.AutomaticPaymentMethods | null;
|
|
352
|
+
canceled_at: number | null;
|
|
353
|
+
cancellation_reason: Stripe.PaymentIntent.CancellationReason | null;
|
|
354
|
+
capture_method: Stripe.PaymentIntent.CaptureMethod;
|
|
355
|
+
client_secret: string | null;
|
|
356
|
+
confirmation_method: Stripe.PaymentIntent.ConfirmationMethod;
|
|
357
|
+
created: number;
|
|
358
|
+
currency: string;
|
|
359
|
+
customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
|
|
360
|
+
description: string | null;
|
|
361
|
+
excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
|
|
362
|
+
last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
|
|
363
|
+
livemode: boolean;
|
|
364
|
+
next_action: Stripe.PaymentIntent.NextAction | null;
|
|
365
|
+
on_behalf_of: string | Stripe.Account | null;
|
|
366
|
+
payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
|
|
367
|
+
payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
|
|
368
|
+
payment_method_types: Array<string>;
|
|
369
|
+
presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
|
|
370
|
+
processing: Stripe.PaymentIntent.Processing | null;
|
|
371
|
+
receipt_email: string | null;
|
|
372
|
+
review: string | Stripe.Review | null;
|
|
373
|
+
setup_future_usage: Stripe.PaymentIntent.SetupFutureUsage | null;
|
|
374
|
+
shipping: Stripe.PaymentIntent.Shipping | null;
|
|
375
|
+
source: string | Stripe.CustomerSource | Stripe.DeletedCustomerSource | null;
|
|
376
|
+
statement_descriptor: string | null;
|
|
377
|
+
statement_descriptor_suffix: string | null;
|
|
378
|
+
status: Stripe.PaymentIntent.Status;
|
|
379
|
+
transfer_data: Stripe.PaymentIntent.TransferData | null;
|
|
380
|
+
transfer_group: string | null;
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
export { type CartMetadata, type MappedCart, type MappedProduct, type MappedShippingRate, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, filterValidProduct, filterValidProducts, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, mapShippingRate, mapShippingRates, objectToStripeQuery, sanitizeQueryValue, sortProducts };
|
package/dist/internal.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var d=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),S=t=>Object.entries(t).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function N(t){return t.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=e.object({category:e.string().optional(),order:e.coerce.number().optional(),slug:e.string(),variant:e.string().optional(),stock:e.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:e.string().optional(),preview:e.string().optional()});function f({default_price:t,marketing_features:r,...n}){return i(t,"Product must have a default price"),i(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function x(t){return!!(t.active&&!t.deleted&&t.default_price)}function T(t){return{...t,data:t.data.filter(x)}}function k(t){return t.data.map(f)}function b(t){return t}function A(t){return t.data.map(b)}function B(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var R=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId:e.string().optional(),couponCode:e.string().optional(),taxedAmount:e.string().optional(),"billingAddress.city":e.string().optional(),"billingAddress.country":e.string().optional(),"billingAddress.line1":e.string().optional(),"billingAddress.line2":e.string().optional(),"billingAddress.name":e.string().optional(),"billingAddress.postalCode":e.string().optional(),"billingAddress.state":e.string().optional(),netAmount:e.string().optional(),taxBreakdown0:e.string().optional(),taxBreakdown1:e.string().optional(),taxBreakdown2:e.string().optional(),taxBreakdown3:e.string().optional(),taxBreakdown4:e.string().optional(),taxBreakdown5:e.string().optional()}).and(e.record(e.string(),e.string())),c=e.object({taxType:e.string(),taxPercentage:e.string(),taxAmount:e.number()});function I(t){let r=t.payment_method;i(typeof r!="string","Payment method should not be a string");let n=t.customer;i(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=l.parse(t.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:r,taxBreakdown:o}}function M({payment_method:t,latest_charge:r,...n}){i(typeof t=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,x as filterValidProduct,T as filterValidProducts,B as getUniqueVariants,R as isProductAvailable,I as mapCart,M as mapOrder,f as mapProduct,k as mapProducts,b as mapShippingRate,A as mapShippingRates,S as objectToStripeQuery,m as sanitizeQueryValue,N as sortProducts};
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
interface BaseProvider {
|
|
2
|
+
productBrowse(params: ProductBrowseParams): Promise<ProductBrowseResult>;
|
|
3
|
+
productGet(params: ProductGetParams): Promise<Product | null>;
|
|
4
|
+
productSearch?(params: ProductSearchParams): Promise<ProductSearchResult>;
|
|
5
|
+
cartAdd(params: CartAddParams): Promise<Cart>;
|
|
6
|
+
cartUpdate(params: CartUpdateParams): Promise<Cart>;
|
|
7
|
+
cartRemove(params: CartRemoveParams): Promise<Cart>;
|
|
8
|
+
cartClear(params: CartClearParams): Promise<Cart>;
|
|
9
|
+
cartGet(params: CartGetParams): Promise<Cart | null>;
|
|
10
|
+
orderGet?(params: OrderGetParams): Promise<Order | null>;
|
|
11
|
+
orderList?(params: OrderListParams): Promise<OrderListResult>;
|
|
12
|
+
}
|
|
13
|
+
interface StripeProviderConfig {
|
|
14
|
+
secretKey?: string;
|
|
15
|
+
tagPrefix?: string;
|
|
16
|
+
}
|
|
17
|
+
interface YnsProviderConfig {
|
|
18
|
+
endpoint: string;
|
|
19
|
+
token: string;
|
|
20
|
+
}
|
|
21
|
+
interface Product {
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
slug?: string;
|
|
25
|
+
summary?: string;
|
|
26
|
+
images: string[];
|
|
27
|
+
active: boolean;
|
|
28
|
+
price: number;
|
|
29
|
+
currency: string;
|
|
30
|
+
stock?: number;
|
|
31
|
+
}
|
|
32
|
+
interface Customer {
|
|
33
|
+
id: string;
|
|
34
|
+
email?: string;
|
|
35
|
+
}
|
|
36
|
+
interface ProductInfo {
|
|
37
|
+
id: string;
|
|
38
|
+
name?: string;
|
|
39
|
+
images?: string[];
|
|
40
|
+
}
|
|
41
|
+
interface Cart {
|
|
42
|
+
id: string;
|
|
43
|
+
customerId?: string;
|
|
44
|
+
storeId?: string;
|
|
45
|
+
customer?: Customer;
|
|
46
|
+
items: CartItem[];
|
|
47
|
+
total: number;
|
|
48
|
+
currency: string;
|
|
49
|
+
createdAt?: string;
|
|
50
|
+
updatedAt?: string;
|
|
51
|
+
}
|
|
52
|
+
interface CartItem {
|
|
53
|
+
id: string;
|
|
54
|
+
productId: string;
|
|
55
|
+
variantId?: string;
|
|
56
|
+
quantity: number;
|
|
57
|
+
price: number;
|
|
58
|
+
stock?: number;
|
|
59
|
+
product?: ProductInfo;
|
|
60
|
+
}
|
|
61
|
+
interface Order {
|
|
62
|
+
id: string;
|
|
63
|
+
customerId?: string;
|
|
64
|
+
items: CartItem[];
|
|
65
|
+
total: number;
|
|
66
|
+
currency: string;
|
|
67
|
+
status: string;
|
|
68
|
+
createdAt: string;
|
|
69
|
+
updatedAt: string;
|
|
70
|
+
}
|
|
71
|
+
interface ProductBrowseParams {
|
|
72
|
+
first?: number;
|
|
73
|
+
offset?: number;
|
|
74
|
+
category?: string;
|
|
75
|
+
query?: string;
|
|
76
|
+
active?: boolean;
|
|
77
|
+
orderBy?: string;
|
|
78
|
+
orderDirection?: "asc" | "desc";
|
|
79
|
+
graphql?: string;
|
|
80
|
+
_provider?: "stripe" | "yns";
|
|
81
|
+
}
|
|
82
|
+
interface ProductGetParams {
|
|
83
|
+
slug?: string;
|
|
84
|
+
id?: string;
|
|
85
|
+
graphql?: string;
|
|
86
|
+
_provider?: "stripe" | "yns";
|
|
87
|
+
}
|
|
88
|
+
interface ProductSearchParams {
|
|
89
|
+
query: string;
|
|
90
|
+
limit?: number;
|
|
91
|
+
fields?: string[];
|
|
92
|
+
_provider?: "stripe" | "yns";
|
|
93
|
+
}
|
|
94
|
+
interface CartAddParams {
|
|
95
|
+
variantId: string;
|
|
96
|
+
quantity: number;
|
|
97
|
+
cartId?: string;
|
|
98
|
+
subscriptionId?: string;
|
|
99
|
+
_provider?: "stripe" | "yns";
|
|
100
|
+
}
|
|
101
|
+
interface CartRemoveParams {
|
|
102
|
+
cartId: string;
|
|
103
|
+
variantId: string;
|
|
104
|
+
_provider?: "stripe" | "yns";
|
|
105
|
+
}
|
|
106
|
+
interface CartClearParams {
|
|
107
|
+
cartId: string;
|
|
108
|
+
_provider?: "stripe" | "yns";
|
|
109
|
+
}
|
|
110
|
+
interface CartGetParams {
|
|
111
|
+
cartId: string;
|
|
112
|
+
_provider?: "stripe" | "yns";
|
|
113
|
+
}
|
|
114
|
+
interface CartUpdateParams {
|
|
115
|
+
cartId: string;
|
|
116
|
+
variantId: string;
|
|
117
|
+
quantity: number;
|
|
118
|
+
_provider?: "stripe" | "yns";
|
|
119
|
+
}
|
|
120
|
+
interface OrderGetParams {
|
|
121
|
+
orderId: string;
|
|
122
|
+
_provider?: "stripe" | "yns";
|
|
123
|
+
}
|
|
124
|
+
interface OrderListParams {
|
|
125
|
+
customerId?: string;
|
|
126
|
+
limit?: number;
|
|
127
|
+
offset?: number;
|
|
128
|
+
_provider?: "stripe" | "yns";
|
|
129
|
+
}
|
|
130
|
+
interface ProductBrowseResult {
|
|
131
|
+
data: Product[];
|
|
132
|
+
meta: {
|
|
133
|
+
count: number;
|
|
134
|
+
offset: number;
|
|
135
|
+
limit: number;
|
|
136
|
+
hasMore: boolean;
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
interface ProductSearchResult {
|
|
140
|
+
data: Product[];
|
|
141
|
+
total: number;
|
|
142
|
+
}
|
|
143
|
+
interface OrderListResult {
|
|
144
|
+
data: Order[];
|
|
145
|
+
meta: {
|
|
146
|
+
count: number;
|
|
147
|
+
offset: number;
|
|
148
|
+
limit: number;
|
|
149
|
+
hasMore: boolean;
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
interface YnsProduct extends Product {
|
|
153
|
+
category?: {
|
|
154
|
+
id: string;
|
|
155
|
+
name: string;
|
|
156
|
+
slug: string;
|
|
157
|
+
};
|
|
158
|
+
variants: Array<{
|
|
159
|
+
id: string;
|
|
160
|
+
price: number;
|
|
161
|
+
stock?: number;
|
|
162
|
+
attributes?: string;
|
|
163
|
+
}>;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
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, Customer as g, OrderGetParams as h, OrderListParams as i, OrderListResult as j, ProductBrowseParams as k, ProductBrowseResult as l, ProductGetParams as m, ProductInfo as n, ProductSearchParams as o, ProductSearchResult as p, YnsProviderConfig as q };
|
package/dist/stripe.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { S as StripeProviderConfig, k as ProductBrowseParams, l as ProductBrowseResult, m 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-CeP9uHnB.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Stripe Commerce client - zero-config constructor
|
|
5
|
+
* Reads configuration from environment variables by default
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { Commerce } from "commerce-kit/stripe";
|
|
10
|
+
*
|
|
11
|
+
* // Zero config - uses STRIPE_SECRET_KEY from environment
|
|
12
|
+
* const commerce = new Commerce();
|
|
13
|
+
*
|
|
14
|
+
* const products = await commerce.product.browse({ first: 10 });
|
|
15
|
+
* const result = await commerce.cart.add({ variantId: "price_123", quantity: 1 });
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
declare class Commerce {
|
|
19
|
+
private config;
|
|
20
|
+
private provider?;
|
|
21
|
+
private providerPromise?;
|
|
22
|
+
constructor(config?: StripeProviderConfig);
|
|
23
|
+
/**
|
|
24
|
+
* Detect Stripe configuration from environment variables
|
|
25
|
+
*/
|
|
26
|
+
private detectFromEnv;
|
|
27
|
+
/**
|
|
28
|
+
* Lazy-load and cache provider instance
|
|
29
|
+
*/
|
|
30
|
+
private getProvider;
|
|
31
|
+
/**
|
|
32
|
+
* Load Stripe provider
|
|
33
|
+
*/
|
|
34
|
+
private loadProvider;
|
|
35
|
+
/**
|
|
36
|
+
* Product operations - Stripe specific
|
|
37
|
+
*/
|
|
38
|
+
get product(): {
|
|
39
|
+
/**
|
|
40
|
+
* Browse/list products with Stripe-specific parameters
|
|
41
|
+
*/
|
|
42
|
+
browse: (params?: ProductBrowseParams) => Promise<ProductBrowseResult>;
|
|
43
|
+
/**
|
|
44
|
+
* Get single product by ID or slug
|
|
45
|
+
*/
|
|
46
|
+
get: (params: ProductGetParams) => Promise<Product | null>;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Cart operations - Stripe specific
|
|
50
|
+
*/
|
|
51
|
+
get cart(): {
|
|
52
|
+
/**
|
|
53
|
+
* Add item to cart (additive behavior)
|
|
54
|
+
*/
|
|
55
|
+
add: (params: CartAddParams) => Promise<Cart>;
|
|
56
|
+
/**
|
|
57
|
+
* Update item in cart (absolute behavior)
|
|
58
|
+
*/
|
|
59
|
+
update: (params: CartUpdateParams) => Promise<Cart>;
|
|
60
|
+
/**
|
|
61
|
+
* Remove item from cart
|
|
62
|
+
*/
|
|
63
|
+
remove: (params: CartRemoveParams) => Promise<Cart>;
|
|
64
|
+
/**
|
|
65
|
+
* Clear entire cart
|
|
66
|
+
*/
|
|
67
|
+
clear: (params: CartClearParams) => Promise<Cart>;
|
|
68
|
+
/**
|
|
69
|
+
* Get cart details
|
|
70
|
+
*/
|
|
71
|
+
get: (params: CartGetParams) => Promise<Cart | null>;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export { Commerce };
|
package/dist/stripe.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var xt=Object.defineProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var wt=(e,t)=>{for(var r in t)xt(e,r,{get:t[r],enumerable:!0})};var Ct,vt,y,q=v(()=>{"use strict";Ct=process.env.STRIPE_SECRET_KEY,vt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:Ct,StripeCurrency:vt}});function _(e,t){if(!e)throw new Error(t)}var M,J,K=v(()=>{"use strict";M=e=>{if(e==null)return 0;if(typeof e=="number")return e;let t=Number.parseInt(e,10);return Number.isNaN(t)?0:t},J=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}}});var Pt,O,W=v(()=>{"use strict";Pt=e=>e.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=e=>Object.entries(e).map(([t,r])=>`${t}:"${Pt(r)}"`).join(" AND ").trim()});import{z as o}from"zod";function B(e){return e.toSorted((t,r)=>{let n=Number(t.metadata.order),i=Number(r.metadata.order);return Number.isNaN(n)&&Number.isNaN(i)||n===i?r.updated-t.updated:Number.isNaN(n)?1:Number.isNaN(i)?-1:n-i})}function $({default_price:e,marketing_features:t,...r}){return _(e,"Product must have a default price"),_(typeof e=="object","Product default price must be an object"),{...r,default_price:e,marketing_features:t.map(n=>n.name).filter(Boolean),metadata:St.parse(r.metadata)}}function _t(e){return!!(e.active&&!e.deleted&&e.default_price)}function N(e){return{...e,data:e.data.filter(_t)}}function G(e){return e.data.map($)}function F(e){return e.filter((t,r,n)=>r===n.findIndex(i=>i.metadata.slug===t.metadata.slug))}function Y(e){let t=e.payment_method;_(typeof t!="string","Payment method should not be a string");let r=e.customer;_(typeof r!="string"&&!r?.deleted,"Customer should not be a string");let n=U.parse(e.metadata),i=Object.entries(n).filter(([a])=>a.startsWith("taxBreakdown")).map(([a,s])=>{let d=It.safeParse(J(String(s)));return d.success?d.data:null}).filter(Boolean);return{...e,metadata:n,customer:r,payment_method:t,taxBreakdown:i}}var St,X,U,It,H=v(()=>{"use strict";K();W();St=o.object({category:o.string().optional(),order:o.coerce.number().optional(),slug:o.string(),variant:o.string().optional(),stock:o.coerce.number().optional().transform(e=>e===void 0?Number.POSITIVE_INFINITY:e),digitalAsset:o.string().optional(),preview:o.string().optional()});X=e=>!e.deleted&&e.active,U=o.object({shippingRateId:o.string().optional(),taxCalculationId:o.string().optional(),taxCalculationExp:o.string().optional(),taxId:o.string().optional(),couponCode:o.string().optional(),taxedAmount:o.string().optional(),"billingAddress.city":o.string().optional(),"billingAddress.country":o.string().optional(),"billingAddress.line1":o.string().optional(),"billingAddress.line2":o.string().optional(),"billingAddress.name":o.string().optional(),"billingAddress.postalCode":o.string().optional(),"billingAddress.state":o.string().optional(),netAmount:o.string().optional(),taxBreakdown0:o.string().optional(),taxBreakdown1:o.string().optional(),taxBreakdown2:o.string().optional(),taxBreakdown3:o.string().optional(),taxBreakdown4:o.string().optional(),taxBreakdown5:o.string().optional()}).and(o.record(o.string(),o.string())),It=o.object({taxType:o.string(),taxPercentage:o.string(),taxAmount:o.number()})});var S,Rt,Et,E,m,Z=v(()=>{"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(e){E>S.DEBUG||console.time(e)},timeEnd(e){E>S.DEBUG||console.timeEnd(e)},log(...e){E>S.LOG||console.log(...e)},dir(e,t){E>S.LOG||console.dir(e,t)},warn(...e){E>S.WARN||console.warn(...e)},error(...e){E>S.ERROR||console.error(...e)}}});var w,P,tt=v(()=>{"use strict";w=e=>e.filter(Boolean),P={accountGetById:{tags:({accountId:e})=>w(["account",e&&`account-${e}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:e})=>w(["cart",`cart-${e}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:e})=>w(["tax-calculations",`tax-calculations-${e}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:e})=>w(["files",`file-${e}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:e})=>w(["order",`order-${e}`]),revalidate:()=>{}},productBrowse:{tags:({category:e})=>w(["product",e&&`category-${e}`]),revalidate:()=>{}},productGetById:{tags:({productId:e})=>w(["product",`product-${e}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:e})=>w(["product",`product-${e}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:e})=>w(["shipping",`shipping-${e}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}}});import et from"stripe";var bt,f,rt=v(()=>{"use strict";q();bt=(e,t)=>!e||!t?e:[...e,`prefix-${t}`,...e.map(r=>`${t}-${r}`)],f=({tags:e,revalidate:t,cache:r,tagPrefix:n,secretKey:i})=>{let a=i??y.StripeSecretKey;if(!a)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let s=bt(e,n);return new et(a,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:et.createFetchHttpClient(((p,c)=>fetch(p,{...c,cache:r??c?.cache,next:{tags:s??c?.next?.tags,revalidate:t??c?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var h,at=v(()=>{"use strict";h=async()=>{let e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??e}});import{revalidateTag as At}from"next/cache";import b from"stripe";import{z as ue}from"zod";function ot({productId:e,cartId:t}){return t?j({cartId:t,productId:e,operation:"INCREASE",clearTaxCalculation:!0}):Tt({productId:e})}async function j({productId:e,cartId:t,operation:r,clearTaxCalculation:n}){let[i,a]=await Promise.all([V(e),pt(t)]);if(!i)throw new Error(`Product not found: ${e}`);if(!a)throw new Error(`Cart not found: ${t}`);if(i.metadata.stock<=0)throw Error(`Product ${e} 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 s=a.cart.metadata??{},c=M(s[e])+(r==="INCREASE"?1:-1);c<=0?s[e]="":s[e]=c.toString();let C=Nt(a)+(i.default_price.unit_amount??0);try{return await Mt({paymentIntentId:t,data:{metadata:s,amount:C||it},clearTaxCalculation:n})}catch(g){m.error(g)}finally{At(`cart-${t}`)}}async function st(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.cartGetById.tags({cartId:e}),cache:"force-cache"});try{let a=await i.paymentIntents.retrieve(e,{expand:["payment_method","customer"]},{stripeAccount:t});if(dt.includes(a.status)){let s=Y(a);if(!s)return null;let d=await z(s.metadata),{metadata:{shippingRateId:p}}=s,c=p&&await Q(p);return{cart:s,lines:d.map(({product:C,quantity:g})=>C?{product:C,quantity:g}:null).filter(Boolean),shippingRate:c||null}}}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function Tt({productId:e}={}){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let a=e?await V(e):null;if(a&&a.metadata.stock<=0)throw Error(`Product ${e} is out of stock`);return await i.paymentIntents.create({currency:y.StripeCurrency,amount:a?.default_price.unit_amount||it,automatic_payment_methods:{enabled:!0},metadata:{...a&&{[a.id]:"1"}}},{stripeAccount:t})}catch(a){throw m.error(a),a}}async function D(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.productGetById.tags({productId:e}),cache:"force-cache"});try{let a=await i.products.retrieve(e,{expand:["default_price"]},{stripeAccount:t});return $(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function ct({slug:e}){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),a=await f({secretKey:n,tagPrefix:r,tags:P.productGetBySlug.tags({productSlug:e}),cache:"force-cache"}).products.search({query:O({active:!0,'metadata["slug"]':e}),expand:["data.default_price"]},{stripeAccount:t});if(a.data.length>1&&a.data.some(s=>!s.metadata.variant))throw new Error(`Multiple products found with the same slug (${e}) but no variant set.`);return await Promise.allSettled(a.data.map(s=>D(s.id))),B(G(N(a)))}async function ut(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h();if(e.filter?.category){let s=e.filter?.category,p=await f({secretKey:n,tagPrefix:r,tags:P.productBrowse.tags({category:s}),cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':s}),expand:["data.default_price"]},{stripeAccount:t});return B(F(G(N(p)))).slice(e.offset||0,e.first)}let a=await f({secretKey:n,tagPrefix:r,tags:P.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:t});return B(F(G(N(a))).filter(X)).slice(e.offset||0,e.first)}async function Q(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.shippingGetById.tags({shippingId:e}),cache:"force-cache"});try{let a=await i.shippingRates.retrieve(e,{},{stripeAccount:t});return a}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function z(e){let t=Bt(e);return await Promise.all(t.map(async([n,i])=>({product:await V(n),quantity:i})))}function Lt({oldCart:e,data:t,mergedMetadata:r,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),a=r.taxCalculationExp?Number.parseInt(r.taxCalculationExp,10)*1e3:null;if(!a||i>=a)return!0;let s=e.cart.metadata.netAmount||e.cart.amount,d=t.amount,p=Gt.some(u=>!r[u]&&!e.cart.metadata[u]?!1:r[u]!==e.cart.metadata[u]),c=n.length!==e.lines.length||n.some(u=>{let x=e.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||p||c}async function lt(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:["customers",`customers-${e}`],cache:"force-cache"});try{let a=await i.customers.retrieve(e,{},{stripeAccount:t});return a.deleted?null:a}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}function qt(e,t){return t.coupon.amount_off?Math.max(e-t.coupon.amount_off,0):t.coupon.percent_off?Math.floor(e*(1-t.coupon.percent_off/100)):e}async function Kt(){let{stripeAccount:e,storeId:t,secretKey:r}=await h();return await f({secretKey:r,tagPrefix:t,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:e})}var it,V,dt,Bt,$t,pt,Nt,Gt,kt,nt,Mt,mt=v(()=>{"use strict";q();H();Z();tt();rt();W();K();at();it=1e3;V=async e=>{let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.productGetById.tags({productId:e}),cache:"force-cache"});try{let a=await i.products.retrieve(e,{expand:["default_price"]},{stripeAccount:t});return $(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}},dt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Bt=e=>Object.entries(e??{}).filter(([t])=>t.startsWith("prod_")).map(([t,r])=>[t,M(r)]).filter(([,t])=>t&&Number.isFinite(t)&&t>0),$t=async e=>{let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.cartGetById.tags({cartId:e}),cache:"force-cache"});try{let a=await i.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:t}),s=typeof a.customer=="string"?await lt(a.customer):null;if(dt.includes(a.status))return Y({...a,customer:s})}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}};pt=async e=>{let t=await $t(e);if(!t)return null;let r=await z(t.metadata),{metadata:{shippingRateId:n}}=t,i=n&&await Q(n);return{cart:t,lines:r.map(({product:a,quantity:s})=>a?{product:a,quantity:s}:null).filter(Boolean),shippingRate:i||null}},Nt=e=>e?e.cart.metadata?.taxCalculationId?e.cart.amount:(e.shippingRate?.fixed_amount?.amount??0)+e.lines.reduce((t,{product:r,quantity:n})=>t+(r.default_price?.unit_amount??0)*n,0):0,Gt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];kt=async({lineItems:e,billingAddress:t,cartId:r,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:a,storeId:s,secretKey:d}=await h(),p=f({secretKey:d,tagPrefix:s,tags:P.createTaxCalculation.tags({cartId:r}),cache:"force-cache"});if(!t?.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 ${r}`);let I=await p.tax.calculations.create({expand:["line_items"],line_items:e.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:t.country,city:t?.city,line1:t?.line1,line2:t?.line2,postal_code:t?.postalCode,state:t?.state}}},{stripeAccount:a});return m.timeEnd(`createTaxCalculation ${r}`),console.log(JSON.stringify(I).length),I},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};Mt=async({paymentIntentId:e,data:t,customerOverride:r,clearTaxCalculation:n})=>{let{stripeAccount:i,storeId:a,secretKey:s}=await h(),d=await pt(e);_(d,`Cart not found: ${e}`);let p=t.amount?t.amount.toString():null,c=U.parse({...d.cart.metadata,...t.metadata});m.time("getProductsFromMetadata");let C=await z(c);m.timeEnd("getProductsFromMetadata");let g=!n&&Lt({oldCart:d,data:t,mergedMetadata:c,lines:C});console.log({shouldRecalculateTax:g});let u=g?await kt({cartId:e,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=r??(t.customer?await lt(t.customer):d.cart.customer);console.log({customer:x});let I=f({secretKey:s,tagPrefix:a,cache:"no-cache"});m.time(`paymentIntents.update ${e}`);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:t.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":t.amount,netAmount:p});let ht=await I.paymentIntents.update(e,{...t,...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 ${e}`),ht}});var ft={};wt(ft,{StripeProvider:()=>L,createStripeProvider:()=>Wt});function Wt(e){return new L(e)}var L,gt=v(()=>{"use strict";mt();L=class{constructor(t){this.config=t}mapStripeProduct(t){let r=t.default_price?.unit_amount||0,n=t.default_price?.currency||"usd";return{id:t.id,name:t.name,slug:t.metadata?.slug,summary:t.description,images:t.images||[],active:t.active,price:r/100,currency:n.toUpperCase(),stock:Number.parseInt(t.metadata?.stock||"0",10),stripeId:t.id,metadata:t.metadata||{}}}async productBrowse(t){let r=await ut({first:t.first||10,...t}),n=r.data.map(i=>this.mapStripeProduct(i));return{data:n,meta:{count:r.totalCount||n.length,offset:t.offset||0,limit:t.first||10,hasMore:n.length===(t.first||10)}}}async productGet(t){if(t.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),t.slug){let r=await ct({slug:t.slug});return r?this.mapStripeProduct(r):null}if(t.id){let r=await D(t.id);return r?this.mapStripeProduct(r):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(t){let r=t.quantity;if(t.cartId)try{let s=await this.cartGet({cartId:t.cartId});if(s){let d=s.items.find(p=>p.variantId===t.variantId);d&&(r=d.quantity+t.quantity)}}catch{}let i=(await ot({productId:t.variantId,cartId:t.cartId}))?.id||t.cartId||"",a=await this.cartGet({cartId:i});if(!a)throw new Error("Failed to retrieve cart after adding item");return a}async cartUpdate(t){let r=await j({cartId:t.cartId,productId:t.variantId,operation:"SET",quantity:t.quantity}),n=await this.cartGet({cartId:r?.id||t.cartId});if(!n)throw new Error("Failed to retrieve cart after update");return n}async cartClear(t){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartRemove(t){return await this.cartUpdate({cartId:t.cartId,variantId:t.variantId,quantity:0})}async cartGet(t){let r=await st(t.cartId);return r?this.mapCart(r):null}mapCart(t){let r=this.mapCartItems(t.lines);return{id:t.cart.id,customerId:this.mapCustomerId(t.cart.customer),storeId:void 0,customer:void 0,items:r,total:this.calculateTotal(r),currency:t.cart.currency?.toUpperCase()||"USD",createdAt:new Date(t.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}mapCartItems(t){return t?.map(r=>this.mapCartItem(r))||[]}mapCartItem(t){return{id:t.product?.id||"",productId:t.product?.id||"",variantId:t.product?.id,quantity:t.quantity,price:t.product?.default_price?.unit_amount||0,stock:void 0,product:void 0}}mapCustomerId(t){if(typeof t=="string")return t;if(t?.id)return t.id}calculateTotal(t){return t.reduce((r,n)=>r+n.price*n.quantity,0)}}});var yt=class{config;provider;providerPromise;constructor(t){if(this.config=t||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:t}=await Promise.resolve().then(()=>(gt(),ft));return t(this.config)}catch(t){throw new Error(`Failed to initialize Stripe provider: ${t instanceof Error?t.message:"Unknown error"}`)}}get product(){return{browse:async(t={})=>(await this.getProvider()).productBrowse(t),get:async t=>(await this.getProvider()).productGet(t)}}get cart(){return{add:async t=>(await this.getProvider()).cartAdd(t),update:async t=>(await this.getProvider()).cartUpdate(t),remove:async t=>(await this.getProvider()).cartRemove(t),clear:async t=>(await this.getProvider()).cartClear(t),get:async t=>(await this.getProvider()).cartGet(t)}}};export{yt as Commerce};
|