@usethrottle/cart 3.11.1 → 3.13.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,24 @@ 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
+ LineLimitReachedError: () => LineLimitReachedError,
33
+ LineNotPurchasableError: () => LineNotPurchasableError,
34
+ LineResolverNotAvailableError: () => LineResolverNotAvailableError,
35
+ LineResolverUnavailableError: () => LineResolverUnavailableError,
36
+ PriceLockedError: () => PriceLockedError,
37
+ QuantityUnavailableError: () => QuantityUnavailableError,
38
+ ResolvedLinesRequiredError: () => ResolvedLinesRequiredError,
39
+ ShippingMethodUnavailableError: () => ShippingMethodUnavailableError,
40
+ ShippingQuoteUnavailableError: () => ShippingQuoteUnavailableError,
28
41
  StorefrontQuoteClient: () => StorefrontQuoteClient,
29
42
  ThrottleApiError: () => ThrottleApiError,
30
43
  ThrottleError: () => import_errors2.ThrottleError,
@@ -77,6 +90,130 @@ var CartTimeoutError = class extends import_errors.ThrottleError {
77
90
  this.name = "CartTimeoutError";
78
91
  }
79
92
  };
93
+ function coded(code, statusCode, args) {
94
+ return {
95
+ code,
96
+ statusCode: args.statusCode ?? statusCode,
97
+ message: args.message,
98
+ details: args.details,
99
+ responseHeaders: args.responseHeaders
100
+ };
101
+ }
102
+ var str = (v) => typeof v === "string" ? v : null;
103
+ var num = (v) => typeof v === "number" ? v : null;
104
+ var PriceLockedError = class extends ThrottleApiError {
105
+ /** The refused fields, e.g. `['unitPrice', 'metadata.lineResolver']`. */
106
+ fields;
107
+ constructor(args) {
108
+ super(coded("price_locked", 400, args));
109
+ this.name = "PriceLockedError";
110
+ this.fields = Array.isArray(args.details?.fields) ? args.details.fields : [];
111
+ }
112
+ };
113
+ var QuantityUnavailableError = class extends ThrottleApiError {
114
+ reason;
115
+ maxQuantity;
116
+ constructor(args) {
117
+ super(coded("quantity_unavailable", 409, args));
118
+ this.name = "QuantityUnavailableError";
119
+ this.reason = str(args.details?.reason);
120
+ this.maxQuantity = num(args.details?.maxQuantity);
121
+ }
122
+ };
123
+ var LineNotPurchasableError = class extends ThrottleApiError {
124
+ reason;
125
+ lines;
126
+ constructor(args) {
127
+ super(coded("line_not_purchasable", 422, args));
128
+ this.name = "LineNotPurchasableError";
129
+ this.reason = str(args.details?.reason);
130
+ this.lines = Array.isArray(args.details?.lines) ? args.details.lines : null;
131
+ }
132
+ };
133
+ var LineResolverUnavailableError = class extends ThrottleApiError {
134
+ reason;
135
+ constructor(args) {
136
+ super(coded("line_resolver_unavailable", 503, args));
137
+ this.name = "LineResolverUnavailableError";
138
+ this.reason = str(args.details?.reason);
139
+ }
140
+ };
141
+ var LineResolverNotAvailableError = class extends ThrottleApiError {
142
+ reason;
143
+ constructor(args) {
144
+ super(coded("line_resolver_not_available", 422, args));
145
+ this.name = "LineResolverNotAvailableError";
146
+ this.reason = str(args.details?.reason);
147
+ }
148
+ };
149
+ var CurrencyNotEnabledError = class extends ThrottleApiError {
150
+ constructor(args) {
151
+ super(coded("currency_not_enabled", 422, args));
152
+ this.name = "CurrencyNotEnabledError";
153
+ }
154
+ };
155
+ var ResolvedLinesRequiredError = class extends ThrottleApiError {
156
+ constructor(args) {
157
+ super(coded("resolved_lines_required", 422, args));
158
+ this.name = "ResolvedLinesRequiredError";
159
+ }
160
+ };
161
+ var LineLimitReachedError = class extends ThrottleApiError {
162
+ constructor(args) {
163
+ super(coded("line_limit_reached", 422, args));
164
+ this.name = "LineLimitReachedError";
165
+ }
166
+ };
167
+ var CartPricesChangedError = class extends ThrottleApiError {
168
+ cart;
169
+ shipping;
170
+ constructor(args) {
171
+ super(coded("cart_prices_changed", 409, args));
172
+ this.name = "CartPricesChangedError";
173
+ const d = args.details;
174
+ this.cart = d?.cart && typeof d.cart === "object" ? d.cart : null;
175
+ this.shipping = d?.shipping && typeof d.shipping === "object" ? d.shipping : null;
176
+ }
177
+ };
178
+ var ShippingMethodUnavailableError = class extends ThrottleApiError {
179
+ constructor(args) {
180
+ super(coded("shipping_method_unavailable", 422, args));
181
+ this.name = "ShippingMethodUnavailableError";
182
+ }
183
+ };
184
+ var ShippingQuoteUnavailableError = class extends ThrottleApiError {
185
+ constructor(args) {
186
+ super(coded("shipping_quote_unavailable", 503, args));
187
+ this.name = "ShippingQuoteUnavailableError";
188
+ }
189
+ };
190
+ var AmountTooLargeError = class extends ThrottleApiError {
191
+ constructor(args) {
192
+ super(coded("amount_too_large", 422, args));
193
+ this.name = "AmountTooLargeError";
194
+ }
195
+ };
196
+ var CartChangedError = class extends ThrottleApiError {
197
+ constructor(args) {
198
+ super(coded("cart_changed", 409, args));
199
+ this.name = "CartChangedError";
200
+ }
201
+ };
202
+ var RESOLVED_CART_ERRORS = {
203
+ price_locked: PriceLockedError,
204
+ quantity_unavailable: QuantityUnavailableError,
205
+ line_not_purchasable: LineNotPurchasableError,
206
+ line_resolver_unavailable: LineResolverUnavailableError,
207
+ line_resolver_not_available: LineResolverNotAvailableError,
208
+ currency_not_enabled: CurrencyNotEnabledError,
209
+ resolved_lines_required: ResolvedLinesRequiredError,
210
+ line_limit_reached: LineLimitReachedError,
211
+ cart_prices_changed: CartPricesChangedError,
212
+ shipping_method_unavailable: ShippingMethodUnavailableError,
213
+ shipping_quote_unavailable: ShippingQuoteUnavailableError,
214
+ amount_too_large: AmountTooLargeError,
215
+ cart_changed: CartChangedError
216
+ };
80
217
  function cartErrorFromResponse(args) {
81
218
  if (args.statusCode === 409 && args.code === "cart_not_open") {
82
219
  return new CartNotOpenError({
@@ -94,6 +231,15 @@ function cartErrorFromResponse(args) {
94
231
  responseHeaders: args.responseHeaders
95
232
  });
96
233
  }
234
+ const ResolvedCartError = Object.prototype.hasOwnProperty.call(RESOLVED_CART_ERRORS, args.code) ? RESOLVED_CART_ERRORS[args.code] : void 0;
235
+ if (ResolvedCartError) {
236
+ return new ResolvedCartError({
237
+ message: args.message,
238
+ statusCode: args.statusCode,
239
+ details: args.details,
240
+ responseHeaders: args.responseHeaders
241
+ });
242
+ }
97
243
  return new ThrottleApiError(args);
98
244
  }
99
245
 
@@ -151,6 +297,17 @@ var CartClient = class {
151
297
  get items() {
152
298
  return {
153
299
  add: (cartId, input) => this.request("POST", `/api/v1/carts/${segment(cartId)}/items`, input),
300
+ /**
301
+ * Add a line to a resolved cart (one created with `lineResolver`). Only
302
+ * the item, quantity and metadata are sent; the app sets the name, price
303
+ * and image. Refusals throw the typed resolver errors.
304
+ */
305
+ addResolvedItem: (cartId, input) => {
306
+ const body = { referenceId: input.referenceId };
307
+ if (input.quantity !== void 0) body.quantity = input.quantity;
308
+ if (input.metadata !== void 0) body.metadata = input.metadata;
309
+ return this.request("POST", `/api/v1/carts/${segment(cartId)}/items`, body);
310
+ },
154
311
  update: (cartId, itemId, input) => this.request("PATCH", `/api/v1/carts/${segment(cartId)}/items/${segment(itemId)}`, input),
155
312
  remove: (cartId, itemId) => this.request("DELETE", `/api/v1/carts/${segment(cartId)}/items/${segment(itemId)}`)
156
313
  };
@@ -323,6 +480,32 @@ var CartSessionClient = class _CartSessionClient {
323
480
  async addItem(input) {
324
481
  return (await this.request("POST", `${this.basePath()}/items`, input)).cart;
325
482
  }
483
+ /**
484
+ * Add a line to a resolved cart (one created with `lineResolver`). Only the
485
+ * item, quantity and metadata are sent; the app sets the name, price and
486
+ * image. A refusal throws `QuantityUnavailableError`,
487
+ * `LineNotPurchasableError` or `LineResolverUnavailableError`.
488
+ */
489
+ async addResolvedItem(input) {
490
+ const body = { referenceId: input.referenceId };
491
+ if (input.quantity !== void 0) body.quantity = input.quantity;
492
+ if (input.metadata !== void 0) body.metadata = input.metadata;
493
+ return (await this.request("POST", `${this.basePath()}/items`, body)).cart;
494
+ }
495
+ /**
496
+ * Ask the app that prices a resolved cart to re-check every line it owns.
497
+ * `changed` is true when a price, name or refusal changed. An unresolved
498
+ * cart comes back unchanged. Throws `LineResolverUnavailableError` (nothing
499
+ * changed) when the app does not answer.
500
+ */
501
+ async refresh() {
502
+ const data = await this.request(
503
+ "POST",
504
+ `${this.basePath()}/refresh`,
505
+ {}
506
+ );
507
+ return { ...data.cart, changed: data.changed };
508
+ }
326
509
  async updateItem(itemId, input) {
327
510
  return (await this.request(
328
511
  "PATCH",
@@ -336,6 +519,17 @@ var CartSessionClient = class _CartSessionClient {
336
519
  async selectShipping(input) {
337
520
  return (await this.request("POST", `${this.basePath()}/shipping`, input)).cart;
338
521
  }
522
+ /**
523
+ * Pick a shipping method on a resolved cart. Throttle quotes the amount, so
524
+ * only `methodId` is sent. A method Throttle does not quote for the cart
525
+ * (it needs a shipping address first) throws `ShippingMethodUnavailableError`;
526
+ * a failed quote throws `ShippingQuoteUnavailableError`.
527
+ */
528
+ async selectShippingMethod(input) {
529
+ return (await this.request("POST", `${this.basePath()}/shipping`, {
530
+ methodId: input.methodId
531
+ })).cart;
532
+ }
339
533
  async clearShipping() {
340
534
  return (await this.request("DELETE", `${this.basePath()}/shipping`)).cart;
341
535
  }
@@ -424,11 +618,24 @@ var CartSessionClient = class _CartSessionClient {
424
618
  };
425
619
  // Annotate the CommonJS export names for ESM import in node:
426
620
  0 && (module.exports = {
621
+ AmountTooLargeError,
622
+ CartChangedError,
427
623
  CartClient,
428
624
  CartNotFoundError,
429
625
  CartNotOpenError,
626
+ CartPricesChangedError,
430
627
  CartSessionClient,
431
628
  CartTimeoutError,
629
+ CurrencyNotEnabledError,
630
+ LineLimitReachedError,
631
+ LineNotPurchasableError,
632
+ LineResolverNotAvailableError,
633
+ LineResolverUnavailableError,
634
+ PriceLockedError,
635
+ QuantityUnavailableError,
636
+ ResolvedLinesRequiredError,
637
+ ShippingMethodUnavailableError,
638
+ ShippingQuoteUnavailableError,
432
639
  StorefrontQuoteClient,
433
640
  ThrottleApiError,
434
641
  ThrottleError,