@usethrottle/cart 3.18.0 → 3.20.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 +2 -0
- package/dist/index.cjs +84 -5
- package/dist/index.d.cts +89 -4
- package/dist/index.d.ts +89 -4
- package/dist/index.js +84 -5
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -89,6 +89,8 @@ await cart.create({ currency: 'USD' });
|
|
|
89
89
|
|
|
90
90
|
await cart.addItem({ name: 'Premium Widget', unitPrice: 2999, quantity: 2 });
|
|
91
91
|
await cart.applyDiscount('SAVE10');
|
|
92
|
+
// A cart holds one goods code and one free-shipping code. With both applied, name the one to remove:
|
|
93
|
+
// await cart.removeDiscount({ kind: 'shipping' }); // or 'order', or { code: 'SHIPFREE' }
|
|
92
94
|
await cart.selectShipping({ methodId: 'fedex_ground', displayName: 'FedEx Ground', rateAmount: 599 });
|
|
93
95
|
|
|
94
96
|
// Set buyer-editable fields. `customerEmail` is what makes a guest cart
|
package/dist/index.cjs
CHANGED
|
@@ -328,6 +328,76 @@ function cartErrorFromResponse(args) {
|
|
|
328
328
|
return new ThrottleApiError(args);
|
|
329
329
|
}
|
|
330
330
|
|
|
331
|
+
// src/analytics-context.ts
|
|
332
|
+
var LONG_KEYS = ["landingPage", "referrer"];
|
|
333
|
+
var SHORT_KEYS = [
|
|
334
|
+
"utmSource",
|
|
335
|
+
"utmMedium",
|
|
336
|
+
"utmCampaign",
|
|
337
|
+
"utmTerm",
|
|
338
|
+
"utmContent",
|
|
339
|
+
"gclid",
|
|
340
|
+
"fbclid",
|
|
341
|
+
"msclkid",
|
|
342
|
+
"ttclid",
|
|
343
|
+
"gaClientId",
|
|
344
|
+
"gaSessionId",
|
|
345
|
+
"fbp",
|
|
346
|
+
"fbc"
|
|
347
|
+
];
|
|
348
|
+
var CONSENT_KEYS = ["analytics", "marketing", "adUserData", "adPersonalization"];
|
|
349
|
+
var MAX_SHORT = 512;
|
|
350
|
+
var MAX_LONG = 2048;
|
|
351
|
+
var MAX_BYTES = 8192;
|
|
352
|
+
function sanitize(raw) {
|
|
353
|
+
const out = {};
|
|
354
|
+
const take = (keys, max) => {
|
|
355
|
+
for (const key of keys) {
|
|
356
|
+
const v = raw[key];
|
|
357
|
+
if (typeof v !== "string") continue;
|
|
358
|
+
const t = v.trim().slice(0, max).trim();
|
|
359
|
+
if (t) out[key] = t;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
take(LONG_KEYS, MAX_LONG);
|
|
363
|
+
take(SHORT_KEYS, MAX_SHORT);
|
|
364
|
+
const consent = raw.consent;
|
|
365
|
+
if (consent && typeof consent === "object") {
|
|
366
|
+
const c = {};
|
|
367
|
+
for (const key of CONSENT_KEYS) {
|
|
368
|
+
const v = consent[key];
|
|
369
|
+
if (typeof v === "boolean") c[key] = v;
|
|
370
|
+
}
|
|
371
|
+
if (Object.keys(c).length > 0) out.consent = c;
|
|
372
|
+
}
|
|
373
|
+
if (Object.keys(out).length === 0) return void 0;
|
|
374
|
+
if (new TextEncoder().encode(JSON.stringify(out)).length > MAX_BYTES) return void 0;
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
function withAnalyticsContext(input) {
|
|
378
|
+
if (input.clientContext !== void 0) return input;
|
|
379
|
+
try {
|
|
380
|
+
const throttle = globalThis.Throttle;
|
|
381
|
+
const fn = throttle?.analyticsContext;
|
|
382
|
+
if (typeof fn !== "function") return input;
|
|
383
|
+
const raw = fn.call(throttle);
|
|
384
|
+
if (!raw || typeof raw !== "object") return input;
|
|
385
|
+
const clientContext = sanitize(raw);
|
|
386
|
+
return clientContext ? { ...input, clientContext } : input;
|
|
387
|
+
} catch {
|
|
388
|
+
return input;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// src/discount-query.ts
|
|
393
|
+
function removeDiscountQuery(opts) {
|
|
394
|
+
const query = new URLSearchParams();
|
|
395
|
+
if (opts?.kind) query.set("kind", opts.kind);
|
|
396
|
+
if (opts?.code) query.set("code", opts.code);
|
|
397
|
+
const text = query.toString();
|
|
398
|
+
return text ? `?${text}` : "";
|
|
399
|
+
}
|
|
400
|
+
|
|
331
401
|
// src/client.ts
|
|
332
402
|
function segment(value) {
|
|
333
403
|
return encodeURIComponent(value);
|
|
@@ -375,7 +445,7 @@ var CartClient = class {
|
|
|
375
445
|
create: (input) => this.request("POST", "/api/v1/carts", input),
|
|
376
446
|
get: (id) => this.request("GET", `/api/v1/carts/${segment(id)}`),
|
|
377
447
|
update: (id, input) => this.request("PATCH", `/api/v1/carts/${segment(id)}`, input),
|
|
378
|
-
checkout: (id, input) => this.request("POST", `/api/v1/carts/${segment(id)}/checkout`, input ?? {}),
|
|
448
|
+
checkout: (id, input) => this.request("POST", `/api/v1/carts/${segment(id)}/checkout`, withAnalyticsContext(input ?? {})),
|
|
379
449
|
merge: (id, customerId) => this.request("POST", `/api/v1/carts/${segment(id)}/merge`, { customerId })
|
|
380
450
|
};
|
|
381
451
|
}
|
|
@@ -406,7 +476,12 @@ var CartClient = class {
|
|
|
406
476
|
get discounts() {
|
|
407
477
|
return {
|
|
408
478
|
apply: (cartId, code) => this.request("POST", `/api/v1/carts/${segment(cartId)}/apply-discount`, { code }),
|
|
409
|
-
|
|
479
|
+
/**
|
|
480
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code:
|
|
481
|
+
* with both applied, name one with `kind` or `code` (else
|
|
482
|
+
* 400 `discount_kind_required`).
|
|
483
|
+
*/
|
|
484
|
+
remove: (cartId, opts) => this.request("DELETE", `/api/v1/carts/${segment(cartId)}/discount${removeDiscountQuery(opts)}`)
|
|
410
485
|
};
|
|
411
486
|
}
|
|
412
487
|
get taxLines() {
|
|
@@ -621,8 +696,12 @@ var CartSessionClient = class _CartSessionClient {
|
|
|
621
696
|
async applyDiscount(code) {
|
|
622
697
|
return (await this.request("POST", `${this.basePath()}/discount`, { code })).cart;
|
|
623
698
|
}
|
|
624
|
-
|
|
625
|
-
|
|
699
|
+
/**
|
|
700
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code: with
|
|
701
|
+
* both applied, name one with `kind` or `code` (else 400 `discount_kind_required`).
|
|
702
|
+
*/
|
|
703
|
+
async removeDiscount(opts) {
|
|
704
|
+
return (await this.request("DELETE", `${this.basePath()}/discount${removeDiscountQuery(opts)}`)).cart;
|
|
626
705
|
}
|
|
627
706
|
/** Set buyer-editable cart fields. Pass `null` to clear one. */
|
|
628
707
|
async update(input) {
|
|
@@ -658,7 +737,7 @@ var CartSessionClient = class _CartSessionClient {
|
|
|
658
737
|
}
|
|
659
738
|
/** Hand off to hosted/embedded checkout. Marks the session converted (no more edits). */
|
|
660
739
|
checkout(input) {
|
|
661
|
-
return this.request("POST", `${this.basePath()}/checkout-session`, input);
|
|
740
|
+
return this.request("POST", `${this.basePath()}/checkout-session`, withAnalyticsContext(input));
|
|
662
741
|
}
|
|
663
742
|
basePath() {
|
|
664
743
|
if (!this.sessionId) {
|
package/dist/index.d.cts
CHANGED
|
@@ -45,7 +45,10 @@ interface Cart {
|
|
|
45
45
|
subtotal: number;
|
|
46
46
|
taxTotal: number;
|
|
47
47
|
discountTotal: number;
|
|
48
|
+
/** Net shipping the buyer pays: already reduced by `shippingDiscountTotal`. */
|
|
48
49
|
shippingTotal: number;
|
|
50
|
+
/** What a free-shipping code took off shipping, in minor units (0 when none). Original shipping is `shippingTotal + shippingDiscountTotal`. */
|
|
51
|
+
shippingDiscountTotal?: number;
|
|
49
52
|
total: number;
|
|
50
53
|
netN: number | null;
|
|
51
54
|
billingAddress: CartAddress | null;
|
|
@@ -59,7 +62,10 @@ interface Cart {
|
|
|
59
62
|
externalMetadata: Record<string, unknown>;
|
|
60
63
|
};
|
|
61
64
|
selectedShipping?: SelectedShipping | null;
|
|
65
|
+
/** The goods code. A free-shipping code is `appliedShippingDiscount`. */
|
|
62
66
|
appliedDiscount?: AppliedDiscount | null;
|
|
67
|
+
/** The cart's free-shipping code and how it stands, or `null` when the cart holds none. */
|
|
68
|
+
appliedShippingDiscount: AppliedShippingDiscount | null;
|
|
63
69
|
taxLines?: TaxLine[];
|
|
64
70
|
lineItems?: LineItem[];
|
|
65
71
|
createdAt: string;
|
|
@@ -229,6 +235,8 @@ interface SelectShippingMethodInput {
|
|
|
229
235
|
}
|
|
230
236
|
interface SelectedShipping {
|
|
231
237
|
methodId: string;
|
|
238
|
+
/** The connected adapter of a live carrier rate; absent when none was sent. */
|
|
239
|
+
provider?: string;
|
|
232
240
|
carrier: string | null;
|
|
233
241
|
serviceCode: string | null;
|
|
234
242
|
displayName: string;
|
|
@@ -242,10 +250,56 @@ interface AppliedDiscount {
|
|
|
242
250
|
type: 'percentage' | 'fixed_amount';
|
|
243
251
|
amount: number;
|
|
244
252
|
currency: CurrencyCode;
|
|
245
|
-
|
|
253
|
+
/** @deprecated Always `false`: a free-shipping code is `appliedShippingDiscount`, not the goods code. Use `appliedShippingDiscount`. */
|
|
254
|
+
freeShipping?: boolean;
|
|
246
255
|
validUntil: string | null;
|
|
247
256
|
snapshotHash: string;
|
|
248
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* A shipping option a free-shipping code makes free: a native shipping method,
|
|
260
|
+
* or a live carrier service of a connected shipping provider.
|
|
261
|
+
*/
|
|
262
|
+
type ShippingTarget = {
|
|
263
|
+
kind: 'method';
|
|
264
|
+
methodId: string;
|
|
265
|
+
} | {
|
|
266
|
+
kind: 'carrier_service';
|
|
267
|
+
provider: string;
|
|
268
|
+
carrier: string;
|
|
269
|
+
serviceCode: string;
|
|
270
|
+
};
|
|
271
|
+
/** Where a cart's free-shipping code stands against its address and shipping option. */
|
|
272
|
+
type AppliedShippingDiscountStatus = 'applied' | 'not_eligible' | 'pending_address' | 'pending_shipping' | 'merchant_applies';
|
|
273
|
+
/**
|
|
274
|
+
* The cart's free-shipping code (the goods code stays `appliedDiscount`).
|
|
275
|
+
* `zoneIds`, `targets` and `cap` are the code's rules, so a custom checkout can
|
|
276
|
+
* explain them; `null` means all regions, any option, or free in full.
|
|
277
|
+
*/
|
|
278
|
+
interface AppliedShippingDiscount {
|
|
279
|
+
discountId: string;
|
|
280
|
+
code: string;
|
|
281
|
+
/** The reduction the cart carries now, in minor units. */
|
|
282
|
+
amount: number;
|
|
283
|
+
status: AppliedShippingDiscountStatus;
|
|
284
|
+
/** Why the code does not apply, when `status` is `not_eligible`. */
|
|
285
|
+
reason?: 'zone' | 'shipping_option' | 'minimum_order';
|
|
286
|
+
/** How much more the order needs to reach the minimum, when `reason` is `minimum_order`. */
|
|
287
|
+
amountToMinimum?: number;
|
|
288
|
+
zoneIds: string[] | null;
|
|
289
|
+
targets: ShippingTarget[] | null;
|
|
290
|
+
cap: number | null;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Which code to take off a cart that holds a goods code and a free-shipping
|
|
294
|
+
* code. With both applied and neither given the API answers
|
|
295
|
+
* 400 `discount_kind_required`.
|
|
296
|
+
*/
|
|
297
|
+
interface RemoveDiscountOptions {
|
|
298
|
+
/** `order` removes the goods code, `shipping` the free-shipping code. */
|
|
299
|
+
kind?: 'order' | 'shipping';
|
|
300
|
+
/** Remove this code (case-insensitive). */
|
|
301
|
+
code?: string;
|
|
302
|
+
}
|
|
249
303
|
interface TaxLine {
|
|
250
304
|
id: string;
|
|
251
305
|
lineItemId: string;
|
|
@@ -362,6 +416,8 @@ interface SelectShippingInput {
|
|
|
362
416
|
displayName: string;
|
|
363
417
|
rateAmount: number;
|
|
364
418
|
currency?: string;
|
|
419
|
+
/** Connected shipping adapter id of a live carrier rate (`shippo`, `ups`); a free-shipping carrier target matches on it. */
|
|
420
|
+
provider?: string;
|
|
365
421
|
carrier?: string;
|
|
366
422
|
serviceCode?: string;
|
|
367
423
|
estimatedDeliveryDays?: number;
|
|
@@ -382,6 +438,8 @@ interface CheckoutInput {
|
|
|
382
438
|
termsSnapshot?: string;
|
|
383
439
|
invoiceNumber?: string;
|
|
384
440
|
metadata?: Record<string, unknown>;
|
|
441
|
+
/** The buyer's GA4 ids, UTMs and consent. Defaults to `Throttle.analyticsContext()` when that exists. */
|
|
442
|
+
clientContext?: Record<string, unknown>;
|
|
385
443
|
}
|
|
386
444
|
interface Order {
|
|
387
445
|
id: string;
|
|
@@ -439,6 +497,8 @@ interface ShippingTaxCartCalculateInput {
|
|
|
439
497
|
}
|
|
440
498
|
interface ShippingTaxMethod {
|
|
441
499
|
id: string;
|
|
500
|
+
/** A native method's stable key: what a free-shipping `method` target names (`id` changes on every shipping save). */
|
|
501
|
+
stableKey?: string;
|
|
442
502
|
type?: 'ship' | 'pickup';
|
|
443
503
|
label: string;
|
|
444
504
|
amount: number;
|
|
@@ -446,6 +506,16 @@ interface ShippingTaxMethod {
|
|
|
446
506
|
deliveryWindowLabel?: string | null;
|
|
447
507
|
deliveryMinDays?: number | null;
|
|
448
508
|
deliveryMaxDays?: number | null;
|
|
509
|
+
/** Who a live carrier rate came from. Absent on a manual zone method. */
|
|
510
|
+
provider?: string;
|
|
511
|
+
carrier?: string;
|
|
512
|
+
serviceCode?: string;
|
|
513
|
+
/**
|
|
514
|
+
* What the buyer would pay for this option with the cart's free-shipping code
|
|
515
|
+
* applied. Present only when the code would apply to it; `amount` stays the
|
|
516
|
+
* full price.
|
|
517
|
+
*/
|
|
518
|
+
discountedAmount?: number;
|
|
449
519
|
warnings?: Array<{
|
|
450
520
|
code: string;
|
|
451
521
|
message: string;
|
|
@@ -502,7 +572,11 @@ interface ShippingTaxCalculationResponse {
|
|
|
502
572
|
shippingTotal: number;
|
|
503
573
|
taxTotal: number;
|
|
504
574
|
total: number;
|
|
575
|
+
/** What a free-shipping code took off shipping; present only on a cart holding one. */
|
|
576
|
+
shippingDiscountTotal?: number;
|
|
505
577
|
};
|
|
578
|
+
/** The cart's free-shipping code and how it stands; absent on a cart holding none. */
|
|
579
|
+
appliedShippingDiscount?: AppliedShippingDiscount | null;
|
|
506
580
|
/**
|
|
507
581
|
* Verbatim messaging the tax engine returned about this transaction. In
|
|
508
582
|
* several EU member states the engine's own wording is what makes the
|
|
@@ -582,7 +656,12 @@ declare class CartClient {
|
|
|
582
656
|
};
|
|
583
657
|
get discounts(): {
|
|
584
658
|
apply: (cartId: string, code: string) => Promise<Cart>;
|
|
585
|
-
|
|
659
|
+
/**
|
|
660
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code:
|
|
661
|
+
* with both applied, name one with `kind` or `code` (else
|
|
662
|
+
* 400 `discount_kind_required`).
|
|
663
|
+
*/
|
|
664
|
+
remove: (cartId: string, opts?: RemoveDiscountOptions) => Promise<Cart>;
|
|
586
665
|
};
|
|
587
666
|
get taxLines(): {
|
|
588
667
|
set: (cartId: string, lines: TaxLineInput[]) => Promise<Cart>;
|
|
@@ -731,6 +810,8 @@ interface CheckoutHandoffInput {
|
|
|
731
810
|
* checkout returns to a live cart. Throttle's own hosted cart page sets this.
|
|
732
811
|
*/
|
|
733
812
|
keepOpen?: boolean;
|
|
813
|
+
/** The buyer's GA4 ids, UTMs and consent. Defaults to `Throttle.analyticsContext()` when that exists. */
|
|
814
|
+
clientContext?: Record<string, unknown>;
|
|
734
815
|
}
|
|
735
816
|
interface CheckoutHandoff {
|
|
736
817
|
cartSessionId: string;
|
|
@@ -794,7 +875,11 @@ declare class CartSessionClient {
|
|
|
794
875
|
selectShippingMethod(input: SelectShippingMethodInput): Promise<CartSessionCart>;
|
|
795
876
|
clearShipping(): Promise<CartSessionCart>;
|
|
796
877
|
applyDiscount(code: string): Promise<CartSessionCart>;
|
|
797
|
-
|
|
878
|
+
/**
|
|
879
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code: with
|
|
880
|
+
* both applied, name one with `kind` or `code` (else 400 `discount_kind_required`).
|
|
881
|
+
*/
|
|
882
|
+
removeDiscount(opts?: RemoveDiscountOptions): Promise<CartSessionCart>;
|
|
798
883
|
/** Set buyer-editable cart fields. Pass `null` to clear one. */
|
|
799
884
|
update(input: UpdateCartSessionInput): Promise<CartSessionCart>;
|
|
800
885
|
/**
|
|
@@ -1129,4 +1214,4 @@ declare function cartErrorFromResponse(args: {
|
|
|
1129
1214
|
responseHeaders?: ThrottleErrorArgs['responseHeaders'];
|
|
1130
1215
|
}): ThrottleApiError;
|
|
1131
1216
|
|
|
1132
|
-
export { type AddLineItemInput, type AddResolvedLineItemInput, AmountTooLargeError, type AppliedDiscount, type Cart, type CartAddress, type CartBranding, CartChangedError, CartClient, type CartErrorArgs, type CartEvent, CartNotFoundError, CartNotOpenError, type CartPricesChangedDetails, CartPricesChangedError, type CartSession, type CartSessionCart, CartSessionClient, type CartSessionClientOptions, type CartSessionSummary, type CartShippingChange, CartTimeoutError, type CheckoutHandoff, type CheckoutHandoffInput, type CheckoutInput, type CreateCartInput, type CreateCartSessionInput, CurrencyLockedError, CurrencyNotAvailableInProductionError, type CurrencyNotEnabledDetails, CurrencyNotEnabledError, CurrencyNotPayableError, CurrencyNotSupportedError, DiscountCurrencyUnsupportedError, type ExternalShippingTaxSnapshotInput, type LegacyLineRecurring, type LineItem, type LineLimitReachedDetails, LineLimitReachedError, type LineNotPurchasableDetails, LineNotPurchasableError, type LineRecurringInput, type LineResolution, type LineResolverNotAvailableDetails, LineResolverNotAvailableError, type LineResolverUnavailableDetails, LineResolverUnavailableError, type Order, type PriceLockedDetails, PriceLockedError, type QuantityUnavailableDetails, QuantityUnavailableError, QuoteAmountsNeedReviewError, type RefusedCartLine, ResolvedLinesRequiredError, type SelectShippingInput, type SelectShippingMethodInput, type SelectedShipping, ShippingCurrencyUnsupportedError, ShippingMethodUnavailableError, ShippingQuoteUnavailableError, type ShippingTaxAddress, type ShippingTaxCalculationResponse, type ShippingTaxCartCalculateInput, type ShippingTaxMethod, type ShippingTaxQuoteInput, type ShippingTaxQuoteItem, type StoredLineRecurring, StorefrontQuoteClient, type SubscriptionInterval, type SubscriptionIntervalUnit, type TaxLine, type TaxLineInput, ThrottleApiError, type UpdateCartInput, type UpdateCartSessionInput, type UpdateLineItemInput, cartErrorFromResponse };
|
|
1217
|
+
export { type AddLineItemInput, type AddResolvedLineItemInput, AmountTooLargeError, type AppliedDiscount, type AppliedShippingDiscount, type AppliedShippingDiscountStatus, type Cart, type CartAddress, type CartBranding, CartChangedError, CartClient, type CartErrorArgs, type CartEvent, CartNotFoundError, CartNotOpenError, type CartPricesChangedDetails, CartPricesChangedError, type CartSession, type CartSessionCart, CartSessionClient, type CartSessionClientOptions, type CartSessionSummary, type CartShippingChange, CartTimeoutError, type CheckoutHandoff, type CheckoutHandoffInput, type CheckoutInput, type CreateCartInput, type CreateCartSessionInput, CurrencyLockedError, CurrencyNotAvailableInProductionError, type CurrencyNotEnabledDetails, CurrencyNotEnabledError, CurrencyNotPayableError, CurrencyNotSupportedError, DiscountCurrencyUnsupportedError, type ExternalShippingTaxSnapshotInput, type LegacyLineRecurring, type LineItem, type LineLimitReachedDetails, LineLimitReachedError, type LineNotPurchasableDetails, LineNotPurchasableError, type LineRecurringInput, type LineResolution, type LineResolverNotAvailableDetails, LineResolverNotAvailableError, type LineResolverUnavailableDetails, LineResolverUnavailableError, type Order, type PriceLockedDetails, PriceLockedError, type QuantityUnavailableDetails, QuantityUnavailableError, QuoteAmountsNeedReviewError, type RefusedCartLine, type RemoveDiscountOptions, ResolvedLinesRequiredError, type SelectShippingInput, type SelectShippingMethodInput, type SelectedShipping, ShippingCurrencyUnsupportedError, ShippingMethodUnavailableError, ShippingQuoteUnavailableError, type ShippingTarget, type ShippingTaxAddress, type ShippingTaxCalculationResponse, type ShippingTaxCartCalculateInput, type ShippingTaxMethod, type ShippingTaxQuoteInput, type ShippingTaxQuoteItem, type StoredLineRecurring, StorefrontQuoteClient, type SubscriptionInterval, type SubscriptionIntervalUnit, type TaxLine, type TaxLineInput, ThrottleApiError, type UpdateCartInput, type UpdateCartSessionInput, type UpdateLineItemInput, cartErrorFromResponse };
|
package/dist/index.d.ts
CHANGED
|
@@ -45,7 +45,10 @@ interface Cart {
|
|
|
45
45
|
subtotal: number;
|
|
46
46
|
taxTotal: number;
|
|
47
47
|
discountTotal: number;
|
|
48
|
+
/** Net shipping the buyer pays: already reduced by `shippingDiscountTotal`. */
|
|
48
49
|
shippingTotal: number;
|
|
50
|
+
/** What a free-shipping code took off shipping, in minor units (0 when none). Original shipping is `shippingTotal + shippingDiscountTotal`. */
|
|
51
|
+
shippingDiscountTotal?: number;
|
|
49
52
|
total: number;
|
|
50
53
|
netN: number | null;
|
|
51
54
|
billingAddress: CartAddress | null;
|
|
@@ -59,7 +62,10 @@ interface Cart {
|
|
|
59
62
|
externalMetadata: Record<string, unknown>;
|
|
60
63
|
};
|
|
61
64
|
selectedShipping?: SelectedShipping | null;
|
|
65
|
+
/** The goods code. A free-shipping code is `appliedShippingDiscount`. */
|
|
62
66
|
appliedDiscount?: AppliedDiscount | null;
|
|
67
|
+
/** The cart's free-shipping code and how it stands, or `null` when the cart holds none. */
|
|
68
|
+
appliedShippingDiscount: AppliedShippingDiscount | null;
|
|
63
69
|
taxLines?: TaxLine[];
|
|
64
70
|
lineItems?: LineItem[];
|
|
65
71
|
createdAt: string;
|
|
@@ -229,6 +235,8 @@ interface SelectShippingMethodInput {
|
|
|
229
235
|
}
|
|
230
236
|
interface SelectedShipping {
|
|
231
237
|
methodId: string;
|
|
238
|
+
/** The connected adapter of a live carrier rate; absent when none was sent. */
|
|
239
|
+
provider?: string;
|
|
232
240
|
carrier: string | null;
|
|
233
241
|
serviceCode: string | null;
|
|
234
242
|
displayName: string;
|
|
@@ -242,10 +250,56 @@ interface AppliedDiscount {
|
|
|
242
250
|
type: 'percentage' | 'fixed_amount';
|
|
243
251
|
amount: number;
|
|
244
252
|
currency: CurrencyCode;
|
|
245
|
-
|
|
253
|
+
/** @deprecated Always `false`: a free-shipping code is `appliedShippingDiscount`, not the goods code. Use `appliedShippingDiscount`. */
|
|
254
|
+
freeShipping?: boolean;
|
|
246
255
|
validUntil: string | null;
|
|
247
256
|
snapshotHash: string;
|
|
248
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* A shipping option a free-shipping code makes free: a native shipping method,
|
|
260
|
+
* or a live carrier service of a connected shipping provider.
|
|
261
|
+
*/
|
|
262
|
+
type ShippingTarget = {
|
|
263
|
+
kind: 'method';
|
|
264
|
+
methodId: string;
|
|
265
|
+
} | {
|
|
266
|
+
kind: 'carrier_service';
|
|
267
|
+
provider: string;
|
|
268
|
+
carrier: string;
|
|
269
|
+
serviceCode: string;
|
|
270
|
+
};
|
|
271
|
+
/** Where a cart's free-shipping code stands against its address and shipping option. */
|
|
272
|
+
type AppliedShippingDiscountStatus = 'applied' | 'not_eligible' | 'pending_address' | 'pending_shipping' | 'merchant_applies';
|
|
273
|
+
/**
|
|
274
|
+
* The cart's free-shipping code (the goods code stays `appliedDiscount`).
|
|
275
|
+
* `zoneIds`, `targets` and `cap` are the code's rules, so a custom checkout can
|
|
276
|
+
* explain them; `null` means all regions, any option, or free in full.
|
|
277
|
+
*/
|
|
278
|
+
interface AppliedShippingDiscount {
|
|
279
|
+
discountId: string;
|
|
280
|
+
code: string;
|
|
281
|
+
/** The reduction the cart carries now, in minor units. */
|
|
282
|
+
amount: number;
|
|
283
|
+
status: AppliedShippingDiscountStatus;
|
|
284
|
+
/** Why the code does not apply, when `status` is `not_eligible`. */
|
|
285
|
+
reason?: 'zone' | 'shipping_option' | 'minimum_order';
|
|
286
|
+
/** How much more the order needs to reach the minimum, when `reason` is `minimum_order`. */
|
|
287
|
+
amountToMinimum?: number;
|
|
288
|
+
zoneIds: string[] | null;
|
|
289
|
+
targets: ShippingTarget[] | null;
|
|
290
|
+
cap: number | null;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Which code to take off a cart that holds a goods code and a free-shipping
|
|
294
|
+
* code. With both applied and neither given the API answers
|
|
295
|
+
* 400 `discount_kind_required`.
|
|
296
|
+
*/
|
|
297
|
+
interface RemoveDiscountOptions {
|
|
298
|
+
/** `order` removes the goods code, `shipping` the free-shipping code. */
|
|
299
|
+
kind?: 'order' | 'shipping';
|
|
300
|
+
/** Remove this code (case-insensitive). */
|
|
301
|
+
code?: string;
|
|
302
|
+
}
|
|
249
303
|
interface TaxLine {
|
|
250
304
|
id: string;
|
|
251
305
|
lineItemId: string;
|
|
@@ -362,6 +416,8 @@ interface SelectShippingInput {
|
|
|
362
416
|
displayName: string;
|
|
363
417
|
rateAmount: number;
|
|
364
418
|
currency?: string;
|
|
419
|
+
/** Connected shipping adapter id of a live carrier rate (`shippo`, `ups`); a free-shipping carrier target matches on it. */
|
|
420
|
+
provider?: string;
|
|
365
421
|
carrier?: string;
|
|
366
422
|
serviceCode?: string;
|
|
367
423
|
estimatedDeliveryDays?: number;
|
|
@@ -382,6 +438,8 @@ interface CheckoutInput {
|
|
|
382
438
|
termsSnapshot?: string;
|
|
383
439
|
invoiceNumber?: string;
|
|
384
440
|
metadata?: Record<string, unknown>;
|
|
441
|
+
/** The buyer's GA4 ids, UTMs and consent. Defaults to `Throttle.analyticsContext()` when that exists. */
|
|
442
|
+
clientContext?: Record<string, unknown>;
|
|
385
443
|
}
|
|
386
444
|
interface Order {
|
|
387
445
|
id: string;
|
|
@@ -439,6 +497,8 @@ interface ShippingTaxCartCalculateInput {
|
|
|
439
497
|
}
|
|
440
498
|
interface ShippingTaxMethod {
|
|
441
499
|
id: string;
|
|
500
|
+
/** A native method's stable key: what a free-shipping `method` target names (`id` changes on every shipping save). */
|
|
501
|
+
stableKey?: string;
|
|
442
502
|
type?: 'ship' | 'pickup';
|
|
443
503
|
label: string;
|
|
444
504
|
amount: number;
|
|
@@ -446,6 +506,16 @@ interface ShippingTaxMethod {
|
|
|
446
506
|
deliveryWindowLabel?: string | null;
|
|
447
507
|
deliveryMinDays?: number | null;
|
|
448
508
|
deliveryMaxDays?: number | null;
|
|
509
|
+
/** Who a live carrier rate came from. Absent on a manual zone method. */
|
|
510
|
+
provider?: string;
|
|
511
|
+
carrier?: string;
|
|
512
|
+
serviceCode?: string;
|
|
513
|
+
/**
|
|
514
|
+
* What the buyer would pay for this option with the cart's free-shipping code
|
|
515
|
+
* applied. Present only when the code would apply to it; `amount` stays the
|
|
516
|
+
* full price.
|
|
517
|
+
*/
|
|
518
|
+
discountedAmount?: number;
|
|
449
519
|
warnings?: Array<{
|
|
450
520
|
code: string;
|
|
451
521
|
message: string;
|
|
@@ -502,7 +572,11 @@ interface ShippingTaxCalculationResponse {
|
|
|
502
572
|
shippingTotal: number;
|
|
503
573
|
taxTotal: number;
|
|
504
574
|
total: number;
|
|
575
|
+
/** What a free-shipping code took off shipping; present only on a cart holding one. */
|
|
576
|
+
shippingDiscountTotal?: number;
|
|
505
577
|
};
|
|
578
|
+
/** The cart's free-shipping code and how it stands; absent on a cart holding none. */
|
|
579
|
+
appliedShippingDiscount?: AppliedShippingDiscount | null;
|
|
506
580
|
/**
|
|
507
581
|
* Verbatim messaging the tax engine returned about this transaction. In
|
|
508
582
|
* several EU member states the engine's own wording is what makes the
|
|
@@ -582,7 +656,12 @@ declare class CartClient {
|
|
|
582
656
|
};
|
|
583
657
|
get discounts(): {
|
|
584
658
|
apply: (cartId: string, code: string) => Promise<Cart>;
|
|
585
|
-
|
|
659
|
+
/**
|
|
660
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code:
|
|
661
|
+
* with both applied, name one with `kind` or `code` (else
|
|
662
|
+
* 400 `discount_kind_required`).
|
|
663
|
+
*/
|
|
664
|
+
remove: (cartId: string, opts?: RemoveDiscountOptions) => Promise<Cart>;
|
|
586
665
|
};
|
|
587
666
|
get taxLines(): {
|
|
588
667
|
set: (cartId: string, lines: TaxLineInput[]) => Promise<Cart>;
|
|
@@ -731,6 +810,8 @@ interface CheckoutHandoffInput {
|
|
|
731
810
|
* checkout returns to a live cart. Throttle's own hosted cart page sets this.
|
|
732
811
|
*/
|
|
733
812
|
keepOpen?: boolean;
|
|
813
|
+
/** The buyer's GA4 ids, UTMs and consent. Defaults to `Throttle.analyticsContext()` when that exists. */
|
|
814
|
+
clientContext?: Record<string, unknown>;
|
|
734
815
|
}
|
|
735
816
|
interface CheckoutHandoff {
|
|
736
817
|
cartSessionId: string;
|
|
@@ -794,7 +875,11 @@ declare class CartSessionClient {
|
|
|
794
875
|
selectShippingMethod(input: SelectShippingMethodInput): Promise<CartSessionCart>;
|
|
795
876
|
clearShipping(): Promise<CartSessionCart>;
|
|
796
877
|
applyDiscount(code: string): Promise<CartSessionCart>;
|
|
797
|
-
|
|
878
|
+
/**
|
|
879
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code: with
|
|
880
|
+
* both applied, name one with `kind` or `code` (else 400 `discount_kind_required`).
|
|
881
|
+
*/
|
|
882
|
+
removeDiscount(opts?: RemoveDiscountOptions): Promise<CartSessionCart>;
|
|
798
883
|
/** Set buyer-editable cart fields. Pass `null` to clear one. */
|
|
799
884
|
update(input: UpdateCartSessionInput): Promise<CartSessionCart>;
|
|
800
885
|
/**
|
|
@@ -1129,4 +1214,4 @@ declare function cartErrorFromResponse(args: {
|
|
|
1129
1214
|
responseHeaders?: ThrottleErrorArgs['responseHeaders'];
|
|
1130
1215
|
}): ThrottleApiError;
|
|
1131
1216
|
|
|
1132
|
-
export { type AddLineItemInput, type AddResolvedLineItemInput, AmountTooLargeError, type AppliedDiscount, type Cart, type CartAddress, type CartBranding, CartChangedError, CartClient, type CartErrorArgs, type CartEvent, CartNotFoundError, CartNotOpenError, type CartPricesChangedDetails, CartPricesChangedError, type CartSession, type CartSessionCart, CartSessionClient, type CartSessionClientOptions, type CartSessionSummary, type CartShippingChange, CartTimeoutError, type CheckoutHandoff, type CheckoutHandoffInput, type CheckoutInput, type CreateCartInput, type CreateCartSessionInput, CurrencyLockedError, CurrencyNotAvailableInProductionError, type CurrencyNotEnabledDetails, CurrencyNotEnabledError, CurrencyNotPayableError, CurrencyNotSupportedError, DiscountCurrencyUnsupportedError, type ExternalShippingTaxSnapshotInput, type LegacyLineRecurring, type LineItem, type LineLimitReachedDetails, LineLimitReachedError, type LineNotPurchasableDetails, LineNotPurchasableError, type LineRecurringInput, type LineResolution, type LineResolverNotAvailableDetails, LineResolverNotAvailableError, type LineResolverUnavailableDetails, LineResolverUnavailableError, type Order, type PriceLockedDetails, PriceLockedError, type QuantityUnavailableDetails, QuantityUnavailableError, QuoteAmountsNeedReviewError, type RefusedCartLine, ResolvedLinesRequiredError, type SelectShippingInput, type SelectShippingMethodInput, type SelectedShipping, ShippingCurrencyUnsupportedError, ShippingMethodUnavailableError, ShippingQuoteUnavailableError, type ShippingTaxAddress, type ShippingTaxCalculationResponse, type ShippingTaxCartCalculateInput, type ShippingTaxMethod, type ShippingTaxQuoteInput, type ShippingTaxQuoteItem, type StoredLineRecurring, StorefrontQuoteClient, type SubscriptionInterval, type SubscriptionIntervalUnit, type TaxLine, type TaxLineInput, ThrottleApiError, type UpdateCartInput, type UpdateCartSessionInput, type UpdateLineItemInput, cartErrorFromResponse };
|
|
1217
|
+
export { type AddLineItemInput, type AddResolvedLineItemInput, AmountTooLargeError, type AppliedDiscount, type AppliedShippingDiscount, type AppliedShippingDiscountStatus, type Cart, type CartAddress, type CartBranding, CartChangedError, CartClient, type CartErrorArgs, type CartEvent, CartNotFoundError, CartNotOpenError, type CartPricesChangedDetails, CartPricesChangedError, type CartSession, type CartSessionCart, CartSessionClient, type CartSessionClientOptions, type CartSessionSummary, type CartShippingChange, CartTimeoutError, type CheckoutHandoff, type CheckoutHandoffInput, type CheckoutInput, type CreateCartInput, type CreateCartSessionInput, CurrencyLockedError, CurrencyNotAvailableInProductionError, type CurrencyNotEnabledDetails, CurrencyNotEnabledError, CurrencyNotPayableError, CurrencyNotSupportedError, DiscountCurrencyUnsupportedError, type ExternalShippingTaxSnapshotInput, type LegacyLineRecurring, type LineItem, type LineLimitReachedDetails, LineLimitReachedError, type LineNotPurchasableDetails, LineNotPurchasableError, type LineRecurringInput, type LineResolution, type LineResolverNotAvailableDetails, LineResolverNotAvailableError, type LineResolverUnavailableDetails, LineResolverUnavailableError, type Order, type PriceLockedDetails, PriceLockedError, type QuantityUnavailableDetails, QuantityUnavailableError, QuoteAmountsNeedReviewError, type RefusedCartLine, type RemoveDiscountOptions, ResolvedLinesRequiredError, type SelectShippingInput, type SelectShippingMethodInput, type SelectedShipping, ShippingCurrencyUnsupportedError, ShippingMethodUnavailableError, ShippingQuoteUnavailableError, type ShippingTarget, type ShippingTaxAddress, type ShippingTaxCalculationResponse, type ShippingTaxCartCalculateInput, type ShippingTaxMethod, type ShippingTaxQuoteInput, type ShippingTaxQuoteItem, type StoredLineRecurring, StorefrontQuoteClient, type SubscriptionInterval, type SubscriptionIntervalUnit, type TaxLine, type TaxLineInput, ThrottleApiError, type UpdateCartInput, type UpdateCartSessionInput, type UpdateLineItemInput, cartErrorFromResponse };
|
package/dist/index.js
CHANGED
|
@@ -252,6 +252,76 @@ function cartErrorFromResponse(args) {
|
|
|
252
252
|
return new ThrottleApiError(args);
|
|
253
253
|
}
|
|
254
254
|
|
|
255
|
+
// src/analytics-context.ts
|
|
256
|
+
var LONG_KEYS = ["landingPage", "referrer"];
|
|
257
|
+
var SHORT_KEYS = [
|
|
258
|
+
"utmSource",
|
|
259
|
+
"utmMedium",
|
|
260
|
+
"utmCampaign",
|
|
261
|
+
"utmTerm",
|
|
262
|
+
"utmContent",
|
|
263
|
+
"gclid",
|
|
264
|
+
"fbclid",
|
|
265
|
+
"msclkid",
|
|
266
|
+
"ttclid",
|
|
267
|
+
"gaClientId",
|
|
268
|
+
"gaSessionId",
|
|
269
|
+
"fbp",
|
|
270
|
+
"fbc"
|
|
271
|
+
];
|
|
272
|
+
var CONSENT_KEYS = ["analytics", "marketing", "adUserData", "adPersonalization"];
|
|
273
|
+
var MAX_SHORT = 512;
|
|
274
|
+
var MAX_LONG = 2048;
|
|
275
|
+
var MAX_BYTES = 8192;
|
|
276
|
+
function sanitize(raw) {
|
|
277
|
+
const out = {};
|
|
278
|
+
const take = (keys, max) => {
|
|
279
|
+
for (const key of keys) {
|
|
280
|
+
const v = raw[key];
|
|
281
|
+
if (typeof v !== "string") continue;
|
|
282
|
+
const t = v.trim().slice(0, max).trim();
|
|
283
|
+
if (t) out[key] = t;
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
take(LONG_KEYS, MAX_LONG);
|
|
287
|
+
take(SHORT_KEYS, MAX_SHORT);
|
|
288
|
+
const consent = raw.consent;
|
|
289
|
+
if (consent && typeof consent === "object") {
|
|
290
|
+
const c = {};
|
|
291
|
+
for (const key of CONSENT_KEYS) {
|
|
292
|
+
const v = consent[key];
|
|
293
|
+
if (typeof v === "boolean") c[key] = v;
|
|
294
|
+
}
|
|
295
|
+
if (Object.keys(c).length > 0) out.consent = c;
|
|
296
|
+
}
|
|
297
|
+
if (Object.keys(out).length === 0) return void 0;
|
|
298
|
+
if (new TextEncoder().encode(JSON.stringify(out)).length > MAX_BYTES) return void 0;
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
function withAnalyticsContext(input) {
|
|
302
|
+
if (input.clientContext !== void 0) return input;
|
|
303
|
+
try {
|
|
304
|
+
const throttle = globalThis.Throttle;
|
|
305
|
+
const fn = throttle?.analyticsContext;
|
|
306
|
+
if (typeof fn !== "function") return input;
|
|
307
|
+
const raw = fn.call(throttle);
|
|
308
|
+
if (!raw || typeof raw !== "object") return input;
|
|
309
|
+
const clientContext = sanitize(raw);
|
|
310
|
+
return clientContext ? { ...input, clientContext } : input;
|
|
311
|
+
} catch {
|
|
312
|
+
return input;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// src/discount-query.ts
|
|
317
|
+
function removeDiscountQuery(opts) {
|
|
318
|
+
const query = new URLSearchParams();
|
|
319
|
+
if (opts?.kind) query.set("kind", opts.kind);
|
|
320
|
+
if (opts?.code) query.set("code", opts.code);
|
|
321
|
+
const text = query.toString();
|
|
322
|
+
return text ? `?${text}` : "";
|
|
323
|
+
}
|
|
324
|
+
|
|
255
325
|
// src/client.ts
|
|
256
326
|
function segment(value) {
|
|
257
327
|
return encodeURIComponent(value);
|
|
@@ -299,7 +369,7 @@ var CartClient = class {
|
|
|
299
369
|
create: (input) => this.request("POST", "/api/v1/carts", input),
|
|
300
370
|
get: (id) => this.request("GET", `/api/v1/carts/${segment(id)}`),
|
|
301
371
|
update: (id, input) => this.request("PATCH", `/api/v1/carts/${segment(id)}`, input),
|
|
302
|
-
checkout: (id, input) => this.request("POST", `/api/v1/carts/${segment(id)}/checkout`, input ?? {}),
|
|
372
|
+
checkout: (id, input) => this.request("POST", `/api/v1/carts/${segment(id)}/checkout`, withAnalyticsContext(input ?? {})),
|
|
303
373
|
merge: (id, customerId) => this.request("POST", `/api/v1/carts/${segment(id)}/merge`, { customerId })
|
|
304
374
|
};
|
|
305
375
|
}
|
|
@@ -330,7 +400,12 @@ var CartClient = class {
|
|
|
330
400
|
get discounts() {
|
|
331
401
|
return {
|
|
332
402
|
apply: (cartId, code) => this.request("POST", `/api/v1/carts/${segment(cartId)}/apply-discount`, { code }),
|
|
333
|
-
|
|
403
|
+
/**
|
|
404
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code:
|
|
405
|
+
* with both applied, name one with `kind` or `code` (else
|
|
406
|
+
* 400 `discount_kind_required`).
|
|
407
|
+
*/
|
|
408
|
+
remove: (cartId, opts) => this.request("DELETE", `/api/v1/carts/${segment(cartId)}/discount${removeDiscountQuery(opts)}`)
|
|
334
409
|
};
|
|
335
410
|
}
|
|
336
411
|
get taxLines() {
|
|
@@ -545,8 +620,12 @@ var CartSessionClient = class _CartSessionClient {
|
|
|
545
620
|
async applyDiscount(code) {
|
|
546
621
|
return (await this.request("POST", `${this.basePath()}/discount`, { code })).cart;
|
|
547
622
|
}
|
|
548
|
-
|
|
549
|
-
|
|
623
|
+
/**
|
|
624
|
+
* Remove a code. A cart can hold a goods code and a free-shipping code: with
|
|
625
|
+
* both applied, name one with `kind` or `code` (else 400 `discount_kind_required`).
|
|
626
|
+
*/
|
|
627
|
+
async removeDiscount(opts) {
|
|
628
|
+
return (await this.request("DELETE", `${this.basePath()}/discount${removeDiscountQuery(opts)}`)).cart;
|
|
550
629
|
}
|
|
551
630
|
/** Set buyer-editable cart fields. Pass `null` to clear one. */
|
|
552
631
|
async update(input) {
|
|
@@ -582,7 +661,7 @@ var CartSessionClient = class _CartSessionClient {
|
|
|
582
661
|
}
|
|
583
662
|
/** Hand off to hosted/embedded checkout. Marks the session converted (no more edits). */
|
|
584
663
|
checkout(input) {
|
|
585
|
-
return this.request("POST", `${this.basePath()}/checkout-session`, input);
|
|
664
|
+
return this.request("POST", `${this.basePath()}/checkout-session`, withAnalyticsContext(input));
|
|
586
665
|
}
|
|
587
666
|
basePath() {
|
|
588
667
|
if (!this.sessionId) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usethrottle/cart",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.20.0",
|
|
4
4
|
"description": "Typed REST client for the Throttle Cart API.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
},
|
|
32
32
|
"scripts": {
|
|
33
33
|
"build": "tsup",
|
|
34
|
-
"test": "tsc --noEmit --strict --skipLibCheck --target es2022 --lib es2022,dom --module esnext --moduleResolution bundler __tests__/recurring-types.check.ts __tests__/cart-customer-detach.check.ts __tests__/currency-types.check.ts && vitest run",
|
|
34
|
+
"test": "tsc --noEmit --strict --skipLibCheck --target es2022 --lib es2022,dom --module esnext --moduleResolution bundler __tests__/recurring-types.check.ts __tests__/cart-customer-detach.check.ts __tests__/currency-types.check.ts __tests__/free-shipping-types.check.ts && vitest run",
|
|
35
35
|
"typecheck": "tsc --noEmit"
|
|
36
36
|
}
|
|
37
37
|
}
|