@usethrottle/cart 3.12.0 → 3.14.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
@@ -144,6 +144,127 @@ button — checkout still works. Omitting `returnUrl` or `cancelUrl` falls back
144
144
  to Throttle's own `/complete` page and this same hosted cart page,
145
145
  respectively.
146
146
 
147
+ ### Resolved carts
148
+
149
+ A resolved cart's lines are priced by an installed app (a line resolver, such
150
+ as Product Catalog), never by the browser. Create the session with
151
+ `lineResolver` and the environment's `currency`, then add lines by
152
+ `referenceId`. Throttle asks the app for the price, stock and limits on every
153
+ add, quantity change, sign-in merge and checkout.
154
+
155
+ ```ts
156
+ import {
157
+ QuantityUnavailableError,
158
+ LineNotPurchasableError,
159
+ LineResolverUnavailableError,
160
+ CartPricesChangedError,
161
+ } from '@usethrottle/cart';
162
+
163
+ await cart.create({
164
+ currency: 'USD', // required with lineResolver; must be the environment's currency
165
+ lineResolver: { extensionId: '0b6a3c1e-8d2f-4a5b-9c7d-1e2f3a4b5c6d' },
166
+ locale: 'en-US', // optional, passed to the app
167
+ });
168
+
169
+ try {
170
+ await cart.addResolvedItem({ referenceId: 'TSHIRT-BLUE-M', quantity: 2 });
171
+ } catch (e) {
172
+ if (e instanceof QuantityUnavailableError) showMessage(`Only ${e.maxQuantity ?? 0} available`);
173
+ else if (e instanceof LineNotPurchasableError) showMessage('No longer available');
174
+ else if (e instanceof LineResolverUnavailableError) showMessage('Try again in a moment');
175
+ else throw e;
176
+ }
177
+
178
+ // Re-check every owned line (for example when the buyer comes back to the cart).
179
+ const { changed, ...current } = await cart.refresh();
180
+
181
+ try {
182
+ const { checkoutUrl } = await cart.checkout({ returnUrl, cancelUrl });
183
+ location.href = checkoutUrl;
184
+ } catch (e) {
185
+ if (e instanceof CartPricesChangedError) {
186
+ // The new prices are already applied; show them, then check out again.
187
+ if (e.cart) render(e.cart);
188
+ } else throw e;
189
+ }
190
+ ```
191
+
192
+ `addResolvedItem()` sends only `referenceId`, `quantity` (default 1) and
193
+ `metadata`. The app sets the name, price and image: sending `unitPrice`,
194
+ `name`, `imageUrl`, `taxAmount`, `discountAmount`, a reserved metadata key
195
+ (`lineResolver`, `requiresShipping`) or a metadata key that changes a shipping
196
+ or tax quote answers `400 price_locked` (`PriceLockedError.fields` names them).
197
+ `updateItem()` keeps working for quantity and other metadata; a quantity change
198
+ is re-checked by the app.
199
+
200
+ A resolved cart carries `lineResolver: { extensionId }` (`extensionId` is
201
+ `null` if the app's installation is gone), and each line carries `resolution`:
202
+ `null` on a line the app does not own, otherwise `{ status, code, maxQuantity,
203
+ minQuantity }`. `status` is `resolved`, `refused` (the app refused the line;
204
+ `code` says why, for example `OUT_OF_STOCK`) or `stale` (the last re-check
205
+ failed; checkout re-checks it). Carts created without `lineResolver` have
206
+ neither key.
207
+
208
+ Shipping on a resolved cart is priced by Throttle, not the browser: pick a
209
+ method Throttle quotes for the cart with
210
+ `cart.selectShippingMethod({ methodId })`, which sends only the method id (the
211
+ cart needs a shipping address first). A method Throttle does not quote answers
212
+ `422 shipping_method_unavailable`. If you use `selectShipping()` instead, a
213
+ `rateAmount` or `currency` different from the quote answers `400
214
+ price_locked`. There is no flat-rate fallback (no selection means shipping
215
+ is not calculated yet). The checkout hand-off re-checks every line and
216
+ re-quotes shipping; any change answers `409 cart_prices_changed` with the
217
+ updated `cart` and, when shipping moved, `shipping: { methodId,
218
+ previousAmount, amount, reason? }` (`amount` is `null` with `reason`
219
+ `method_unavailable` or `quote_unavailable`).
220
+
221
+ #### From your server (`CartClient`)
222
+
223
+ Other apps can integrate the same way with a secret key. Create the cart with
224
+ `lineResolver` (and the environment's `currency`), optionally pricing up to 50
225
+ lines in one call with `lineItems` (all or nothing), then add lines by
226
+ `referenceId`:
227
+
228
+ ```ts
229
+ const cart = await client.carts.create({
230
+ applicationId,
231
+ currency: 'USD',
232
+ lineResolver: { extensionId: '0b6a3c1e-8d2f-4a5b-9c7d-1e2f3a4b5c6d' },
233
+ locale: 'en-GB',
234
+ lineItems: [{ referenceId: 'TSHIRT-BLUE-M', quantity: 2 }],
235
+ });
236
+ const line = await client.items.addResolvedItem(cart.id, { referenceId: 'MUG-WHITE', quantity: 1 });
237
+ ```
238
+
239
+ A server cart has no refresh: `refresh()` exists only on a browser cart
240
+ session (`CartSessionClient`). From the server, a line is re-checked with the
241
+ app when you change its quantity with `items.update(cartId, itemId,
242
+ { quantity })`. To re-check the whole cart, mint a hosted-cart session for it
243
+ (`POST /api/v1/carts/{id}/sessions`, which answers `{ sessionId, cartUrl,
244
+ expiresAt }`) and call `CartSessionClient.forSession(sessionId).refresh()`. An
245
+ owned line's `unitPrice`, `taxAmount`, `discountAmount` and reserved metadata
246
+ keys answer `400 price_locked` for every caller. Both clients throw the same
247
+ typed errors:
248
+
249
+ | Error class | Status / code | Typed fields (`details`) |
250
+ | --- | --- | --- |
251
+ | `PriceLockedError` | `400 price_locked` | `fields` |
252
+ | `QuantityUnavailableError` | `409 quantity_unavailable` | `reason`, `maxQuantity` (or `null`) |
253
+ | `LineNotPurchasableError` | `422 line_not_purchasable` | `reason` on an add; `lines` at checkout |
254
+ | `LineResolverUnavailableError` | `503 line_resolver_unavailable` | `reason` (or `null`); nothing changed, retry |
255
+ | `LineResolverNotAvailableError` | `422 line_resolver_not_available` | `reason`; the app is not installed |
256
+ | `CurrencyNotEnabledError` | `422 currency_not_enabled` | `details.currency`, `details.enabledCurrencies` |
257
+ | `ResolvedLinesRequiredError` | `422 resolved_lines_required` | the store only accepts resolved lines |
258
+ | `LineLimitReachedError` | `422 line_limit_reached` | `details.maxLines` (50 per app) |
259
+ | `CartPricesChangedError` | `409 cart_prices_changed` | `cart`, `shipping` (or `null`) |
260
+ | `ShippingMethodUnavailableError` | `422 shipping_method_unavailable` | |
261
+ | `ShippingQuoteUnavailableError` | `503 shipping_quote_unavailable` | nothing changed, retry |
262
+ | `AmountTooLargeError` | `422 amount_too_large` | lower the quantity |
263
+ | `CartChangedError` | `409 cart_changed` | the cart changed during the add; retry |
264
+
265
+ Every class extends `ThrottleApiError` (and so `ThrottleError`), so existing
266
+ `instanceof ThrottleApiError` and `e.code` checks keep working.
267
+
147
268
  ## Net-N invoice terms
148
269
 
149
270
  Cart-level invoice terms are optional. Pass `netN` on cart create or update to
package/dist/index.cjs CHANGED
@@ -20,11 +20,26 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AmountTooLargeError: () => AmountTooLargeError,
24
+ CartChangedError: () => CartChangedError,
23
25
  CartClient: () => CartClient,
24
26
  CartNotFoundError: () => CartNotFoundError,
25
27
  CartNotOpenError: () => CartNotOpenError,
28
+ CartPricesChangedError: () => CartPricesChangedError,
26
29
  CartSessionClient: () => CartSessionClient,
27
30
  CartTimeoutError: () => CartTimeoutError,
31
+ CurrencyNotEnabledError: () => CurrencyNotEnabledError,
32
+ DiscountCurrencyUnsupportedError: () => DiscountCurrencyUnsupportedError,
33
+ LineLimitReachedError: () => LineLimitReachedError,
34
+ LineNotPurchasableError: () => LineNotPurchasableError,
35
+ LineResolverNotAvailableError: () => LineResolverNotAvailableError,
36
+ LineResolverUnavailableError: () => LineResolverUnavailableError,
37
+ PriceLockedError: () => PriceLockedError,
38
+ QuantityUnavailableError: () => QuantityUnavailableError,
39
+ ResolvedLinesRequiredError: () => ResolvedLinesRequiredError,
40
+ ShippingCurrencyUnsupportedError: () => ShippingCurrencyUnsupportedError,
41
+ ShippingMethodUnavailableError: () => ShippingMethodUnavailableError,
42
+ ShippingQuoteUnavailableError: () => ShippingQuoteUnavailableError,
28
43
  StorefrontQuoteClient: () => StorefrontQuoteClient,
29
44
  ThrottleApiError: () => ThrottleApiError,
30
45
  ThrottleError: () => import_errors2.ThrottleError,
@@ -77,6 +92,147 @@ var CartTimeoutError = class extends import_errors.ThrottleError {
77
92
  this.name = "CartTimeoutError";
78
93
  }
79
94
  };
95
+ function coded(code, statusCode, args) {
96
+ return {
97
+ code,
98
+ statusCode: args.statusCode ?? statusCode,
99
+ message: args.message,
100
+ details: args.details,
101
+ responseHeaders: args.responseHeaders
102
+ };
103
+ }
104
+ var str = (v) => typeof v === "string" ? v : null;
105
+ var num = (v) => typeof v === "number" ? v : null;
106
+ var PriceLockedError = class extends ThrottleApiError {
107
+ /** The refused fields, e.g. `['unitPrice', 'metadata.lineResolver']`. */
108
+ fields;
109
+ constructor(args) {
110
+ super(coded("price_locked", 400, args));
111
+ this.name = "PriceLockedError";
112
+ this.fields = Array.isArray(args.details?.fields) ? args.details.fields : [];
113
+ }
114
+ };
115
+ var QuantityUnavailableError = class extends ThrottleApiError {
116
+ reason;
117
+ maxQuantity;
118
+ constructor(args) {
119
+ super(coded("quantity_unavailable", 409, args));
120
+ this.name = "QuantityUnavailableError";
121
+ this.reason = str(args.details?.reason);
122
+ this.maxQuantity = num(args.details?.maxQuantity);
123
+ }
124
+ };
125
+ var LineNotPurchasableError = class extends ThrottleApiError {
126
+ reason;
127
+ lines;
128
+ constructor(args) {
129
+ super(coded("line_not_purchasable", 422, args));
130
+ this.name = "LineNotPurchasableError";
131
+ this.reason = str(args.details?.reason);
132
+ this.lines = Array.isArray(args.details?.lines) ? args.details.lines : null;
133
+ }
134
+ };
135
+ var LineResolverUnavailableError = class extends ThrottleApiError {
136
+ reason;
137
+ constructor(args) {
138
+ super(coded("line_resolver_unavailable", 503, args));
139
+ this.name = "LineResolverUnavailableError";
140
+ this.reason = str(args.details?.reason);
141
+ }
142
+ };
143
+ var LineResolverNotAvailableError = class extends ThrottleApiError {
144
+ reason;
145
+ constructor(args) {
146
+ super(coded("line_resolver_not_available", 422, args));
147
+ this.name = "LineResolverNotAvailableError";
148
+ this.reason = str(args.details?.reason);
149
+ }
150
+ };
151
+ var CurrencyNotEnabledError = class extends ThrottleApiError {
152
+ constructor(args) {
153
+ super(coded("currency_not_enabled", 422, args));
154
+ this.name = "CurrencyNotEnabledError";
155
+ }
156
+ };
157
+ var ResolvedLinesRequiredError = class extends ThrottleApiError {
158
+ constructor(args) {
159
+ super(coded("resolved_lines_required", 422, args));
160
+ this.name = "ResolvedLinesRequiredError";
161
+ }
162
+ };
163
+ var LineLimitReachedError = class extends ThrottleApiError {
164
+ constructor(args) {
165
+ super(coded("line_limit_reached", 422, args));
166
+ this.name = "LineLimitReachedError";
167
+ }
168
+ };
169
+ var CartPricesChangedError = class extends ThrottleApiError {
170
+ cart;
171
+ shipping;
172
+ constructor(args) {
173
+ super(coded("cart_prices_changed", 409, args));
174
+ this.name = "CartPricesChangedError";
175
+ const d = args.details;
176
+ this.cart = d?.cart && typeof d.cart === "object" ? d.cart : null;
177
+ this.shipping = d?.shipping && typeof d.shipping === "object" ? d.shipping : null;
178
+ }
179
+ };
180
+ var ShippingMethodUnavailableError = class extends ThrottleApiError {
181
+ constructor(args) {
182
+ super(coded("shipping_method_unavailable", 422, args));
183
+ this.name = "ShippingMethodUnavailableError";
184
+ }
185
+ };
186
+ var ShippingQuoteUnavailableError = class extends ThrottleApiError {
187
+ constructor(args) {
188
+ super(coded("shipping_quote_unavailable", 503, args));
189
+ this.name = "ShippingQuoteUnavailableError";
190
+ }
191
+ };
192
+ var AmountTooLargeError = class extends ThrottleApiError {
193
+ constructor(args) {
194
+ super(coded("amount_too_large", 422, args));
195
+ this.name = "AmountTooLargeError";
196
+ }
197
+ };
198
+ var CartChangedError = class extends ThrottleApiError {
199
+ constructor(args) {
200
+ super(coded("cart_changed", 409, args));
201
+ this.name = "CartChangedError";
202
+ }
203
+ };
204
+ var DiscountCurrencyUnsupportedError = class extends ThrottleApiError {
205
+ constructor(args) {
206
+ super(coded("discount_currency_unsupported", 422, args));
207
+ this.name = "DiscountCurrencyUnsupportedError";
208
+ }
209
+ };
210
+ var ShippingCurrencyUnsupportedError = class extends ThrottleApiError {
211
+ shipping;
212
+ constructor(args) {
213
+ super(coded("shipping_currency_unsupported", 422, args));
214
+ this.name = "ShippingCurrencyUnsupportedError";
215
+ const d = args.details;
216
+ this.shipping = d?.shipping && typeof d.shipping === "object" ? d.shipping : null;
217
+ }
218
+ };
219
+ var RESOLVED_CART_ERRORS = {
220
+ price_locked: PriceLockedError,
221
+ quantity_unavailable: QuantityUnavailableError,
222
+ line_not_purchasable: LineNotPurchasableError,
223
+ line_resolver_unavailable: LineResolverUnavailableError,
224
+ line_resolver_not_available: LineResolverNotAvailableError,
225
+ currency_not_enabled: CurrencyNotEnabledError,
226
+ resolved_lines_required: ResolvedLinesRequiredError,
227
+ line_limit_reached: LineLimitReachedError,
228
+ cart_prices_changed: CartPricesChangedError,
229
+ shipping_method_unavailable: ShippingMethodUnavailableError,
230
+ shipping_quote_unavailable: ShippingQuoteUnavailableError,
231
+ amount_too_large: AmountTooLargeError,
232
+ cart_changed: CartChangedError,
233
+ discount_currency_unsupported: DiscountCurrencyUnsupportedError,
234
+ shipping_currency_unsupported: ShippingCurrencyUnsupportedError
235
+ };
80
236
  function cartErrorFromResponse(args) {
81
237
  if (args.statusCode === 409 && args.code === "cart_not_open") {
82
238
  return new CartNotOpenError({
@@ -94,6 +250,15 @@ function cartErrorFromResponse(args) {
94
250
  responseHeaders: args.responseHeaders
95
251
  });
96
252
  }
253
+ const ResolvedCartError = Object.prototype.hasOwnProperty.call(RESOLVED_CART_ERRORS, args.code) ? RESOLVED_CART_ERRORS[args.code] : void 0;
254
+ if (ResolvedCartError) {
255
+ return new ResolvedCartError({
256
+ message: args.message,
257
+ statusCode: args.statusCode,
258
+ details: args.details,
259
+ responseHeaders: args.responseHeaders
260
+ });
261
+ }
97
262
  return new ThrottleApiError(args);
98
263
  }
99
264
 
@@ -151,6 +316,17 @@ var CartClient = class {
151
316
  get items() {
152
317
  return {
153
318
  add: (cartId, input) => this.request("POST", `/api/v1/carts/${segment(cartId)}/items`, input),
319
+ /**
320
+ * Add a line to a resolved cart (one created with `lineResolver`). Only
321
+ * the item, quantity and metadata are sent; the app sets the name, price
322
+ * and image. Refusals throw the typed resolver errors.
323
+ */
324
+ addResolvedItem: (cartId, input) => {
325
+ const body = { referenceId: input.referenceId };
326
+ if (input.quantity !== void 0) body.quantity = input.quantity;
327
+ if (input.metadata !== void 0) body.metadata = input.metadata;
328
+ return this.request("POST", `/api/v1/carts/${segment(cartId)}/items`, body);
329
+ },
154
330
  update: (cartId, itemId, input) => this.request("PATCH", `/api/v1/carts/${segment(cartId)}/items/${segment(itemId)}`, input),
155
331
  remove: (cartId, itemId) => this.request("DELETE", `/api/v1/carts/${segment(cartId)}/items/${segment(itemId)}`)
156
332
  };
@@ -323,6 +499,32 @@ var CartSessionClient = class _CartSessionClient {
323
499
  async addItem(input) {
324
500
  return (await this.request("POST", `${this.basePath()}/items`, input)).cart;
325
501
  }
502
+ /**
503
+ * Add a line to a resolved cart (one created with `lineResolver`). Only the
504
+ * item, quantity and metadata are sent; the app sets the name, price and
505
+ * image. A refusal throws `QuantityUnavailableError`,
506
+ * `LineNotPurchasableError` or `LineResolverUnavailableError`.
507
+ */
508
+ async addResolvedItem(input) {
509
+ const body = { referenceId: input.referenceId };
510
+ if (input.quantity !== void 0) body.quantity = input.quantity;
511
+ if (input.metadata !== void 0) body.metadata = input.metadata;
512
+ return (await this.request("POST", `${this.basePath()}/items`, body)).cart;
513
+ }
514
+ /**
515
+ * Ask the app that prices a resolved cart to re-check every line it owns.
516
+ * `changed` is true when a price, name or refusal changed. An unresolved
517
+ * cart comes back unchanged. Throws `LineResolverUnavailableError` (nothing
518
+ * changed) when the app does not answer.
519
+ */
520
+ async refresh() {
521
+ const data = await this.request(
522
+ "POST",
523
+ `${this.basePath()}/refresh`,
524
+ {}
525
+ );
526
+ return { ...data.cart, changed: data.changed };
527
+ }
326
528
  async updateItem(itemId, input) {
327
529
  return (await this.request(
328
530
  "PATCH",
@@ -336,6 +538,17 @@ var CartSessionClient = class _CartSessionClient {
336
538
  async selectShipping(input) {
337
539
  return (await this.request("POST", `${this.basePath()}/shipping`, input)).cart;
338
540
  }
541
+ /**
542
+ * Pick a shipping method on a resolved cart. Throttle quotes the amount, so
543
+ * only `methodId` is sent. A method Throttle does not quote for the cart
544
+ * (it needs a shipping address first) throws `ShippingMethodUnavailableError`;
545
+ * a failed quote throws `ShippingQuoteUnavailableError`.
546
+ */
547
+ async selectShippingMethod(input) {
548
+ return (await this.request("POST", `${this.basePath()}/shipping`, {
549
+ methodId: input.methodId
550
+ })).cart;
551
+ }
339
552
  async clearShipping() {
340
553
  return (await this.request("DELETE", `${this.basePath()}/shipping`)).cart;
341
554
  }
@@ -424,11 +637,26 @@ var CartSessionClient = class _CartSessionClient {
424
637
  };
425
638
  // Annotate the CommonJS export names for ESM import in node:
426
639
  0 && (module.exports = {
640
+ AmountTooLargeError,
641
+ CartChangedError,
427
642
  CartClient,
428
643
  CartNotFoundError,
429
644
  CartNotOpenError,
645
+ CartPricesChangedError,
430
646
  CartSessionClient,
431
647
  CartTimeoutError,
648
+ CurrencyNotEnabledError,
649
+ DiscountCurrencyUnsupportedError,
650
+ LineLimitReachedError,
651
+ LineNotPurchasableError,
652
+ LineResolverNotAvailableError,
653
+ LineResolverUnavailableError,
654
+ PriceLockedError,
655
+ QuantityUnavailableError,
656
+ ResolvedLinesRequiredError,
657
+ ShippingCurrencyUnsupportedError,
658
+ ShippingMethodUnavailableError,
659
+ ShippingQuoteUnavailableError,
432
660
  StorefrontQuoteClient,
433
661
  ThrottleApiError,
434
662
  ThrottleError,