@classytic/cart 0.1.2 → 0.2.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +12 -2
  3. package/dist/{shipping.bridge-CmQFTgSE.d.mts → clock.port-BUe6Dk_M.d.mts} +27 -10
  4. package/dist/{create-cart-B4l61iKT.mjs → create-cart-Iqvlv0V2.mjs} +183 -24
  5. package/dist/domain/errors/index.d.mts +1 -1
  6. package/dist/domain/errors/index.mjs +2 -2
  7. package/dist/domain/index.d.mts +7 -7
  8. package/dist/domain/index.mjs +3 -3
  9. package/dist/domain/ports/index.d.mts +2 -2
  10. package/dist/domain/saga/index.d.mts +1 -1
  11. package/dist/domain/saga/index.mjs +1 -1
  12. package/dist/engine/cart-config.schema.d.mts +7 -1
  13. package/dist/engine/cart-config.schema.mjs +10 -1
  14. package/dist/engine/index.d.mts +1 -1
  15. package/dist/engine/index.mjs +1 -1
  16. package/dist/{errors-DzR7Pipp.mjs → errors-7Pd0yATM.mjs} +1 -26
  17. package/dist/{id.port-C7ygWLRU.d.mts → id.port-DitjeoHg.d.mts} +1 -19
  18. package/dist/{index-BFBUk6qT.d.mts → index-qfN8dZN9.d.mts} +6 -5
  19. package/dist/index.d.mts +41 -15
  20. package/dist/index.mjs +84 -27
  21. package/dist/{internal-event-bus-DKcDteh-.d.mts → internal-event-bus-vMG6v-e6.d.mts} +71 -6
  22. package/dist/{kind-registry-C1n47C7h.d.mts → kind-registry-D03c2VV5.d.mts} +1 -1
  23. package/dist/kinds/index.d.mts +2 -2
  24. package/dist/kinds/index.mjs +2 -2
  25. package/dist/{line-kind-Ck3fVXzG.d.mts → line-kind-CKOWafK0.d.mts} +11 -6
  26. package/dist/{reservation.entity-b5cZ1ojx.d.mts → reservation.entity-WdaZCJg9.d.mts} +3 -3
  27. package/dist/{price-changed.error-C-wGVcfc.mjs → stale-quote.error-BkFLXWo5.mjs} +30 -4
  28. package/dist/{state-transitions-e4z3Yhxb.mjs → state-transitions-Bm3lC2Uv.mjs} +2 -2
  29. package/dist/{state-transitions-X_Eix5Iw.d.mts → state-transitions-D8CRykBv.d.mts} +7 -7
  30. package/dist/{variant.kind-9P1DXdXu.d.mts → variant.kind-Cpo_Hh7G.d.mts} +65 -2
  31. package/dist/{variant.kind-DfEh2oku.mjs → variant.kind-z2gwH9Vo.mjs} +92 -10
  32. package/package.json +8 -6
@@ -1,3 +1,3 @@
1
- import { _ as PromotionsBridge, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as ReservationRequest, f as CatalogBridge, g as PromotionResult, h as CartSnapshot, i as ShippingQuoteRequest, l as InventoryBridge, m as AdjustmentSpec, n as ShippingMethod, o as TaxBridge, p as ProductSummary, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as ReservationRef, x as OperationContext, y as BridgeRef } from "../../shipping.bridge-CmQFTgSE.mjs";
2
- import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../../id.port-C7ygWLRU.mjs";
1
+ import { C as OperationContext, S as BridgeStatus, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../../clock.port-BUe6Dk_M.mjs";
2
+ import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../../id.port-DitjeoHg.mjs";
3
3
  export { AdjustmentSpec, BridgeRef, BridgeStatus, CartSnapshot, CatalogBridge, ClockPort, IdPort, InventoryBridge, OperationContext, ProductSummary, PromotionResult, PromotionsBridge, ReservationRef, ReservationRequest, ShippingBridge, ShippingMethod, ShippingQuote, ShippingQuoteRequest, TaxBreakdown, TaxBridge, TaxCalculationRequest, TaxCalculationResult, createCounterIdPort, cryptoIdPort, systemClock };
@@ -1,2 +1,2 @@
1
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../../state-transitions-X_Eix5Iw.mjs";
1
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../../state-transitions-D8CRykBv.mjs";
2
2
  export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, type CheckoutFlowState, CheckoutStep, type CheckoutStepNumber, type SagaDependencies, type SagaStepFn, isLegalCheckoutTransition };
@@ -1,2 +1,2 @@
1
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-e4z3Yhxb.mjs";
1
+ import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-Bm3lC2Uv.mjs";
2
2
  export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CheckoutStep, isLegalCheckoutTransition };
@@ -14,6 +14,9 @@ declare const idempotencyConfigSchema: z.ZodObject<{
14
14
  declare const reservationConfigSchema: z.ZodObject<{
15
15
  defaultTtlSeconds: z.ZodDefault<z.ZodNumber>;
16
16
  }, z.core.$strip>;
17
+ declare const checkoutConfigSchema: z.ZodObject<{
18
+ staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
19
+ }, z.core.$strip>;
17
20
  declare const scopeConfigSchema: z.ZodObject<{
18
21
  contextKey: z.ZodDefault<z.ZodString>;
19
22
  }, z.core.$strip>;
@@ -30,6 +33,9 @@ declare const cartConfigSchema: z.ZodObject<{
30
33
  reservation: z.ZodDefault<z.ZodObject<{
31
34
  defaultTtlSeconds: z.ZodDefault<z.ZodNumber>;
32
35
  }, z.core.$strip>>;
36
+ checkout: z.ZodDefault<z.ZodObject<{
37
+ staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
38
+ }, z.core.$strip>>;
33
39
  draftTtlSeconds: z.ZodOptional<z.ZodNumber>;
34
40
  }, z.core.$strip>;
35
41
  /**
@@ -38,4 +44,4 @@ declare const cartConfigSchema: z.ZodObject<{
38
44
  */
39
45
  type CartConfigShape = z.infer<typeof cartConfigSchema>;
40
46
  //#endregion
41
- export { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
47
+ export { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -16,6 +16,14 @@ const idempotencyConfigSchema = z.object({
16
16
  const reservationConfigSchema = z.object({
17
17
  /** Default TTL for reservations in seconds. Default 10 minutes. */
18
18
  defaultTtlSeconds: z.number().int().positive().default(600) });
19
+ const checkoutConfigSchema = z.object({
20
+ /**
21
+ * Age (ms) past which an `open` checkout counts as a zombie and is
22
+ * lazily expired by `createFromDraft` (CAS `open → canceled`, reason
23
+ * `'expired'`) so a fresh checkout can be created. Default 10 minutes —
24
+ * matches `reservationConfigSchema.defaultTtlSeconds`.
25
+ */
26
+ staleOpenCheckoutMs: z.number().int().positive().default(6e5) });
19
27
  const scopeConfigSchema = z.object({
20
28
  /**
21
29
  * Optional context key name. The STORAGE FIELD is always
@@ -33,8 +41,9 @@ const cartConfigSchema = z.object({
33
41
  retentionSeconds: 1440 * 60
34
42
  }),
35
43
  reservation: reservationConfigSchema.default({ defaultTtlSeconds: 600 }),
44
+ checkout: checkoutConfigSchema.default({ staleOpenCheckoutMs: 6e5 }),
36
45
  /** Whether drafts auto-expire via TTL. Default off. */
37
46
  draftTtlSeconds: z.number().int().positive().optional()
38
47
  });
39
48
  //#endregion
40
- export { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
49
+ export { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
1
  import { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
2
- import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-DKcDteh-.mjs";
2
+ import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-vMG6v-e6.mjs";
3
3
  export { type CartBridges, type CartConfig, type CartConfigShape, type CartEngine, InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
- import { n as InProcessCartEventBus, t as createCart } from "../create-cart-B4l61iKT.mjs";
1
+ import { n as InProcessCartEventBus, t as createCart } from "../create-cart-Iqvlv0V2.mjs";
2
2
  import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -69,29 +69,4 @@ var IdempotencyStorageError = class extends CartError {
69
69
  }
70
70
  };
71
71
  //#endregion
72
- //#region src/domain/errors/stale-quote.error.ts
73
- /**
74
- * A priced line's validity window has elapsed and its LineKind's revalidate()
75
- * returned `invalid`. Fired from the saga's step 2 (revalidation).
76
- *
77
- * Example: a bid line whose underlying auction moved to a new highest bid
78
- * while the user was reviewing the cart.
79
- *
80
- * Clients should re-read the cart, show the updated state, and confirm again.
81
- * Retryable with a new idempotency key.
82
- */
83
- var StaleQuoteError = class extends CartError {
84
- code = "cart/stale_quote";
85
- category = "validation";
86
- retryable = true;
87
- constructor(lineId, kind, reason, details) {
88
- super(`Line ${lineId} (${kind}) is no longer valid: ${reason}`, {
89
- lineId,
90
- kind,
91
- reason,
92
- ...details
93
- });
94
- }
95
- };
96
- //#endregion
97
- export { ReservationError as a, SagaError as i, IdempotencyBusyError as n, IdempotencyStorageError as r, StaleQuoteError as t };
72
+ export { ReservationError as i, IdempotencyStorageError as n, SagaError as r, IdempotencyBusyError as t };
@@ -1,21 +1,3 @@
1
- //#region src/domain/ports/clock.port.d.ts
2
- /**
3
- * Clock port — the one source of "now" in the cart engine.
4
- *
5
- * Injected through config so tests can install a fake clock and fast-forward
6
- * through TTLs, validity windows, and saga lease expirations. Production
7
- * hosts pass nothing and get a default `systemClock` that calls `new Date()`.
8
- *
9
- * Never read `Date.now()` or `new Date()` directly in cart code. Always use
10
- * `engine.clock.now()`. Integration tests assert this via ESLint rule.
11
- */
12
- interface ClockPort {
13
- /** Wall clock — used for timestamps, TTL expiry, idempotency leases. */
14
- now(): Date;
15
- }
16
- /** Default system clock — passes straight through to `new Date()`. */
17
- declare const systemClock: ClockPort;
18
- //#endregion
19
1
  //#region src/domain/ports/id.port.d.ts
20
2
  /**
21
3
  * IdPort — a swappable source of unique identifiers.
@@ -61,4 +43,4 @@ declare const cryptoIdPort: IdPort;
61
43
  */
62
44
  declare function createCounterIdPort(prefix?: string): IdPort;
63
45
  //#endregion
64
- export { systemClock as a, ClockPort as i, createCounterIdPort as n, cryptoIdPort as r, IdPort as t };
46
+ export { createCounterIdPort as n, cryptoIdPort as r, IdPort as t };
@@ -103,11 +103,12 @@ declare class NotFoundError extends CartError {
103
103
  //#endregion
104
104
  //#region src/domain/errors/price-changed.error.d.ts
105
105
  /**
106
- * The re-run pricing snapshot's hash does not match the `expectedPricingHash`
107
- * the client supplied when initiating finalize. Fired from saga step 3.
106
+ * The stored pricing snapshot's hash does not match the `expectedPricingHash`
107
+ * the client supplied when initiating checkout. Fired from the cheap hash
108
+ * check before the checkout snapshot is frozen.
108
109
  *
109
110
  * This is a safety interlock: the client saw totals X, but by the time the
110
- * saga ran, totals are now Y. Rather than silently charging a different
111
+ * checkout ran, totals are now Y. Rather than silently charging a different
111
112
  * amount, the saga aborts with this error so the client re-displays and
112
113
  * re-confirms.
113
114
  *
@@ -194,8 +195,8 @@ declare class IdempotencyStorageError extends CartError {
194
195
  //#endregion
195
196
  //#region src/domain/errors/stale-quote.error.d.ts
196
197
  /**
197
- * A priced line's validity window has elapsed and its LineKind's revalidate()
198
- * returned `invalid`. Fired from the saga's step 2 (revalidation).
198
+ * A priced line's validity window has elapsed. Fired during checkout's
199
+ * freshness check before the snapshot is frozen.
199
200
  *
200
201
  * Example: a bid line whose underlying auction moved to a new highest bid
201
202
  * while the user was reviewing the cart.
package/dist/index.d.mts CHANGED
@@ -1,20 +1,20 @@
1
- import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "./index-BFBUk6qT.mjs";
1
+ import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "./index-qfN8dZN9.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
3
3
  import { S as CartEvents, _ as CartEventMeta, a as OutboxErrorInfo, b as CartEventName, c as OutboxFailureDecision, d as OutboxStore, f as OutboxStoreWriteOptions, g as CartEventAggregate, h as CartDomainEvent, i as OutboxClaimOptions, l as OutboxFailurePolicy, m as CartAggregateType, n as MemoryOutboxStore, o as OutboxFailOptions, p as OutboxWriteOptions, r as OutboxAcknowledgeOptions, s as OutboxFailureContext, t as InvalidOutboxEventError, u as OutboxOwnershipError, v as createCartEvent, x as CartEventPayload, y as CartEventMap } from "./outbox-store-CBt9fSYh.mjs";
4
4
  import { a as CartEventRegistry, c as defineCartEvent, d as EventValidationResult, f as EventValidator, i as CartEventDefinitionInput, l as EventSchema, n as cartEventsByName, o as PayloadOf, r as CartEventDefinition, s as createCartEventRegistry, t as cartEventDefinitions, u as EventSchemaProperty } from "./cart-event-catalog-BxDJhtTM.mjs";
5
- import { C as PricingSnapshot, S as PricedLine, _ as PromotionsBridge, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as ReservationRequest, f as CatalogBridge, g as PromotionResult, h as CartSnapshot, i as ShippingQuoteRequest, l as InventoryBridge, m as AdjustmentSpec, n as ShippingMethod, o as TaxBridge, p as ProductSummary, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as ReservationRef, v as Address, x as OperationContext, y as BridgeRef } from "./shipping.bridge-CmQFTgSE.mjs";
6
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-b5cZ1ojx.mjs";
7
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep } from "./state-transitions-X_Eix5Iw.mjs";
8
- import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "./line-kind-Ck3fVXzG.mjs";
9
- import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-C1n47C7h.mjs";
10
- import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-C7ygWLRU.mjs";
11
- import { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
- import { C as IdempotencyDocument, D as CheckoutDocument, E as createDraftModel, O as createCheckoutModel, S as createReservationModel, T as DraftDocument, _ as CartModelName, a as CartEngine, b as createCartModels, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as CartEventPublisherDeps, h as DraftRepositoryDeps, i as CartConfig, l as createCartRepositories, m as DraftRepository, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModels, w as createIdempotencyModel, x as ReservationDocument, y as CreateCartModelsOptions } from "./internal-event-bus-DKcDteh-.mjs";
13
- import { a as timeslotKind, c as skuKind, d as BundlePayload, f as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, n as variantKind, o as timeslotPayloadSchema, p as bundlePayloadSchema, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as BundleComponent } from "./variant.kind-9P1DXdXu.mjs";
5
+ import { C as OperationContext, S as BridgeStatus, T as PricingSnapshot, _ as CartSnapshot, a as ShippingQuote, b as Address, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, w as PricedLine, x as BridgeRef, y as PromotionsBridge } from "./clock.port-BUe6Dk_M.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-WdaZCJg9.mjs";
7
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep } from "./state-transitions-D8CRykBv.mjs";
8
+ import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "./line-kind-CKOWafK0.mjs";
9
+ import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-D03c2VV5.mjs";
10
+ import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DitjeoHg.mjs";
11
+ import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
+ import { C as createReservationModel, D as createDraftModel, E as DraftDocument, O as CheckoutDocument, S as ReservationDocument, T as createIdempotencyModel, _ as CartEventPublisherDeps, a as CartEngine, b as CreateCartModelsOptions, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as DraftRepositoryDeps, h as DraftRepository, i as CartConfig, k as createCheckoutModel, l as createCartRepositories, m as DEFAULT_STALE_OPEN_CHECKOUT_MS, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModelName, w as IdempotencyDocument, x as createCartModels, y as CartModels } from "./internal-event-bus-vMG6v-e6.mjs";
13
+ import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "./variant.kind-Cpo_Hh7G.mjs";
14
14
  import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
15
  import { EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
16
16
  import { Schema } from "mongoose";
17
- import { ResolvedTenantConfig, TenantConfig } from "@classytic/primitives/tenant";
17
+ import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
18
18
 
19
19
  //#region src/services/abandonment.service.d.ts
20
20
  /**
@@ -50,9 +50,35 @@ declare function markAbandoned(opts: {
50
50
  * active draft on login.
51
51
  *
52
52
  * Merge strategy: iterate the source's lines. For each line, if a line
53
- * with the same `(kind, skuRef)` exists in the target, increment the
54
- * target's quantity. Otherwise, append. Display snapshots carry over
55
- * from the source since they're already captured.
53
+ * with the same merge key (kind-defined, `(kind, skuRef)` fallback)
54
+ * exists in the target, increment the target's quantity. Otherwise,
55
+ * append. Display snapshots carry over from the source since they're
56
+ * already captured.
57
+ *
58
+ * ## Concurrency — double-CAS, no lost updates
59
+ *
60
+ * Both drafts can be mutated concurrently (guest tab still open, user
61
+ * adding from another device). The merge is therefore guarded by TWO
62
+ * compare-and-set writes, ordered so a retry can never double-apply:
63
+ *
64
+ * 1. The SOURCE is retired first — `markAbandoned` with
65
+ * `expectedVersion` CAS-pinned to the read that captured its lines.
66
+ * A concurrent add-to-cart on the source bumps `version`, the CAS
67
+ * misses, and the whole merge retries from a fresh read (bounded).
68
+ * Once this write lands, the captured source line set is final.
69
+ * 2. The TARGET write — `replaceLines` CAS-pinned (`expectedVersion`)
70
+ * to the target read the merged line set was computed from. A
71
+ * concurrent add-to-cart on the target surfaces as
72
+ * `ConcurrencyError`; the merge re-reads the target, re-merges the
73
+ * (already-frozen) source lines, and retries — so the concurrent
74
+ * line survives. Because the source was retired exactly once in
75
+ * step 1, target retries can never double-count source quantities.
76
+ *
77
+ * Hosts that need the two writes to be all-or-nothing (no
78
+ * retired-source/unmerged-lines window on a crash between steps) can
79
+ * pass a Mongoose `ctx.session` opened on a transaction — both writes
80
+ * thread it — at the cost of requiring a replica set and a configured
81
+ * outbox (see docs/host-integration.md).
56
82
  *
57
83
  * After merging, the source draft is marked `abandoned` so it's no
58
84
  * longer active.
@@ -115,4 +141,4 @@ type CartTenantInput = TenantConfig | boolean | {
115
141
  /** Re-export of primitives' resolved shape under the legacy name. */
116
142
  type ResolvedTenant = ResolvedTenantConfig;
117
143
  //#endregion
118
- export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBridges, type CartConfig, type CartConfigShape, type CartDomainEvent, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type CreateCartRepositoriesConfig, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, type ProductSummary, type PromotionResult, type PromotionsBridge, type PublishManyResult, type Reservation, type ReservationDocument, ReservationError, type ReservationRef, ReservationRepository, type ReservationRequest, type ReservationStatus, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, type VariantPayload, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
144
+ export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBridges, type CartConfig, type CartConfigShape, type CartDomainEvent, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type CreateCartRepositoriesConfig, DEFAULT_STALE_OPEN_CHECKOUT_MS, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, type ProductSummary, type PromotionResult, type PromotionsBridge, type PublishManyResult, type Reservation, type ReservationDocument, ReservationError, type ReservationRef, ReservationRepository, type ReservationRequest, type ReservationStatus, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, type VariantPayload, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
package/dist/index.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  import { t as CART_REF_NEW } from "./idempotency-key.vo-D0lJsvGn.mjs";
2
2
  import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
3
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "./price-changed.error-C-wGVcfc.mjs";
3
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "./stale-quote.error-BkFLXWo5.mjs";
4
4
  import { n as UnknownKindError, t as KindError } from "./kind.error-DIaJpdUb.mjs";
5
- import { a as ReservationError, i as SagaError, n as IdempotencyBusyError, r as IdempotencyStorageError, t as StaleQuoteError } from "./errors-DzR7Pipp.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-7Pd0yATM.mjs";
6
6
  import { t as StateTransitionError } from "./state-transition.error-2fRLh3p0.mjs";
7
7
  import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-CWW8ppxS.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-BhbFZJPm.mjs";
10
10
  import { t as createKindRegistry } from "./kind-registry-C99h_-8t.mjs";
11
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-e4z3Yhxb.mjs";
12
- import { a as IdempotencyRepository, c as CheckoutRepository, d as createIdempotencyModel, f as createDraftModel, i as ReservationRepository, l as createCartModels, n as InProcessCartEventBus, o as DraftRepository, p as createCheckoutModel, r as createCartRepositories, s as runPricing, t as createCart, u as createReservationModel } from "./create-cart-B4l61iKT.mjs";
13
- import { a as skuKind, c as bundlePayloadSchema, i as timeslotPayloadSchema, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as bundleKind, t as variantKind } from "./variant.kind-DfEh2oku.mjs";
14
- import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
11
+ import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-Bm3lC2Uv.mjs";
12
+ import { a as IdempotencyRepository, c as CheckoutRepository, d as createReservationModel, f as createIdempotencyModel, i as ReservationRepository, l as DEFAULT_STALE_OPEN_CHECKOUT_MS, m as createCheckoutModel, n as InProcessCartEventBus, o as DraftRepository, p as createDraftModel, r as createCartRepositories, s as runPricing, t as createCart, u as createCartModels } from "./create-cart-Iqvlv0V2.mjs";
13
+ import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "./variant.kind-z2gwH9Vo.mjs";
14
+ import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
15
15
  import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
16
16
  //#region src/services/abandonment.service.ts
17
17
  /**
@@ -40,8 +40,9 @@ async function findAbandonedDrafts(opts) {
40
40
  }, {
41
41
  organizationId: ctx.organizationId,
42
42
  skipTenant: ctx.skipTenant,
43
+ signal: ctx.signal,
43
44
  lean: true
44
- })).docs;
45
+ })).data;
45
46
  }
46
47
  /**
47
48
  * Mark a batch of drafts as abandoned. Returns the count of drafts
@@ -54,40 +55,96 @@ async function markAbandoned(opts) {
54
55
  }
55
56
  //#endregion
56
57
  //#region src/services/merge.service.ts
58
+ /** Bounded retries for each CAS-guarded phase of the merge. */
59
+ const MAX_MERGE_ATTEMPTS = 3;
57
60
  /**
58
61
  * Merge a guest (session-scoped) draft into an authenticated user's
59
62
  * active draft on login.
60
63
  *
61
64
  * Merge strategy: iterate the source's lines. For each line, if a line
62
- * with the same `(kind, skuRef)` exists in the target, increment the
63
- * target's quantity. Otherwise, append. Display snapshots carry over
64
- * from the source since they're already captured.
65
+ * with the same merge key (kind-defined, `(kind, skuRef)` fallback)
66
+ * exists in the target, increment the target's quantity. Otherwise,
67
+ * append. Display snapshots carry over from the source since they're
68
+ * already captured.
69
+ *
70
+ * ## Concurrency — double-CAS, no lost updates
71
+ *
72
+ * Both drafts can be mutated concurrently (guest tab still open, user
73
+ * adding from another device). The merge is therefore guarded by TWO
74
+ * compare-and-set writes, ordered so a retry can never double-apply:
75
+ *
76
+ * 1. The SOURCE is retired first — `markAbandoned` with
77
+ * `expectedVersion` CAS-pinned to the read that captured its lines.
78
+ * A concurrent add-to-cart on the source bumps `version`, the CAS
79
+ * misses, and the whole merge retries from a fresh read (bounded).
80
+ * Once this write lands, the captured source line set is final.
81
+ * 2. The TARGET write — `replaceLines` CAS-pinned (`expectedVersion`)
82
+ * to the target read the merged line set was computed from. A
83
+ * concurrent add-to-cart on the target surfaces as
84
+ * `ConcurrencyError`; the merge re-reads the target, re-merges the
85
+ * (already-frozen) source lines, and retries — so the concurrent
86
+ * line survives. Because the source was retired exactly once in
87
+ * step 1, target retries can never double-count source quantities.
88
+ *
89
+ * Hosts that need the two writes to be all-or-nothing (no
90
+ * retired-source/unmerged-lines window on a crash between steps) can
91
+ * pass a Mongoose `ctx.session` opened on a transaction — both writes
92
+ * thread it — at the cost of requiring a replica set and a configured
93
+ * outbox (see docs/host-integration.md).
65
94
  *
66
95
  * After merging, the source draft is marked `abandoned` so it's no
67
96
  * longer active.
68
97
  */
69
98
  async function mergeDrafts(opts) {
70
99
  const { repo, sourcePublicId, targetActorRef, ctx } = opts;
71
- const source = await repo.findByPublicId(sourcePublicId, ctx);
72
- if (!source || source.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
73
100
  const targetCtx = {
74
101
  ...ctx,
75
102
  actorRef: targetActorRef
76
103
  };
77
- const target = await repo.findActiveByActor(targetActorRef, targetCtx);
78
- if (!target) return repo.updateWithVersion(source._id, source.version, {
79
- actorRef: targetActorRef,
80
- actorKind: "user"
81
- }, ctx);
82
- const sourceLines = source.lines;
83
- const currentTargetLines = target.lines;
84
- const mergedLines = repo.mergeLines(currentTargetLines, sourceLines);
85
- const updated = await repo.replaceLines({
86
- draftPublicId: target.publicId,
87
- lines: mergedLines
88
- }, targetCtx);
89
- await repo.markAbandoned(source._id, ctx);
90
- return updated;
104
+ let sourceLines = null;
105
+ let lastError;
106
+ for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
107
+ const source = await repo.findByPublicId(sourcePublicId, ctx);
108
+ if (!source || source.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
109
+ if (!await repo.findActiveByActor(targetActorRef, targetCtx)) try {
110
+ return await repo.updateWithVersion(source._id, source.version, {
111
+ actorRef: targetActorRef,
112
+ actorKind: "user"
113
+ }, ctx);
114
+ } catch (err) {
115
+ if (err instanceof ConcurrencyError) {
116
+ lastError = err;
117
+ continue;
118
+ }
119
+ throw err;
120
+ }
121
+ if (!await repo.markAbandoned(source._id, ctx, { expectedVersion: source.version })) {
122
+ lastError = new ConcurrencyError("draft", source.version, String(source._id));
123
+ continue;
124
+ }
125
+ sourceLines = source.lines;
126
+ break;
127
+ }
128
+ if (!sourceLines) throw lastError;
129
+ for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
130
+ const target = await repo.findActiveByActor(targetActorRef, targetCtx);
131
+ if (!target) throw new Error(`Target draft for actor '${targetActorRef}' disappeared during merge of '${sourcePublicId}'`);
132
+ const mergedLines = repo.mergeLines(target.lines, sourceLines);
133
+ try {
134
+ return await repo.replaceLines({
135
+ draftPublicId: target.publicId,
136
+ lines: mergedLines,
137
+ expectedVersion: target.version
138
+ }, targetCtx);
139
+ } catch (err) {
140
+ if (err instanceof ConcurrencyError) {
141
+ lastError = err;
142
+ continue;
143
+ }
144
+ throw err;
145
+ }
146
+ }
147
+ throw lastError;
91
148
  }
92
149
  //#endregion
93
- export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
150
+ export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
@@ -1,8 +1,8 @@
1
1
  import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CBt9fSYh.mjs";
2
- import { _ as PromotionsBridge, f as CatalogBridge, l as InventoryBridge, o as TaxBridge, t as ShippingBridge, x as OperationContext } from "./shipping.bridge-CmQFTgSE.mjs";
3
- import { l as LineDisplay, r as LineKind } from "./line-kind-Ck3fVXzG.mjs";
4
- import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-C1n47C7h.mjs";
5
- import { i as ClockPort, t as IdPort } from "./id.port-C7ygWLRU.mjs";
2
+ import { C as OperationContext, c as TaxBridge, d as InventoryBridge, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-BUe6Dk_M.mjs";
3
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CKOWafK0.mjs";
4
+ import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-D03c2VV5.mjs";
5
+ import { t as IdPort } from "./id.port-DitjeoHg.mjs";
6
6
  import { CartConfigShape } from "./engine/cart-config.schema.mjs";
7
7
  import { Money } from "@classytic/primitives/money";
8
8
  import { DomainEvent, EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
@@ -209,6 +209,20 @@ interface DraftRepositoryDeps {
209
209
  * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
210
210
  * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
211
211
  * through mongokit's `update()` so all hooks (audit, observability) fire.
212
+ *
213
+ * ## Concurrency invariant — read-modify-write on `lines` is CAS-safe
214
+ *
215
+ * Every line mutation (addItem, updateItemQuantity, removeItem, clear,
216
+ * replaceLines) rebuilds the FULL `lines` array in memory from a single
217
+ * read and persists it via `updateWithVersion`, which only matches when
218
+ * the stored `version` still equals the version of that read. Any
219
+ * concurrent mutation bumps `version`, so the stale rebuild can never
220
+ * land — the loser gets a typed `ConcurrencyError` and retries from a
221
+ * fresh read. Do NOT "optimize" these paths into positional `$push` /
222
+ * `$set('lines.$')` array operators: pricing snapshots are derived from
223
+ * the whole line set, so a partial array write would let `lines` and
224
+ * `pricing` drift apart. The version CAS is what makes the in-memory
225
+ * rebuild safe; the rebuild is what keeps pricing consistent.
212
226
  */
213
227
  declare class DraftRepository extends Repository<DraftDocument> {
214
228
  private readonly kinds;
@@ -266,8 +280,16 @@ declare class DraftRepository extends Repository<DraftDocument> {
266
280
  /**
267
281
  * Atomic transition `active → abandoned`. Returns null if the draft was
268
282
  * already in a non-active state.
283
+ *
284
+ * Pass `opts.expectedVersion` to ALSO compare-and-set on `version` —
285
+ * the merge service uses this to guarantee the source draft's line set
286
+ * it captured is exactly the line set being retired (a concurrent
287
+ * add-to-cart bumps `version`, the CAS misses, and the merge retries
288
+ * from a fresh read instead of silently dropping the new line).
269
289
  */
270
- markAbandoned(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<DraftDocument | null>;
290
+ markAbandoned(draftId: Types.ObjectId | string, ctx: OperationContext, opts?: {
291
+ expectedVersion?: number;
292
+ }): Promise<DraftDocument | null>;
271
293
  /**
272
294
  * Mark a draft as converted (called from CheckoutRepository.commit).
273
295
  * Best-effort: a missed update is reconciled by the next getOrCreate.
@@ -277,10 +299,18 @@ declare class DraftRepository extends Repository<DraftDocument> {
277
299
  * Replace the line collection atomically and refresh the pricing snapshot.
278
300
  * Internal services use this to keep merge-like flows inside repository
279
301
  * concurrency + pricing rules instead of hand-writing persistence logic.
302
+ *
303
+ * Pass `expectedVersion` when `lines` was computed from an EARLIER read
304
+ * of the draft: the CAS then pins to that read's version, so any
305
+ * mutation that landed in between (concurrent add-to-cart during a
306
+ * merge) surfaces as `ConcurrencyError` instead of being overwritten.
307
+ * Without it, the CAS pins to this method's own fresh read — safe for
308
+ * callers whose `lines` doesn't derive from draft state.
280
309
  */
281
310
  replaceLines(input: {
282
311
  draftPublicId: string;
283
312
  lines: readonly LineItem[];
313
+ expectedVersion?: number;
284
314
  }, ctx: OperationContext): Promise<DraftDocument>;
285
315
  mergeLines(existing: readonly LineItem[], incoming: readonly LineItem[]): LineItem[];
286
316
  private readOptions;
@@ -309,7 +339,20 @@ interface CheckoutRepositoryDeps {
309
339
  draftRepo: DraftRepository;
310
340
  clock: ClockPort;
311
341
  eventPublisher: CartEventPublisher;
342
+ /**
343
+ * Age (ms) past which an `open` checkout is considered a zombie and is
344
+ * lazily expired by `createFromDraft` instead of being returned as the
345
+ * idempotent dedup hit. Default: `DEFAULT_STALE_OPEN_CHECKOUT_MS`.
346
+ */
347
+ staleOpenCheckoutMs?: number | undefined;
312
348
  }
349
+ /**
350
+ * Default zombie window for open checkouts — matches the package's
351
+ * existing expiry default (`reservationConfigSchema.defaultTtlSeconds`,
352
+ * 600s): once any reservation hold backing the checkout has lapsed, the
353
+ * open snapshot has no claim on anything and is safe to self-expire.
354
+ */
355
+ declare const DEFAULT_STALE_OPEN_CHECKOUT_MS = 600000;
313
356
  /**
314
357
  * CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
315
358
  *
@@ -322,6 +365,7 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
322
365
  private readonly draftRepo;
323
366
  private readonly clock;
324
367
  private readonly eventPublisher;
368
+ private readonly staleOpenCheckoutMs;
325
369
  constructor(model: Model<CheckoutDocument>, plugins: PluginType[], deps: CheckoutRepositoryDeps);
326
370
  findByPublicId(publicId: string, ctx: OperationContext): Promise<CheckoutDocument | null>;
327
371
  findByDraft(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<CheckoutDocument | null>;
@@ -357,6 +401,13 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
357
401
  * call this from a periodic job (cron, Streamline, etc.) at whatever
358
402
  * cadence matches their checkout completion SLA.
359
403
  *
404
+ * This is the BULK sweep. `createFromDraft` additionally self-heals
405
+ * lazily: when it finds an open checkout older than
406
+ * `staleOpenCheckoutMs`, it CAS-expires that one zombie inline and
407
+ * creates a fresh checkout — so a customer is never stuck waiting for
408
+ * the next cron tick. Keep both: lazy healing fixes the active
409
+ * customer's path; the cron reclaims abandoned rows nobody revisits.
410
+ *
360
411
  * Returns the count of rows expired. Caller scopes the operation via
361
412
  * `ctx` — pass `ctx.organizationId` to scope to one tenant, or use
362
413
  * `skipTenant: true` to expire across the board (only safe for the
@@ -370,6 +421,18 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
370
421
  expireStaleOpenCheckouts(maxAgeMs: number, ctx: OperationContext): Promise<{
371
422
  count: number;
372
423
  }>;
424
+ /** Is this open checkout past the zombie window? */
425
+ private isStaleOpen;
426
+ /**
427
+ * CAS-expire a zombie open checkout: `open → canceled` with
428
+ * `canceledReason: 'expired'` — same terminal shape the cron
429
+ * (`expireStaleOpenCheckouts`) writes, so audit history is uniform.
430
+ * The `{ state: 'open', version }` filter makes the transition atomic:
431
+ * a concurrent commit/cancel/expiry wins and this call is a no-op
432
+ * (returns false). No CHECKOUT_CANCELED event — expiry is janitorial,
433
+ * matching the cron method's contract.
434
+ */
435
+ private expireZombie;
373
436
  private readOptions;
374
437
  private writeOptions;
375
438
  private requireCheckout;
@@ -487,6 +550,8 @@ interface CreateCartRepositoriesConfig {
487
550
  multiTenant?: boolean;
488
551
  outbox?: OutboxStore;
489
552
  plugins?: CartRepositoryPluginBundle;
553
+ /** Zombie window for lazy open-checkout expiry. See `CheckoutRepositoryDeps`. */
554
+ staleOpenCheckoutMs?: number;
490
555
  }
491
556
  declare function createCartRepositories(models: CartModels, config: CreateCartRepositoriesConfig): CartRepositories;
492
557
  //#endregion
@@ -683,4 +748,4 @@ declare class InProcessCartEventBus implements EventTransport {
683
748
  close(): Promise<void>;
684
749
  }
685
750
  //#endregion
686
- export { IdempotencyDocument as C, CheckoutDocument as D, createDraftModel as E, createCheckoutModel as O, createReservationModel as S, DraftDocument as T, CartModelName as _, CartEngine as a, createCartModels as b, CreateCartRepositoriesConfig as c, IdempotencyRepository as d, CheckoutRepository as f, CartEventPublisherDeps as g, DraftRepositoryDeps as h, CartConfig as i, createCartRepositories as l, DraftRepository as m, createCart as n, CartRepositories as o, CheckoutRepositoryDeps as p, CartBridges as r, CartRepositoryPluginBundle as s, InProcessCartEventBus as t, ReservationRepository as u, CartModels as v, createIdempotencyModel as w, ReservationDocument as x, CreateCartModelsOptions as y };
751
+ export { createReservationModel as C, createDraftModel as D, DraftDocument as E, CheckoutDocument as O, ReservationDocument as S, createIdempotencyModel as T, CartEventPublisherDeps as _, CartEngine as a, CreateCartModelsOptions as b, CreateCartRepositoriesConfig as c, IdempotencyRepository as d, CheckoutRepository as f, DraftRepositoryDeps as g, DraftRepository as h, CartConfig as i, createCheckoutModel as k, createCartRepositories as l, DEFAULT_STALE_OPEN_CHECKOUT_MS as m, createCart as n, CartRepositories as o, CheckoutRepositoryDeps as p, CartBridges as r, CartRepositoryPluginBundle as s, InProcessCartEventBus as t, ReservationRepository as u, CartModelName as v, IdempotencyDocument as w, createCartModels as x, CartModels as y };
@@ -1,4 +1,4 @@
1
- import { l as LineDisplay, r as LineKind } from "./line-kind-Ck3fVXzG.mjs";
1
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CKOWafK0.mjs";
2
2
  import * as _$_classytic_primitives_money0 from "@classytic/primitives/money";
3
3
  import { Money } from "@classytic/primitives/money";
4
4
 
@@ -1,2 +1,2 @@
1
- import { a as timeslotKind, c as skuKind, d as BundlePayload, f as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, n as variantKind, o as timeslotPayloadSchema, p as bundlePayloadSchema, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as BundleComponent } from "../variant.kind-9P1DXdXu.mjs";
2
- export { type BundleComponent, type BundlePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
1
+ import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "../variant.kind-Cpo_Hh7G.mjs";
2
+ export { type BundleComponent, type BundlePayload, type ServiceFeePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
@@ -1,2 +1,2 @@
1
- import { a as skuKind, c as bundlePayloadSchema, i as timeslotPayloadSchema, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as bundleKind, t as variantKind } from "../variant.kind-DfEh2oku.mjs";
2
- export { bundleKind, bundlePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
1
+ import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "../variant.kind-z2gwH9Vo.mjs";
2
+ export { bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };