@classytic/cart 0.1.0 → 0.1.2

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 (45) hide show
  1. package/README.md +1 -10
  2. package/dist/{cart-event-catalog-BIbi2Q_n.d.mts → cart-event-catalog-BxDJhtTM.d.mts} +1 -1
  3. package/dist/cart.error-BwWy4RlY.mjs +27 -0
  4. package/dist/{create-cart-q3CXxPP7.mjs → create-cart-B4l61iKT.mjs} +589 -543
  5. package/dist/domain/errors/index.d.mts +1 -1
  6. package/dist/domain/errors/index.mjs +5 -3
  7. package/dist/domain/events/index.d.mts +2 -2
  8. package/dist/domain/events/index.mjs +2 -2
  9. package/dist/domain/index.d.mts +11 -11
  10. package/dist/domain/index.mjs +11 -10
  11. package/dist/domain/ports/index.d.mts +2 -2
  12. package/dist/domain/ports/index.mjs +1 -1
  13. package/dist/domain/saga/index.d.mts +2 -2
  14. package/dist/domain/saga/index.mjs +2 -3
  15. package/dist/engine/index.d.mts +1 -1
  16. package/dist/engine/index.mjs +1 -1
  17. package/dist/{errors-CHR9RlbY.mjs → errors-DzR7Pipp.mjs} +27 -27
  18. package/dist/{index-Doi5uzux.d.mts → index-BFBUk6qT.d.mts} +68 -68
  19. package/dist/index.d.mts +73 -58
  20. package/dist/index.mjs +50 -49
  21. package/dist/{internal-event-bus-IkUfQJxn.d.mts → internal-event-bus-DKcDteh-.d.mts} +109 -84
  22. package/dist/{line-item.entity-B3M_i-pw.d.mts → kind-registry-C1n47C7h.d.mts} +52 -52
  23. package/dist/{kind-registry-Ba4PO4WC.mjs → kind-registry-C99h_-8t.mjs} +1 -1
  24. package/dist/{kind.error-CCjTB6kW.mjs → kind.error-DIaJpdUb.mjs} +2 -27
  25. package/dist/kinds/index.d.mts +1 -1
  26. package/dist/kinds/index.mjs +1 -1
  27. package/dist/{line-kind-Bndo6IS8.d.mts → line-kind-Ck3fVXzG.d.mts} +1 -1
  28. package/dist/{cart-event-catalog-BOP9aDhL.mjs → outbox-store-CWW8ppxS.mjs} +31 -31
  29. package/dist/{not-found.error-B6WYnAjX.mjs → price-changed.error-C-wGVcfc.mjs} +23 -47
  30. package/dist/{idempotency-record.entity-DIFXjN1V.d.mts → reservation.entity-b5cZ1ojx.d.mts} +72 -72
  31. package/dist/{shipping.bridge-DD4A_O0O.d.mts → shipping.bridge-CmQFTgSE.d.mts} +82 -82
  32. package/dist/state-transition.error-2fRLh3p0.mjs +26 -0
  33. package/dist/{saga-step-fn-Cyob38iU.d.mts → state-transitions-X_Eix5Iw.d.mts} +31 -30
  34. package/dist/state-transitions-e4z3Yhxb.mjs +61 -0
  35. package/dist/{bundle.kind-BdgnyKZt.d.mts → variant.kind-9P1DXdXu.d.mts} +51 -51
  36. package/dist/{bundle.kind-DFydSxV_.mjs → variant.kind-DfEh2oku.mjs} +133 -133
  37. package/package.json +14 -7
  38. package/dist/saga-steps-B27LI7xp.mjs +0 -27
  39. package/dist/state-transitions-CpJpZZTK.mjs +0 -21
  40. /package/dist/{cart-status.vo-2iisZGhb.d.mts → cart-status.vo-CNJw4aaB.d.mts} +0 -0
  41. /package/dist/{domain-event-DHNkz15G.mjs → domain-event-CIEORKF6.mjs} +0 -0
  42. /package/dist/{id.port-C3rlDAKP.mjs → id.port-BhbFZJPm.mjs} +0 -0
  43. /package/dist/{id.port-DPXLrqb2.d.mts → id.port-C7ygWLRU.d.mts} +0 -0
  44. /package/dist/{index-DEHBdV_z.d.mts → index-2Ag-54t8.d.mts} +0 -0
  45. /package/dist/{outbox-store-CTWz9pvG.d.mts → outbox-store-CBt9fSYh.d.mts} +0 -0
@@ -1,4 +1,4 @@
1
- import { r as CartError } from "./kind.error-CCjTB6kW.mjs";
1
+ import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
2
2
  //#region src/domain/errors/concurrency.error.ts
3
3
  /**
4
4
  * Optimistic-lock mismatch. Thrown when a mutation attempts to update a
@@ -21,6 +21,27 @@ var ConcurrencyError = class extends CartError {
21
21
  }
22
22
  };
23
23
  //#endregion
24
+ //#region src/domain/errors/not-found.error.ts
25
+ /**
26
+ * The requested draft, checkout, or reservation does not exist (or is not
27
+ * visible under the caller's organizationId scope).
28
+ *
29
+ * Retryable is false — the resource simply does not exist. If the host
30
+ * thinks it should, the bug is upstream.
31
+ */
32
+ var NotFoundError = class extends CartError {
33
+ code = "cart/not_found";
34
+ category = "not_found";
35
+ retryable = false;
36
+ constructor(resource, ref, organizationId) {
37
+ super(`${resource} '${ref}' not found${organizationId ? ` in org ${organizationId}` : ""}`, {
38
+ resource,
39
+ ref,
40
+ organizationId
41
+ });
42
+ }
43
+ };
44
+ //#endregion
24
45
  //#region src/domain/errors/price-changed.error.ts
25
46
  /**
26
47
  * The re-run pricing snapshot's hash does not match the `expectedPricingHash`
@@ -47,49 +68,4 @@ var PriceChangedError = class extends CartError {
47
68
  }
48
69
  };
49
70
  //#endregion
50
- //#region src/domain/errors/state-transition.error.ts
51
- /**
52
- * A write attempted to transition `checkout.state` along an edge that
53
- * does not exist in the frozen state machine (see plan simplification —
54
- * `open → finalized | canceled`).
55
- *
56
- * Thrown by service methods before the mutation reaches the database.
57
- * Never retryable — the caller either has a bug or is racing another
58
- * writer. A concurrency race manifests as `ConcurrencyError` first via
59
- * the version check; if it reaches here, it is a logic bug.
60
- */
61
- var StateTransitionError = class extends CartError {
62
- code = "cart/illegal_state_transition";
63
- category = "state";
64
- retryable = false;
65
- constructor(checkoutId, from, to) {
66
- super(`Illegal checkout state transition on ${checkoutId}: ${from} -> ${to}`, {
67
- checkoutId,
68
- from,
69
- to
70
- });
71
- }
72
- };
73
- //#endregion
74
- //#region src/domain/errors/not-found.error.ts
75
- /**
76
- * The requested draft, checkout, or reservation does not exist (or is not
77
- * visible under the caller's organizationId scope).
78
- *
79
- * Retryable is false — the resource simply does not exist. If the host
80
- * thinks it should, the bug is upstream.
81
- */
82
- var NotFoundError = class extends CartError {
83
- code = "cart/not_found";
84
- category = "not_found";
85
- retryable = false;
86
- constructor(resource, ref, organizationId) {
87
- super(`${resource} '${ref}' not found${organizationId ? ` in org ${organizationId}` : ""}`, {
88
- resource,
89
- ref,
90
- organizationId
91
- });
92
- }
93
- };
94
- //#endregion
95
- export { ConcurrencyError as i, StateTransitionError as n, PriceChangedError as r, NotFoundError as t };
71
+ export { NotFoundError as n, ConcurrencyError as r, PriceChangedError as t };
@@ -1,7 +1,7 @@
1
- import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-2iisZGhb.mjs";
2
- import { o as IdempotencyReplay, s as OperationName, t as LineItem } from "./line-item.entity-B3M_i-pw.mjs";
3
- import { C as PricingSnapshot, l as AdjustmentSpec } from "./shipping.bridge-DD4A_O0O.mjs";
4
- import { a as CheckoutFlowState } from "./saga-step-fn-Cyob38iU.mjs";
1
+ import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
2
+ import { C as PricingSnapshot, m as AdjustmentSpec } from "./shipping.bridge-CmQFTgSE.mjs";
3
+ import { o as CheckoutFlowState } from "./state-transitions-X_Eix5Iw.mjs";
4
+ import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-C1n47C7h.mjs";
5
5
  import { Money } from "@classytic/primitives/money";
6
6
 
7
7
  //#region src/domain/entities/adjustment.entity.d.ts
@@ -45,6 +45,53 @@ interface Adjustment {
45
45
  appliedAt: Date;
46
46
  }
47
47
  //#endregion
48
+ //#region src/domain/entities/checkout.entity.d.ts
49
+ /**
50
+ * Checkout — the locked snapshot a draft produces when the host calls
51
+ * `createFromDraft()`.
52
+ *
53
+ * Deliberately minimal:
54
+ * - Frozen `lines`, `adjustments`, `pricing` (all captured from the draft)
55
+ * - Simple `state` field (`open | finalized | canceled`)
56
+ * - Optional `externalRef` the host attaches on commit — whatever opaque
57
+ * reference the host wants (order ID, Stripe payment intent, ERP
58
+ * invoice number). Cart never interprets it.
59
+ *
60
+ * Cart does NOT carry payment state, capture state, host order refs, or
61
+ * saga compensation bookkeeping. Those are the host's concern.
62
+ */
63
+ interface Checkout {
64
+ _id: string;
65
+ publicId: string;
66
+ organizationId: string;
67
+ draftId: string;
68
+ actorRef: string;
69
+ actorKind: 'user' | 'session';
70
+ state: CheckoutState;
71
+ /** Minimal transient flow state — for diagnostics and logging. */
72
+ flowState: CheckoutFlowState;
73
+ /** Frozen line snapshot. */
74
+ lines: readonly LineItem[];
75
+ /** Frozen adjustment snapshot. */
76
+ adjustments: readonly Adjustment[];
77
+ currency: string;
78
+ /** Frozen pricing — never mutated. */
79
+ pricing: PricingSnapshot;
80
+ /**
81
+ * Opaque reference the host attaches on commit. May be an order ID,
82
+ * a payment intent, an ERP invoice number — cart does not interpret.
83
+ * Populated only after `commit(checkoutId, externalRef)`.
84
+ */
85
+ externalRef?: string | null;
86
+ /** Reason string attached on cancel. */
87
+ canceledReason?: string | null;
88
+ version: number;
89
+ metadata?: Record<string, unknown>;
90
+ privateMetadata?: Record<string, unknown>;
91
+ createdAt: Date;
92
+ updatedAt: Date;
93
+ }
94
+ //#endregion
48
95
  //#region src/domain/entities/draft.entity.d.ts
49
96
  /**
50
97
  * Draft — the mutable cart the buyer interacts with before checkout.
@@ -90,51 +137,36 @@ interface Draft {
90
137
  updatedAt: Date;
91
138
  }
92
139
  //#endregion
93
- //#region src/domain/entities/checkout.entity.d.ts
140
+ //#region src/domain/entities/idempotency-record.entity.d.ts
94
141
  /**
95
- * Checkout — the locked snapshot a draft produces when the host calls
96
- * `createFromDraft()`.
142
+ * IdempotencyRecord — one row per (org, cartRef, op, actor, key) attempt.
97
143
  *
98
- * Deliberately minimal:
99
- * - Frozen `lines`, `adjustments`, `pricing` (all captured from the draft)
100
- * - Simple `state` field (`open | finalized | canceled`)
101
- * - Optional `externalRef` the host attaches on commit — whatever opaque
102
- * reference the host wants (order ID, Stripe payment intent, ERP
103
- * invoice number). Cart never interprets it.
144
+ * See plan §2 — Idempotency identity is composite, and the Replay storage
145
+ * rules (inline vs pointer) and the 6-state crash-window table.
104
146
  *
105
- * Cart does NOT carry payment state, capture state, host order refs, or
106
- * saga compensation bookkeeping. Those are the host's concern.
147
+ * Stored in a dedicated `cart_idempotency` collection with a unique compound
148
+ * index on the composite identity.
107
149
  */
108
- interface Checkout {
150
+ interface IdempotencyRecord {
109
151
  _id: string;
110
- publicId: string;
111
152
  organizationId: string;
112
- draftId: string;
153
+ cartRef: string;
154
+ operation: OperationName;
113
155
  actorRef: string;
114
- actorKind: 'user' | 'session';
115
- state: CheckoutState;
116
- /** Minimal transient flow state — for diagnostics and logging. */
117
- flowState: CheckoutFlowState;
118
- /** Frozen line snapshot. */
119
- lines: readonly LineItem[];
120
- /** Frozen adjustment snapshot. */
121
- adjustments: readonly Adjustment[];
122
- currency: string;
123
- /** Frozen pricing — never mutated. */
124
- pricing: PricingSnapshot;
156
+ idempotencyKey: string;
157
+ status: 'in_flight' | 'succeeded' | 'failed';
125
158
  /**
126
- * Opaque reference the host attaches on commit. May be an order ID,
127
- * a payment intent, an ERP invoice number — cart does not interpret.
128
- * Populated only after `commit(checkoutId, externalRef)`.
159
+ * Replay payload — either inline (small results) or a pointer to
160
+ * `cart_operation_results` (large results). Absent on 'in_flight' records.
129
161
  */
130
- externalRef?: string | null;
131
- /** Reason string attached on cancel. */
132
- canceledReason?: string | null;
133
- version: number;
134
- metadata?: Record<string, unknown>;
135
- privateMetadata?: Record<string, unknown>;
162
+ replay?: IdempotencyReplay;
163
+ /** Unique token minted on insert. Used by retries to claim expired leases. */
164
+ leaseToken: string;
165
+ /** When the current lease expires — default insert + 30s. */
166
+ leaseExpiresAt: Date;
136
167
  createdAt: Date;
137
- updatedAt: Date;
168
+ /** Set when status transitions to 'succeeded' or 'failed'. */
169
+ completedAt?: Date;
138
170
  }
139
171
  //#endregion
140
172
  //#region src/domain/entities/reservation.entity.d.ts
@@ -186,36 +218,4 @@ interface Reservation {
186
218
  updatedAt: Date;
187
219
  }
188
220
  //#endregion
189
- //#region src/domain/entities/idempotency-record.entity.d.ts
190
- /**
191
- * IdempotencyRecord — one row per (org, cartRef, op, actor, key) attempt.
192
- *
193
- * See plan §2 — Idempotency identity is composite, and the Replay storage
194
- * rules (inline vs pointer) and the 6-state crash-window table.
195
- *
196
- * Stored in a dedicated `cart_idempotency` collection with a unique compound
197
- * index on the composite identity.
198
- */
199
- interface IdempotencyRecord {
200
- _id: string;
201
- organizationId: string;
202
- cartRef: string;
203
- operation: OperationName;
204
- actorRef: string;
205
- idempotencyKey: string;
206
- status: 'in_flight' | 'succeeded' | 'failed';
207
- /**
208
- * Replay payload — either inline (small results) or a pointer to
209
- * `cart_operation_results` (large results). Absent on 'in_flight' records.
210
- */
211
- replay?: IdempotencyReplay;
212
- /** Unique token minted on insert. Used by retries to claim expired leases. */
213
- leaseToken: string;
214
- /** When the current lease expires — default insert + 30s. */
215
- leaseExpiresAt: Date;
216
- createdAt: Date;
217
- /** Set when status transitions to 'succeeded' or 'failed'. */
218
- completedAt?: Date;
219
- }
220
- //#endregion
221
- export { Adjustment as a, Draft as i, Reservation as n, Checkout as r, IdempotencyRecord as t };
221
+ export { Adjustment as a, Checkout as i, IdempotencyRecord as n, Draft as r, Reservation as t };
@@ -190,6 +190,87 @@ interface BridgeRef<TPayload = Record<string, unknown>> {
190
190
  payload: TPayload;
191
191
  }
192
192
  //#endregion
193
+ //#region src/domain/ports/promotions.bridge.d.ts
194
+ /**
195
+ * PromotionsBridge — authoritative for promotion rule evaluation.
196
+ *
197
+ * Cart ships NO default rules engine. Every host brings its own — Shopify-
198
+ * script-like, Saleor predicates, Odoo pricelists, or a custom rules engine.
199
+ * The pricing pipeline's promo-apply step does nothing more than call
200
+ * `evaluate()`, sort the results, and turn them into adjustment line items.
201
+ *
202
+ * See plan §6 — Promotions ownership.
203
+ */
204
+ interface PromotionsBridge {
205
+ /**
206
+ * Evaluate the provided snapshot against the host's rules.
207
+ *
208
+ * Called on every pricing pipeline run — including draft mutations, not
209
+ * just finalize. Must be fast. Expensive rule engines should cache
210
+ * internally.
211
+ */
212
+ evaluate(snapshot: CartSnapshot, ctx: OperationContext$1): Promise<PromotionResult[]>;
213
+ /**
214
+ * Optional — preview a single promo code against a snapshot without
215
+ * applying it. Used by frontend widgets that want to validate a coupon
216
+ * before commit. Returning null means "does not apply".
217
+ */
218
+ preview?(code: string, snapshot: CartSnapshot, ctx: OperationContext$1): Promise<PromotionResult | null>;
219
+ }
220
+ /**
221
+ * The subset of cart state the bridge needs to evaluate rules.
222
+ *
223
+ * Deliberately decoupled from the Draft/Checkout entity types so bridges
224
+ * don't pick up schema dependencies.
225
+ */
226
+ interface CartSnapshot {
227
+ organizationId: string;
228
+ actorRef: string;
229
+ actorKind: 'user' | 'session';
230
+ currency: string;
231
+ lines: readonly PricedLine[];
232
+ subtotal: Money;
233
+ appliedPromoCodes: readonly string[];
234
+ metadata?: Record<string, unknown>;
235
+ }
236
+ /**
237
+ * A single promotion-engine verdict.
238
+ *
239
+ * Cart applies these in priority order (descending). Order-level results
240
+ * have `targetLineId: null`. Gifts are represented as a GiftRef the bridge
241
+ * returns; cart adds a corresponding line item with zero price and links it
242
+ * to the promotion rule for audit.
243
+ */
244
+ interface PromotionResult {
245
+ /** Opaque rule reference — cart does not interpret. */
246
+ ruleRef: string;
247
+ /** Optional line targeted by this discount, or null for order-level. */
248
+ targetLineId: string | null;
249
+ /** The adjustment. See AdjustmentSpec below. */
250
+ adjustment: AdjustmentSpec;
251
+ /** Stacking order. Higher runs first. */
252
+ priority: number;
253
+ /** Optional human-readable explanation — displayed in cart / receipt. */
254
+ explanation?: string;
255
+ /** Opaque metadata propagated to audit + outbox events. */
256
+ metadata?: Record<string, unknown>;
257
+ }
258
+ type AdjustmentSpec = {
259
+ type: 'percent';
260
+ value: number;
261
+ } | {
262
+ type: 'fixed';
263
+ value: Money;
264
+ } | {
265
+ type: 'gift';
266
+ skuRef: string;
267
+ quantity: number;
268
+ } | {
269
+ type: 'shipping';
270
+ mode: 'free' | 'percent' | 'fixed';
271
+ value?: number | Money;
272
+ };
273
+ //#endregion
193
274
  //#region src/domain/ports/catalog.bridge.d.ts
194
275
  /**
195
276
  * CatalogBridge — answers product questions for the cart engine.
@@ -347,87 +428,6 @@ interface ReservationRequest {
347
428
  */
348
429
  type ReservationRef = BridgeRef;
349
430
  //#endregion
350
- //#region src/domain/ports/promotions.bridge.d.ts
351
- /**
352
- * PromotionsBridge — authoritative for promotion rule evaluation.
353
- *
354
- * Cart ships NO default rules engine. Every host brings its own — Shopify-
355
- * script-like, Saleor predicates, Odoo pricelists, or a custom rules engine.
356
- * The pricing pipeline's promo-apply step does nothing more than call
357
- * `evaluate()`, sort the results, and turn them into adjustment line items.
358
- *
359
- * See plan §6 — Promotions ownership.
360
- */
361
- interface PromotionsBridge {
362
- /**
363
- * Evaluate the provided snapshot against the host's rules.
364
- *
365
- * Called on every pricing pipeline run — including draft mutations, not
366
- * just finalize. Must be fast. Expensive rule engines should cache
367
- * internally.
368
- */
369
- evaluate(snapshot: CartSnapshot, ctx: OperationContext$1): Promise<PromotionResult[]>;
370
- /**
371
- * Optional — preview a single promo code against a snapshot without
372
- * applying it. Used by frontend widgets that want to validate a coupon
373
- * before commit. Returning null means "does not apply".
374
- */
375
- preview?(code: string, snapshot: CartSnapshot, ctx: OperationContext$1): Promise<PromotionResult | null>;
376
- }
377
- /**
378
- * The subset of cart state the bridge needs to evaluate rules.
379
- *
380
- * Deliberately decoupled from the Draft/Checkout entity types so bridges
381
- * don't pick up schema dependencies.
382
- */
383
- interface CartSnapshot {
384
- organizationId: string;
385
- actorRef: string;
386
- actorKind: 'user' | 'session';
387
- currency: string;
388
- lines: readonly PricedLine[];
389
- subtotal: Money;
390
- appliedPromoCodes: readonly string[];
391
- metadata?: Record<string, unknown>;
392
- }
393
- /**
394
- * A single promotion-engine verdict.
395
- *
396
- * Cart applies these in priority order (descending). Order-level results
397
- * have `targetLineId: null`. Gifts are represented as a GiftRef the bridge
398
- * returns; cart adds a corresponding line item with zero price and links it
399
- * to the promotion rule for audit.
400
- */
401
- interface PromotionResult {
402
- /** Opaque rule reference — cart does not interpret. */
403
- ruleRef: string;
404
- /** Optional line targeted by this discount, or null for order-level. */
405
- targetLineId: string | null;
406
- /** The adjustment. See AdjustmentSpec below. */
407
- adjustment: AdjustmentSpec;
408
- /** Stacking order. Higher runs first. */
409
- priority: number;
410
- /** Optional human-readable explanation — displayed in cart / receipt. */
411
- explanation?: string;
412
- /** Opaque metadata propagated to audit + outbox events. */
413
- metadata?: Record<string, unknown>;
414
- }
415
- type AdjustmentSpec = {
416
- type: 'percent';
417
- value: number;
418
- } | {
419
- type: 'fixed';
420
- value: Money;
421
- } | {
422
- type: 'gift';
423
- skuRef: string;
424
- quantity: number;
425
- } | {
426
- type: 'shipping';
427
- mode: 'free' | 'percent' | 'fixed';
428
- value?: number | Money;
429
- };
430
- //#endregion
431
431
  //#region src/domain/ports/tax.bridge.d.ts
432
432
  /**
433
433
  * TaxBridge — compute line-level taxes from post-promo line amounts.
@@ -535,4 +535,4 @@ interface ShippingMethod {
535
535
  };
536
536
  }
537
537
  //#endregion
538
- export { PricingSnapshot as C, PricedLine as S, ProductSummary as _, TaxBreakdown as a, BridgeStatus as b, TaxCalculationResult as c, PromotionResult as d, PromotionsBridge as f, CatalogBridge as g, ReservationRequest as h, ShippingQuoteRequest as i, AdjustmentSpec as l, ReservationRef as m, ShippingMethod as n, TaxBridge as o, InventoryBridge as p, ShippingQuote as r, TaxCalculationRequest as s, ShippingBridge as t, CartSnapshot as u, Address as v, OperationContext$1 as x, BridgeRef as y };
538
+ export { PricingSnapshot as C, PricedLine as S, PromotionsBridge as _, TaxBreakdown as a, BridgeStatus as b, TaxCalculationResult as c, ReservationRequest as d, CatalogBridge as f, PromotionResult as g, CartSnapshot as h, ShippingQuoteRequest as i, InventoryBridge as l, AdjustmentSpec as m, ShippingMethod as n, TaxBridge as o, ProductSummary as p, ShippingQuote as r, TaxCalculationRequest as s, ShippingBridge as t, ReservationRef as u, Address as v, OperationContext$1 as x, BridgeRef as y };
@@ -0,0 +1,26 @@
1
+ import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
2
+ //#region src/domain/errors/state-transition.error.ts
3
+ /**
4
+ * A write attempted to transition `checkout.state` along an edge that
5
+ * does not exist in the frozen state machine (see plan simplification —
6
+ * `open → finalized | canceled`).
7
+ *
8
+ * Thrown by service methods before the mutation reaches the database.
9
+ * Never retryable — the caller either has a bug or is racing another
10
+ * writer. A concurrency race manifests as `ConcurrencyError` first via
11
+ * the version check; if it reaches here, it is a logic bug.
12
+ */
13
+ var StateTransitionError = class extends CartError {
14
+ code = "cart/illegal_state_transition";
15
+ category = "state";
16
+ retryable = false;
17
+ constructor(checkoutId, from, to) {
18
+ super(`Illegal checkout state transition on ${checkoutId}: ${from} -> ${to}`, {
19
+ checkoutId,
20
+ from,
21
+ to
22
+ });
23
+ }
24
+ };
25
+ //#endregion
26
+ export { StateTransitionError as t };
@@ -1,7 +1,8 @@
1
- import { t as CheckoutState } from "./cart-status.vo-2iisZGhb.mjs";
2
- import { x as OperationContext } from "./shipping.bridge-DD4A_O0O.mjs";
3
- import { t as KindBridges } from "./line-kind-Bndo6IS8.mjs";
4
- import { i as ClockPort, t as IdPort } from "./id.port-DPXLrqb2.mjs";
1
+ import { t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
2
+ import { x as OperationContext } from "./shipping.bridge-CmQFTgSE.mjs";
3
+ import { t as KindBridges } from "./line-kind-Ck3fVXzG.mjs";
4
+ import { i as ClockPort, t as IdPort } from "./id.port-C7ygWLRU.mjs";
5
+ import * as _$_classytic_primitives_state_machine0 from "@classytic/primitives/state-machine";
5
6
 
6
7
  //#region src/domain/saga/saga-steps.d.ts
7
8
  /**
@@ -23,14 +24,6 @@ declare const CheckoutStep: {
23
24
  readonly Commit: 5;
24
25
  };
25
26
  type CheckoutStepNumber = (typeof CheckoutStep)[keyof typeof CheckoutStep];
26
- declare const SagaStep: {
27
- /** Step 1 — load draft + validate status + version. */readonly LoadDraft: 1; /** Step 2 — re-run kind.revalidate() on stale lines. */
28
- readonly Revalidate: 2; /** Step 3 — re-run pricing pipeline, compare expectedPricingHash. */
29
- readonly Reprice: 3; /** Step 4 — create the checkout document with the frozen snapshot. */
30
- readonly CreateCheckout: 4; /** Step 5 — commit (host-called after its own external work succeeds). */
31
- readonly Commit: 5;
32
- };
33
- type SagaStepNumber = CheckoutStepNumber;
34
27
  //#endregion
35
28
  //#region src/domain/saga/saga-state.d.ts
36
29
  /**
@@ -53,21 +46,6 @@ interface CheckoutFlowState {
53
46
  /** ISO timestamp of the first step (checkout creation). */
54
47
  startedAt: string;
55
48
  }
56
- type SagaState = CheckoutFlowState;
57
- //#endregion
58
- //#region src/domain/saga/state-transitions.d.ts
59
- /**
60
- * Frozen state transitions for Checkout.state. Three states, two
61
- * terminal outcomes — finalized (success) or canceled (failure / manual
62
- * cancel / abandonment).
63
- *
64
- * Enforced by `CheckoutRepository.updateWithVersion` callers: the
65
- * service methods pass the expected current state in the filter so
66
- * racing writers see exactly one winner.
67
- */
68
- declare const CHECKOUT_STATE_TRANSITIONS: Record<CheckoutState, readonly CheckoutState[]>;
69
- /** Predicate — is `to` a legal transition from `from`? */
70
- declare function isLegalCheckoutTransition(from: CheckoutState, to: CheckoutState): boolean;
71
49
  //#endregion
72
50
  //#region src/domain/saga/saga-step-fn.d.ts
73
51
  /**
@@ -95,8 +73,8 @@ declare function isLegalCheckoutTransition(from: CheckoutState, to: CheckoutStat
95
73
  * exact previous result.
96
74
  */
97
75
  interface SagaStepFn<TInput, TOutput> {
98
- /** Step number in the fixed 11-step sequence. */
99
- readonly step: SagaStepNumber;
76
+ /** Step number in the checkout flow. */
77
+ readonly step: CheckoutStepNumber;
100
78
  /** Stable name for logging / metrics / activity registration. */
101
79
  readonly name: string;
102
80
  /**
@@ -132,4 +110,27 @@ interface SagaDependencies {
132
110
  readonly id: IdPort;
133
111
  }
134
112
  //#endregion
135
- export { CheckoutFlowState as a, CheckoutStepNumber as c, isLegalCheckoutTransition as i, SagaStep as l, SagaStepFn as n, SagaState as o, CHECKOUT_STATE_TRANSITIONS as r, CheckoutStep as s, SagaDependencies as t, SagaStepNumber as u };
113
+ //#region src/domain/saga/state-transitions.d.ts
114
+ /**
115
+ * Frozen state transitions for Checkout.state. Three states, two
116
+ * terminal outcomes — finalized (success) or canceled (failure / manual
117
+ * cancel / abandonment).
118
+ *
119
+ * Enforced by `CheckoutRepository.updateWithVersion` callers: the
120
+ * service methods pass the expected current state in the filter so
121
+ * racing writers see exactly one winner.
122
+ */
123
+ declare const CHECKOUT_STATE_TRANSITIONS: Record<CheckoutState, readonly CheckoutState[]>;
124
+ /**
125
+ * Checkout state machine — single throw site, declarative table.
126
+ *
127
+ * Wires cart's domain `StateTransitionError` (with code
128
+ * `cart/illegal_state_transition` and structured `{ checkoutId, from, to }`
129
+ * meta) via `errorFactory`, so existing catch sites that match on
130
+ * `error.code` or `instanceof StateTransitionError` keep working.
131
+ */
132
+ declare const CHECKOUT_MACHINE: _$_classytic_primitives_state_machine0.StateMachine<CheckoutState>;
133
+ /** Predicate — is `to` a legal transition from `from`? */
134
+ declare function isLegalCheckoutTransition(from: CheckoutState, to: CheckoutState): boolean;
135
+ //#endregion
136
+ export { SagaStepFn as a, CheckoutStepNumber as c, SagaDependencies as i, CHECKOUT_STATE_TRANSITIONS as n, CheckoutFlowState as o, isLegalCheckoutTransition as r, CheckoutStep as s, CHECKOUT_MACHINE as t };
@@ -0,0 +1,61 @@
1
+ import { t as StateTransitionError } from "./state-transition.error-2fRLh3p0.mjs";
2
+ import { defineStateMachine } from "@classytic/primitives/state-machine";
3
+ //#region src/domain/saga/saga-steps.ts
4
+ /**
5
+ * Checkout flow steps. Deliberately minimal — cart's job is to freeze a
6
+ * snapshot and transition its state. Everything external (payment, order
7
+ * creation, fulfillment) is the host's problem.
8
+ *
9
+ * This enum exists purely for logging / metrics / ordered state-transition
10
+ * dispatch. Cart does not run a "saga engine" — the `CheckoutRepository`
11
+ * domain methods run these steps in plain sequential code and let
12
+ * exceptions propagate. Compensation is one operation (`cancel`) rather
13
+ * than a reverse walk of a multi-step chain.
14
+ */
15
+ const CheckoutStep = {
16
+ /** Step 1 — load draft + validate status + version. */
17
+ LoadDraft: 1,
18
+ /** Step 2 — re-run kind.revalidate() on stale lines. */
19
+ Revalidate: 2,
20
+ /** Step 3 — re-run pricing pipeline, compare expectedPricingHash. */
21
+ Reprice: 3,
22
+ /** Step 4 — create the checkout document with the frozen snapshot. */
23
+ CreateCheckout: 4,
24
+ /** Step 5 — commit (host-called after its own external work succeeds). */
25
+ Commit: 5
26
+ };
27
+ //#endregion
28
+ //#region src/domain/saga/state-transitions.ts
29
+ /**
30
+ * Frozen state transitions for Checkout.state. Three states, two
31
+ * terminal outcomes — finalized (success) or canceled (failure / manual
32
+ * cancel / abandonment).
33
+ *
34
+ * Enforced by `CheckoutRepository.updateWithVersion` callers: the
35
+ * service methods pass the expected current state in the filter so
36
+ * racing writers see exactly one winner.
37
+ */
38
+ const CHECKOUT_STATE_TRANSITIONS = {
39
+ open: ["finalized", "canceled"],
40
+ finalized: [],
41
+ canceled: []
42
+ };
43
+ /**
44
+ * Checkout state machine — single throw site, declarative table.
45
+ *
46
+ * Wires cart's domain `StateTransitionError` (with code
47
+ * `cart/illegal_state_transition` and structured `{ checkoutId, from, to }`
48
+ * meta) via `errorFactory`, so existing catch sites that match on
49
+ * `error.code` or `instanceof StateTransitionError` keep working.
50
+ */
51
+ const CHECKOUT_MACHINE = defineStateMachine({
52
+ name: "Checkout",
53
+ transitions: CHECKOUT_STATE_TRANSITIONS,
54
+ errorFactory: ({ entityId, from, to }) => new StateTransitionError(entityId, from, to)
55
+ });
56
+ /** Predicate — is `to` a legal transition from `from`? */
57
+ function isLegalCheckoutTransition(from, to) {
58
+ return CHECKOUT_MACHINE.canTransition(from, to);
59
+ }
60
+ //#endregion
61
+ export { CheckoutStep as i, CHECKOUT_STATE_TRANSITIONS as n, isLegalCheckoutTransition as r, CHECKOUT_MACHINE as t };