@konfiqo/storefront-sdk 0.9.0 → 0.10.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/README.md CHANGED
@@ -183,36 +183,38 @@ with the response body or rejects with a [`StorefrontError`](#errors).
183
183
  Path arguments (slugs, ids) that are empty, `.` or `..` reject with a
184
184
  `TypeError` (`invalid_path_segment`) without a request.
185
185
 
186
- | Method | Route | Resolves with |
187
- | ----------------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
188
- | `store.get()` | `GET /v1/store` | `Store`: name, `defaultLanguage`, `currency`, `logo`/`logoUrl`, `theme` (`ThemeV1`, as stored), contact, `company`, shipping rules |
189
- | `categories.list()` | `GET /v1/categories` | `{ items: Category[] }` (active tree, sorted) |
190
- | `products.list({ category?, q?, page?, pageSize? })` | `GET /v1/products` | `{ items: Product[], pagination }` (`pageSize` 1–100, default 20) |
191
- | `products.get(slug)` | `GET /v1/products/:slug` | `Product` |
192
- | `blog.list({ page?, pageSize? })` | `GET /v1/blog` | `{ items: BlogPostSummary[], pagination }` (newest first, `pageSize` 1–50, default 12) |
193
- | `blog.get(slug)` | `GET /v1/blog/:slug` | `BlogPost`: the summary fields, `metaDescription` and the body `tree` |
194
- | `carts.create()` | `POST /v1/carts` | `Cart` |
195
- | `carts.get(cartId)` | `GET /v1/carts/:id` | `Cart` |
196
- | `carts.addLine(cartId, { variantId, quantity, personalization? })` | `POST /v1/carts/:id/lines` | `Cart` |
197
- | `carts.updateLine(cartId, lineId, { quantity })` | `PATCH /v1/carts/:id/lines/:lineId` | `Cart` |
198
- | `carts.removeLine(cartId, lineId)` | `DELETE /v1/carts/:id/lines/:lineId` | `Cart` |
199
- | `carts.setCustomer(cartId, { email, name, surname, phone, identityNumber? })` | `PUT /v1/carts/:id/customer` | `Cart` |
200
- | `carts.setAddress(cartId, { shipping, billing? })` | `PUT /v1/carts/:id/address` | `Cart` |
201
- | `carts.shippingOptions(cartId)` | `GET /v1/carts/:id/shipping-options` | `{ items: { id, priceMinor }[] }` |
202
- | `carts.setShippingOption(cartId, optionId)` | `PUT /v1/carts/:id/shipping-option` | `Cart` |
203
- | `carts.agreements(cartId)` | `POST /v1/carts/:id/agreements` | `CartAgreements` (see [Legal texts and agreements](#legal-texts-and-agreements)) |
204
- | `carts.checkout(cartId, { agreementsHash, turnstileToken? })` | `POST /v1/carts/:id/checkout` | `CheckoutResult` (see [Checkout challenge](#checkout-challenge)) |
205
- | `orders.get(orderId, token)` | `GET /v1/orders/:id?token=` | `Order` |
206
- | `orders.createReturn(orderId, token, { lines, note? })` | `POST /v1/orders/:id/returns` | `OrderReturn` (see [Returns](#returns)); the token goes in the body |
207
- | `orders.cancelReturn(orderId, returnId, token)` | `POST /v1/orders/:id/returns/:returnId/cancel` | `OrderReturn`, now `cancelled` |
208
- | `carts.recover(token)` | `POST /v1/carts/recover` | `{ cartId }`: a **new** cart with the abandoned cart's lines (see [Accounts](#accounts-and-cart-recovery)) |
209
- | `account.requestCode(email, { turnstileToken? })` | `POST /v1/account/code` | nothing (202 for any address) |
210
- | `account.signIn(email, code)` | `POST /v1/account/session` | `{ customer: { email } }`; sets the session cookie |
211
- | `account.signOut()` | `DELETE /v1/account/session` | nothing |
212
- | `account.get(page?)` | `GET /v1/account` | `Account`: profile, `savedAddresses`, one page of `orders` (20, newest first) |
213
- | `account.updateProfile({ name, surname, phone })` | `PUT /v1/account/profile` | nothing |
214
- | `account.saveAddresses(list)` | `PUT /v1/account/addresses` | `SavedAddress[]` as stored (max 5, one default) |
215
- | `media.url(key)` | none | absolute image URL (synchronous) |
186
+ | Method | Route | Resolves with |
187
+ | ----------------------------------------------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
188
+ | `store.get()` | `GET /v1/store` | `Store`: name, `defaultLanguage`, `currency`, `logo`/`logoUrl`, `theme` (`ThemeV1`, as stored), contact, `company`, shipping rules, `hasCodeCampaigns` |
189
+ | `categories.list()` | `GET /v1/categories` | `{ items: Category[] }` (active tree, sorted) |
190
+ | `products.list({ category?, q?, page?, pageSize? })` | `GET /v1/products` | `{ items: Product[], pagination }` (`pageSize` 1–100, default 20) |
191
+ | `products.get(slug)` | `GET /v1/products/:slug` | `Product` |
192
+ | `blog.list({ page?, pageSize? })` | `GET /v1/blog` | `{ items: BlogPostSummary[], pagination }` (newest first, `pageSize` 1–50, default 12) |
193
+ | `blog.get(slug)` | `GET /v1/blog/:slug` | `BlogPost`: the summary fields, `metaDescription` and the body `tree` |
194
+ | `carts.create()` | `POST /v1/carts` | `Cart` |
195
+ | `carts.get(cartId)` | `GET /v1/carts/:id` | `Cart` |
196
+ | `carts.addLine(cartId, { variantId, quantity, personalization? })` | `POST /v1/carts/:id/lines` | `Cart` |
197
+ | `carts.updateLine(cartId, lineId, { quantity })` | `PATCH /v1/carts/:id/lines/:lineId` | `Cart` |
198
+ | `carts.removeLine(cartId, lineId)` | `DELETE /v1/carts/:id/lines/:lineId` | `Cart` |
199
+ | `carts.setCustomer(cartId, { email, name, surname, phone, identityNumber? })` | `PUT /v1/carts/:id/customer` | `Cart` |
200
+ | `carts.setAddress(cartId, { shipping, billing? })` | `PUT /v1/carts/:id/address` | `Cart` |
201
+ | `carts.shippingOptions(cartId)` | `GET /v1/carts/:id/shipping-options` | `{ items: { id, priceMinor }[] }` |
202
+ | `carts.setShippingOption(cartId, optionId)` | `PUT /v1/carts/:id/shipping-option` | `Cart` |
203
+ | `carts.applyCode(cartId, code)` | `PUT /v1/carts/:id/coupon` | `Cart` with the code applied (see [Discount codes](#discount-codes)) |
204
+ | `carts.removeCode(cartId)` | `DELETE /v1/carts/:id/coupon` | `Cart` without the code |
205
+ | `carts.agreements(cartId)` | `POST /v1/carts/:id/agreements` | `CartAgreements` (see [Legal texts and agreements](#legal-texts-and-agreements)) |
206
+ | `carts.checkout(cartId, { agreementsHash, turnstileToken? })` | `POST /v1/carts/:id/checkout` | `CheckoutResult` (see [Checkout challenge](#checkout-challenge)) |
207
+ | `orders.get(orderId, token)` | `GET /v1/orders/:id?token=` | `Order` |
208
+ | `orders.createReturn(orderId, token, { lines, note? })` | `POST /v1/orders/:id/returns` | `OrderReturn` (see [Returns](#returns)); the token goes in the body |
209
+ | `orders.cancelReturn(orderId, returnId, token)` | `POST /v1/orders/:id/returns/:returnId/cancel` | `OrderReturn`, now `cancelled` |
210
+ | `carts.recover(token)` | `POST /v1/carts/recover` | `{ cartId }`: a **new** cart with the abandoned cart's lines (see [Accounts](#accounts-and-cart-recovery)) |
211
+ | `account.requestCode(email, { turnstileToken? })` | `POST /v1/account/code` | nothing (202 for any address) |
212
+ | `account.signIn(email, code)` | `POST /v1/account/session` | `{ customer: { email } }`; sets the session cookie |
213
+ | `account.signOut()` | `DELETE /v1/account/session` | nothing |
214
+ | `account.get(page?)` | `GET /v1/account` | `Account`: profile, `savedAddresses`, one page of `orders` (20, newest first) |
215
+ | `account.updateProfile({ name, surname, phone })` | `PUT /v1/account/profile` | nothing |
216
+ | `account.saveAddresses(list)` | `PUT /v1/account/addresses` | `SavedAddress[]` as stored (max 5, one default) |
217
+ | `media.url(key)` | none | absolute image URL (synchronous) |
216
218
 
217
219
  ### Accounts and cart recovery
218
220
 
@@ -318,6 +320,40 @@ return now; `details.reason` is one of `unpaid`, `refunded`, `cancelled`,
318
320
  absent when a cancel is refused because the return is no longer open.
319
321
  `return_not_found` (404) for a return of another order.
320
322
 
323
+ ### Discount codes
324
+
325
+ A cart carries one code. `carts.applyCode(cartId, code)` enters it (a second
326
+ code replaces the first) and answers the cart with the discount applied;
327
+ `carts.removeCode(cartId)` takes it off. Codes are matched without regard to
328
+ case or surrounding spaces.
329
+
330
+ ```ts
331
+ try {
332
+ const cart = await client.carts.applyCode(cartId, 'SUMMER10');
333
+ if (cart.codeReason)
334
+ showCodeReason(cart.codeReason); // kept, not applied
335
+ else showApplied(cart.appliedCampaigns);
336
+ } catch (e) {
337
+ if (isStorefrontError(e) && e.is('coupon_invalid')) {
338
+ showCodeReason(e.details.reason); // 'unknown' | 'used_up'
339
+ } else throw e;
340
+ }
341
+ ```
342
+
343
+ A known code whose conditions do not hold now (a minimum subtotal, a date)
344
+ is kept on the cart with `codeReason` set and no discount; it applies once
345
+ they hold. `codeReason` is `expired`, `not_started`, `min_subtotal`,
346
+ `first_order_only`, `used_up`, `not_combinable_better` or `unknown`. A code
347
+ found no longer usable at checkout (another order used it, it was switched
348
+ off) stays on the cart with `codeReason` `used_up` or `unknown` until the
349
+ buyer applies a code again.
350
+
351
+ The cart is priced without the buyer: a campaign that needs the buyer (first
352
+ order only, a per-customer limit) is listed in `pendingCampaigns` until the
353
+ agreements are loaded. `carts.agreements` answers with `quote`, the totals
354
+ for this buyer: show those at the review step. Offer the code field only
355
+ when `store.hasCodeCampaigns` is true.
356
+
321
357
  **Customer.** `phone` must be a Turkish mobile number (`05XX…`, `5XX…`,
322
358
  `+90…`, `0090…`; spaces, dashes, parentheses allowed); it comes back as
323
359
  `90XXXXXXXXXX`. Addresses use `{ name?, phone?, email?, address | line1 +
@@ -376,50 +412,51 @@ try {
376
412
 
377
413
  ### API error codes
378
414
 
379
- | Code | Status | `details` | Meaning / what to do |
380
- | ------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
381
- | `store_not_found` | 404 | | bad / revoked publishable key, or the store is disabled |
382
- | `origin_not_allowed` | 403 | | browser `Origin` not in the store's `allowedOrigins` |
383
- | `invalid_request` | 400 | `{ issues: [{ path, message }] }` | a body or query field is invalid (e.g. `path: "phone"`) |
384
- | `invalid_buyer_ip` | 400 | | trusted key sent without a valid `buyerIp` |
385
- | `catalog_unavailable` | 503 | | the catalog could not be read; retry later |
386
- | `product_not_found` | 404 | | no sellable product with that slug |
387
- | `cart_not_found` | 404 | | unknown cart (or another store's): start a new cart |
388
- | `variant_not_found` | 404 | | the variant is not sold |
389
- | `insufficient_stock` | 409 | `{ available }` | only `available` units can be added |
390
- | `quantity_out_of_range` | 400 | | a line holds 1–99 units |
391
- | `too_many_lines` | 400 | | a cart holds at most 50 lines |
392
- | `line_not_found` | 404 | | no line with that id |
393
- | `invalid_shipping_option` | 400 | | the option is not offered for this cart |
394
- | `cart_read_only` | 409 | `{ status: 'ordered' \| 'expired' }` | the cart can no longer change: `expired` → start a new cart; `ordered` → show the order, or re-open payment with `REOPEN_AGREEMENTS_HASH` (step 9) |
395
- | `checkout_in_progress` | 409 | | another checkout of this cart is running: retry in a few seconds |
396
- | `checkout_incomplete` | 400 | `{ missing: ('lines' \| 'customer' \| 'identityNumber' \| 'shippingAddress' \| 'shippingOption')[] }` | collect what is missing |
397
- | `legal_not_confirmed` | 409 | | the store has not confirmed its legal texts and takes no orders yet: show a clear "not taking orders" message |
398
- | `agreements_changed` | 409 | | the cart or a legal text changed after `carts.agreements`: load the agreements again, show them, then check out with the new hash |
399
- | `cart_incomplete` | 409 | `{ missing }` (as `checkout_incomplete`) | `carts.agreements` on a cart without lines, customer or address: collect what is missing, then load the agreements |
400
- | `cart_changed` | 409 | `{ lines, subtotalMinor, shippingMinor, totalMinor, shippingOptions }` | prices or shipping changed: show the new totals, let the buyer confirm, then call checkout again. Never re-submit silently. |
401
- | `out_of_stock` | 409 | `{ variantIds }` | remove / reduce those lines |
402
- | `invalid_personalization` | 400, 409 | `{ lineIds? }` (409 at checkout) | 400: the text breaks the product's rule (or the product asks for none). 409: those lines' stored text is no longer valid: remove each line and add it again with a valid text |
403
- | `amount_out_of_range` | 400 | | total not representable |
404
- | `nothing_to_pay` | 400 | | total is zero |
405
- | `invalid_buyer_details` | 422 | `{ field }` | the payment provider refused `name`, `surname`, `email`, `phone`, `identityNumber`, `shippingAddress.<f>` or `billingAddress.<f>`: let the buyer fix it, check out again |
406
- | `payment_unavailable` | 502 | | payments refused or unreachable; the order was cancelled, the cart is still open |
407
- | `checkout_unavailable` | 503 | | store backend unreachable; the cart is still open, retry |
408
- | `order_not_found` | 404 | | unknown order or wrong token |
409
- | `order_unavailable` | 503 | | order status temporarily unavailable; poll again |
410
- | `media_not_found` | 404 | | (image route) key not referenced by the catalog |
411
- | `media_unavailable` | 503 | | (image route) image temporarily unavailable |
412
- | `challenge_required` | 400 | | the store requires a checkout challenge and no token was sent: render the widget, check out with its token |
413
- | `challenge_failed` | 403 | | the token was invalid, expired or already used: `reset()` the widget, check out with the new token |
414
- | `challenge_unavailable` | 503 | | the challenge could not be verified right now: retry in a moment |
415
- | `too_many_open_orders` | 429 | | too many unpaid orders from this buyer: finish or wait out a pending payment |
416
- | `not_signed_in` | 401 | | no valid session cookie: sign in |
417
- | `invalid_code` | 401 | | wrong, spent or expired sign-in code (5 attempts per code) |
418
- | `profile_required` | 409 | | save the profile before saving addresses |
419
- | `too_many_code_requests` | 429 | | too many codes requested from this address: wait |
420
- | `invalid_recovery_token` | 400 | | the recovery link is malformed or not for this store |
421
- | `cart_not_recoverable` | 410 | | the abandoned cart was ordered, expired or deleted: start a new cart |
422
- | `unavailable` | 503 | | the account could not be read or saved right now: retry |
415
+ | Code | Status | `details` | Meaning / what to do |
416
+ | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
417
+ | `store_not_found` | 404 | | bad / revoked publishable key, or the store is disabled |
418
+ | `origin_not_allowed` | 403 | | browser `Origin` not in the store's `allowedOrigins` |
419
+ | `invalid_request` | 400 | `{ issues: [{ path, message }] }` | a body or query field is invalid (e.g. `path: "phone"`) |
420
+ | `invalid_buyer_ip` | 400 | | trusted key sent without a valid `buyerIp` |
421
+ | `catalog_unavailable` | 503 | | the catalog could not be read; retry later |
422
+ | `product_not_found` | 404 | | no sellable product with that slug |
423
+ | `cart_not_found` | 404 | | unknown cart (or another store's): start a new cart |
424
+ | `variant_not_found` | 404 | | the variant is not sold |
425
+ | `insufficient_stock` | 409 | `{ available }` | only `available` units can be added |
426
+ | `quantity_out_of_range` | 400 | | a line holds 1–99 units |
427
+ | `too_many_lines` | 400 | | a cart holds at most 50 lines |
428
+ | `line_not_found` | 404 | | no line with that id |
429
+ | `invalid_shipping_option` | 400 | | the option is not offered for this cart |
430
+ | `cart_read_only` | 409 | `{ status: 'ordered' \| 'expired' }` | the cart can no longer change: `expired` → start a new cart; `ordered` → show the order, or re-open payment with `REOPEN_AGREEMENTS_HASH` (step 9) |
431
+ | `checkout_in_progress` | 409 | | another checkout of this cart is running: retry in a few seconds |
432
+ | `checkout_incomplete` | 400 | `{ missing: ('lines' \| 'customer' \| 'identityNumber' \| 'shippingAddress' \| 'shippingOption')[] }` | collect what is missing |
433
+ | `legal_not_confirmed` | 409 | | the store has not confirmed its legal texts and takes no orders yet: show a clear "not taking orders" message |
434
+ | `agreements_changed` | 409 | | the cart or a legal text changed after `carts.agreements`: load the agreements again, show them, then check out with the new hash |
435
+ | `cart_incomplete` | 409 | `{ missing }` (as `checkout_incomplete`) | `carts.agreements` on a cart without lines, customer or address: collect what is missing, then load the agreements |
436
+ | `cart_changed` | 409 | `{ lines, subtotalMinor, discountMinor, shippingMinor, shippingDiscountMinor, totalMinor, shippingOptions, appliedCampaigns, pendingCampaigns, codeReason }` | prices, shipping or a discount changed: show the new totals, let the buyer confirm, then call checkout again. Never re-submit silently. |
437
+ | `coupon_invalid` | 422 | `{ reason: 'unknown' \| 'used_up' }` | `carts.applyCode`: no such active code (`unknown`), or a single-use code already used or reserved (`used_up`). The cart is unchanged. |
438
+ | `out_of_stock` | 409 | `{ variantIds }` | remove / reduce those lines |
439
+ | `invalid_personalization` | 400, 409 | `{ lineIds? }` (409 at checkout) | 400: the text breaks the product's rule (or the product asks for none). 409: those lines' stored text is no longer valid: remove each line and add it again with a valid text |
440
+ | `amount_out_of_range` | 400 | | total not representable |
441
+ | `nothing_to_pay` | 400 | | total is zero |
442
+ | `invalid_buyer_details` | 422 | `{ field }` | the payment provider refused `name`, `surname`, `email`, `phone`, `identityNumber`, `shippingAddress.<f>` or `billingAddress.<f>`: let the buyer fix it, check out again |
443
+ | `payment_unavailable` | 502 | | payments refused or unreachable; the order was cancelled, the cart is still open |
444
+ | `checkout_unavailable` | 503 | | store backend unreachable; the cart is still open, retry |
445
+ | `order_not_found` | 404 | | unknown order or wrong token |
446
+ | `order_unavailable` | 503 | | order status temporarily unavailable; poll again |
447
+ | `media_not_found` | 404 | | (image route) key not referenced by the catalog |
448
+ | `media_unavailable` | 503 | | (image route) image temporarily unavailable |
449
+ | `challenge_required` | 400 | | the store requires a checkout challenge and no token was sent: render the widget, check out with its token |
450
+ | `challenge_failed` | 403 | | the token was invalid, expired or already used: `reset()` the widget, check out with the new token |
451
+ | `challenge_unavailable` | 503 | | the challenge could not be verified right now: retry in a moment |
452
+ | `too_many_open_orders` | 429 | | too many unpaid orders from this buyer: finish or wait out a pending payment |
453
+ | `not_signed_in` | 401 | | no valid session cookie: sign in |
454
+ | `invalid_code` | 401 | | wrong, spent or expired sign-in code (5 attempts per code) |
455
+ | `profile_required` | 409 | | save the profile before saving addresses |
456
+ | `too_many_code_requests` | 429 | | too many codes requested from this address: wait |
457
+ | `invalid_recovery_token` | 400 | | the recovery link is malformed or not for this store |
458
+ | `cart_not_recoverable` | 410 | | the abandoned cart was ordered, expired or deleted: start a new cart |
459
+ | `unavailable` | 503 | | the account could not be read or saved right now: retry |
423
460
 
424
461
  ### Codes the SDK assigns
425
462
 
@@ -534,7 +571,9 @@ items, so they must be shown **filled in for the cart** before payment:
534
571
 
535
572
  1. Once the cart has lines, a customer and an address, call
536
573
  `carts.agreements(cartId)`. It answers `{ orderNumber, documents,
537
- agreementsHash }`. The `documents` are `{ key, title, tree }`.
574
+ agreementsHash, quote }`. The `documents` are `{ key, title, tree }`;
575
+ `quote` holds the totals for this buyer (see
576
+ [Discount codes](#discount-codes)), null on older APIs.
538
577
  2. Show the documents and ask the buyer to accept them. Call
539
578
  `carts.agreements` again after every change to the cart.
540
579
  3. Check out with the hash:
package/dist/index.cjs CHANGED
@@ -50,6 +50,88 @@ __export(index_exports, {
50
50
  });
51
51
  module.exports = __toCommonJS(index_exports);
52
52
 
53
+ // src/normalize.ts
54
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
55
+ var num = (v) => typeof v === "number" ? v : 0;
56
+ var text = (v) => typeof v === "string" ? v : "";
57
+ var REASONS = /* @__PURE__ */ new Set([
58
+ "expired",
59
+ "not_started",
60
+ "min_subtotal",
61
+ "first_order_only",
62
+ "used_up",
63
+ "not_combinable_better",
64
+ "unknown"
65
+ ]);
66
+ function normalizeReason(v) {
67
+ return typeof v === "string" && REASONS.has(v) ? v : null;
68
+ }
69
+ function normalizeCampaigns(v) {
70
+ if (!Array.isArray(v)) return [];
71
+ return v.filter(isObject).map((c) => ({
72
+ ...typeof c.campaignId === "string" && { campaignId: c.campaignId },
73
+ buyerLabel: text(c.buyerLabel),
74
+ discountMinor: num(c.discountMinor),
75
+ shippingDiscountMinor: num(c.shippingDiscountMinor)
76
+ }));
77
+ }
78
+ function normalizePending(v) {
79
+ if (!Array.isArray(v)) return [];
80
+ return v.filter(isObject).map((c) => ({
81
+ ...typeof c.campaignId === "string" && { campaignId: c.campaignId },
82
+ buyerLabel: text(c.buyerLabel)
83
+ }));
84
+ }
85
+ function normalizeCartLine(l) {
86
+ return { ...l, discountMinor: num(l.discountMinor) };
87
+ }
88
+ function normalizeCart(c) {
89
+ const r = c;
90
+ return {
91
+ ...c,
92
+ lines: (Array.isArray(r.lines) ? r.lines : []).map(
93
+ (l) => normalizeCartLine(l)
94
+ ),
95
+ discountMinor: num(r.discountMinor),
96
+ shippingDiscountMinor: num(r.shippingDiscountMinor),
97
+ appliedCampaigns: normalizeCampaigns(r.appliedCampaigns),
98
+ pendingCampaigns: normalizePending(r.pendingCampaigns),
99
+ couponCode: typeof r.couponCode === "string" ? r.couponCode : null,
100
+ codeReason: normalizeReason(r.codeReason)
101
+ };
102
+ }
103
+ function normalizeOrder(o) {
104
+ const r = o;
105
+ return {
106
+ ...o,
107
+ discountMinor: num(r.discountMinor),
108
+ shippingDiscountMinor: num(r.shippingDiscountMinor),
109
+ appliedCampaigns: normalizeCampaigns(r.appliedCampaigns),
110
+ lines: (Array.isArray(r.lines) ? r.lines : []).map((l) => ({
111
+ ...l,
112
+ discountMinor: num(l.discountMinor)
113
+ }))
114
+ };
115
+ }
116
+ function normalizeAgreements(a) {
117
+ const q = a.quote;
118
+ const quote = isObject(q) ? {
119
+ subtotalMinor: num(q.subtotalMinor),
120
+ discountMinor: num(q.discountMinor),
121
+ shippingMinor: num(q.shippingMinor),
122
+ shippingDiscountMinor: num(q.shippingDiscountMinor),
123
+ totalMinor: num(q.totalMinor),
124
+ appliedCampaigns: normalizeCampaigns(q.appliedCampaigns),
125
+ pendingCampaigns: normalizePending(q.pendingCampaigns),
126
+ codeReason: normalizeReason(q.codeReason)
127
+ } : null;
128
+ return { ...a, quote };
129
+ }
130
+ function normalizeStore(s) {
131
+ const r = s;
132
+ return { ...s, hasCodeCampaigns: r.hasCodeCampaigns !== false };
133
+ }
134
+
53
135
  // src/errors.ts
54
136
  var API_CODES = /* @__PURE__ */ new Set([
55
137
  "store_not_found",
@@ -74,6 +156,7 @@ var API_CODES = /* @__PURE__ */ new Set([
74
156
  "agreements_changed",
75
157
  "cart_incomplete",
76
158
  "cart_changed",
159
+ "coupon_invalid",
77
160
  "invalid_personalization",
78
161
  "out_of_stock",
79
162
  "amount_out_of_range",
@@ -131,7 +214,7 @@ var StorefrontError = class extends Error {
131
214
  function isStorefrontError(e) {
132
215
  return e instanceof StorefrontError || typeof e === "object" && e !== null && e[ERROR_BRAND] === true;
133
216
  }
134
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
217
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
135
218
  function parseRetryAfter(value) {
136
219
  if (value === null) return void 0;
137
220
  const trimmed = value.trim();
@@ -141,7 +224,7 @@ function parseRetryAfter(value) {
141
224
  return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
142
225
  }
143
226
  function errorFromResponse(status, body, headers) {
144
- const b = isObject(body) ? body : {};
227
+ const b = isObject2(body) ? body : {};
145
228
  const message = typeof b.message === "string" && b.message !== "" ? b.message : `Storefront API request failed (HTTP ${status})`;
146
229
  const error = typeof b.error === "string" ? b.error : null;
147
230
  if (status === 429 && (error === null || !API_CODES.has(error))) {
@@ -174,11 +257,20 @@ function apiError(code, status, message, b) {
174
257
  switch (code) {
175
258
  case "cart_changed":
176
259
  return new StorefrontError(code, status, message, {
177
- lines: arr(b.lines),
260
+ lines: arr(b.lines).map(normalizeCartLine),
178
261
  subtotalMinor: n(b.subtotalMinor),
262
+ discountMinor: n(b.discountMinor),
179
263
  shippingMinor: n(b.shippingMinor),
264
+ shippingDiscountMinor: n(b.shippingDiscountMinor),
180
265
  totalMinor: n(b.totalMinor),
181
- shippingOptions: arr(b.shippingOptions)
266
+ shippingOptions: arr(b.shippingOptions),
267
+ appliedCampaigns: normalizeCampaigns(b.appliedCampaigns),
268
+ pendingCampaigns: normalizePending(b.pendingCampaigns),
269
+ codeReason: normalizeReason(b.codeReason)
270
+ });
271
+ case "coupon_invalid":
272
+ return new StorefrontError(code, status, message, {
273
+ reason: b.reason === "used_up" ? "used_up" : "unknown"
182
274
  });
183
275
  case "invalid_personalization":
184
276
  return new StorefrontError(
@@ -343,26 +435,26 @@ function createStorefrontClient(options) {
343
435
  callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
344
436
  try {
345
437
  let res;
346
- let text;
438
+ let text2;
347
439
  try {
348
440
  res = await Promise.race([doFetch(url, init), deadline]);
349
- text = await Promise.race([res.text(), deadline]);
441
+ text2 = await Promise.race([res.text(), deadline]);
350
442
  } catch (e) {
351
443
  if (e instanceof StorefrontError) throw e;
352
444
  throw transportError(e, timedOut, timeoutMs);
353
445
  }
354
446
  let parsed;
355
447
  let isJson = false;
356
- if (text !== "") {
448
+ if (text2 !== "") {
357
449
  try {
358
- parsed = JSON.parse(text);
450
+ parsed = JSON.parse(text2);
359
451
  isJson = true;
360
452
  } catch {
361
453
  parsed = void 0;
362
454
  }
363
455
  }
364
456
  if (!res.ok) throw errorFromResponse(res.status, parsed, res.headers);
365
- if (!isJson && flags.emptyOk && text === "") return void 0;
457
+ if (!isJson && flags.emptyOk && text2 === "") return void 0;
366
458
  if (!isJson) {
367
459
  throw new StorefrontError(
368
460
  "invalid_response",
@@ -381,10 +473,12 @@ function createStorefrontClient(options) {
381
473
  const acct = { credentials: true };
382
474
  const send = (method, path, body, o, extra = {}, emptyOk = false) => request(method, () => path, body, o, extra, { ...acct, emptyOk });
383
475
  const cart = (id) => `/v1/carts/${seg(id)}`;
476
+ const cartRequest = async (method, path, body, o) => normalizeCart(await request(method, path, body, o));
477
+ const cartGet = (id, o) => cartRequest("GET", () => cart(id), void 0, o);
384
478
  return {
385
479
  getContent: (key, o) => get(() => `/v1/content/${seg(key)}`, o),
386
480
  store: {
387
- get: (o) => get(() => "/v1/store", o)
481
+ get: async (o) => normalizeStore(await get(() => "/v1/store", o))
388
482
  },
389
483
  blog: {
390
484
  list: (query = {}, o) => get(() => {
@@ -415,15 +509,15 @@ function createStorefrontClient(options) {
415
509
  get: (slug, o) => get(() => `/v1/products/${seg(slug)}`, o)
416
510
  },
417
511
  carts: {
418
- create: (o) => request("POST", () => "/v1/carts", void 0, o),
512
+ create: (o) => cartRequest("POST", () => "/v1/carts", void 0, o),
419
513
  recover: (token, o) => request(
420
514
  "POST",
421
515
  () => "/v1/carts/recover",
422
516
  { token },
423
517
  o
424
518
  ),
425
- get: (cartId, o) => get(() => cart(cartId), o),
426
- addLine: (cartId, input, o) => request(
519
+ get: (cartId, o) => cartGet(cartId, o),
520
+ addLine: (cartId, input, o) => cartRequest(
427
521
  "POST",
428
522
  () => `${cart(cartId)}/lines`,
429
523
  {
@@ -435,32 +529,36 @@ function createStorefrontClient(options) {
435
529
  },
436
530
  o
437
531
  ),
438
- updateLine: (cartId, lineId, input, o) => request(
532
+ updateLine: (cartId, lineId, input, o) => cartRequest(
439
533
  "PATCH",
440
534
  () => `${cart(cartId)}/lines/${seg(lineId)}`,
441
535
  { quantity: input.quantity },
442
536
  o
443
537
  ),
444
- removeLine: (cartId, lineId, o) => request(
538
+ removeLine: (cartId, lineId, o) => cartRequest(
445
539
  "DELETE",
446
540
  () => `${cart(cartId)}/lines/${seg(lineId)}`,
447
541
  void 0,
448
542
  o
449
543
  ),
450
- setCustomer: (cartId, input, o) => request("PUT", () => `${cart(cartId)}/customer`, input, o),
451
- setAddress: (cartId, input, o) => request("PUT", () => `${cart(cartId)}/address`, input, o),
544
+ applyCode: (cartId, code, o) => cartRequest("PUT", () => `${cart(cartId)}/coupon`, { code }, o),
545
+ removeCode: (cartId, o) => cartRequest("DELETE", () => `${cart(cartId)}/coupon`, void 0, o),
546
+ setCustomer: (cartId, input, o) => cartRequest("PUT", () => `${cart(cartId)}/customer`, input, o),
547
+ setAddress: (cartId, input, o) => cartRequest("PUT", () => `${cart(cartId)}/address`, input, o),
452
548
  shippingOptions: (cartId, o) => get(() => `${cart(cartId)}/shipping-options`, o),
453
- setShippingOption: (cartId, optionId, o) => request(
549
+ setShippingOption: (cartId, optionId, o) => cartRequest(
454
550
  "PUT",
455
551
  () => `${cart(cartId)}/shipping-option`,
456
552
  { id: optionId },
457
553
  o
458
554
  ),
459
- agreements: (cartId, o) => request(
460
- "POST",
461
- () => `${cart(cartId)}/agreements`,
462
- void 0,
463
- o
555
+ agreements: async (cartId, o) => normalizeAgreements(
556
+ await request(
557
+ "POST",
558
+ () => `${cart(cartId)}/agreements`,
559
+ void 0,
560
+ o
561
+ )
464
562
  ),
465
563
  checkout: async (cartId, o) => {
466
564
  const hash = o?.agreementsHash;
@@ -489,9 +587,11 @@ function createStorefrontClient(options) {
489
587
  }
490
588
  },
491
589
  orders: {
492
- get: (orderId, token, o) => get(
493
- () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,
494
- o
590
+ get: async (orderId, token, o) => normalizeOrder(
591
+ await get(
592
+ () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,
593
+ o
594
+ )
495
595
  ),
496
596
  createReturn: (orderId, token, input, o) => request(
497
597
  "POST",
@@ -849,7 +949,7 @@ async function renderTurnstile(element, siteKey, options) {
849
949
  }
850
950
 
851
951
  // src/index.ts
852
- var SDK_VERSION = "0.9.0";
952
+ var SDK_VERSION = "0.10.0";
853
953
  // Annotate the CommonJS export names for ESM import in node:
854
954
  0 && (module.exports = {
855
955
  BUYER_IP_HEADER,