@classytic/cart 0.1.1 → 0.1.3

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 (44) hide show
  1. package/dist/{cart-event-catalog-BIbi2Q_n.d.mts → cart-event-catalog-BxDJhtTM.d.mts} +1 -1
  2. package/dist/cart.error-BwWy4RlY.mjs +27 -0
  3. package/dist/{shipping.bridge-_VwuKCSE.d.mts → clock.port-BUe6Dk_M.d.mts} +27 -10
  4. package/dist/{create-cart-DRYSw5Bj.mjs → create-cart-4wql1XGi.mjs} +33 -15
  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-iFWUnl8m.mjs → errors-7Pd0yATM.mjs} +2 -27
  18. package/dist/{id.port-CpYO7sc1.d.mts → id.port-DitjeoHg.d.mts} +1 -19
  19. package/dist/{index-PD-kf5pR.d.mts → index-qfN8dZN9.d.mts} +7 -6
  20. package/dist/index.d.mts +14 -14
  21. package/dist/index.mjs +14 -13
  22. package/dist/{internal-event-bus-BGcwAeqK.d.mts → internal-event-bus-DhSLiZHi.d.mts} +5 -5
  23. package/dist/{kind-registry-Ba4PO4WC.mjs → kind-registry-C99h_-8t.mjs} +1 -1
  24. package/dist/{kind-registry-CqOJHV-2.d.mts → kind-registry-D03c2VV5.d.mts} +1 -1
  25. package/dist/{kind.error-CCjTB6kW.mjs → kind.error-DIaJpdUb.mjs} +2 -27
  26. package/dist/kinds/index.d.mts +2 -2
  27. package/dist/kinds/index.mjs +2 -2
  28. package/dist/{line-kind-DOYygKG4.d.mts → line-kind-CKOWafK0.d.mts} +11 -6
  29. package/dist/{outbox-store-bP30uBXd.mjs → outbox-store-CWW8ppxS.mjs} +1 -1
  30. package/dist/{reservation.entity-gmeCFe8a.d.mts → reservation.entity-WdaZCJg9.d.mts} +4 -4
  31. package/dist/{state-transition.error-CML7cQSd.mjs → stale-quote.error-BkFLXWo5.mjs} +24 -22
  32. package/dist/state-transition.error-2fRLh3p0.mjs +26 -0
  33. package/dist/state-transitions-Bm3lC2Uv.mjs +61 -0
  34. package/dist/{state-transitions-CbPYzeca.d.mts → state-transitions-D8CRykBv.d.mts} +19 -9
  35. package/dist/{variant.kind-CCwwWAB6.d.mts → variant.kind-Cpo_Hh7G.d.mts} +65 -2
  36. package/dist/{variant.kind-BpEzENX-.mjs → variant.kind-z2gwH9Vo.mjs} +93 -11
  37. package/package.json +8 -6
  38. package/dist/saga-steps-aP8iTHT3.mjs +0 -26
  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/{index-DNLi60D-.d.mts → index-2Ag-54t8.d.mts} +0 -0
  44. /package/dist/{outbox-store-CTWz9pvG.d.mts → outbox-store-CBt9fSYh.d.mts} +0 -0
@@ -1,8 +1,8 @@
1
- import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CTWz9pvG.mjs";
2
- import { _ as PromotionsBridge, f as CatalogBridge, l as InventoryBridge, o as TaxBridge, t as ShippingBridge, x as OperationContext } from "./shipping.bridge-_VwuKCSE.mjs";
3
- import { l as LineDisplay, r as LineKind } from "./line-kind-DOYygKG4.mjs";
4
- import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-CqOJHV-2.mjs";
5
- import { i as ClockPort, t as IdPort } from "./id.port-CpYO7sc1.mjs";
1
+ import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CBt9fSYh.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";
@@ -1,4 +1,4 @@
1
- import { n as UnknownKindError } from "./kind.error-CCjTB6kW.mjs";
1
+ import { n as UnknownKindError } from "./kind.error-DIaJpdUb.mjs";
2
2
  //#region src/domain/kinds/kind-registry.ts
3
3
  /**
4
4
  * Build a KindRegistry from a list of LineKind implementations.
@@ -1,4 +1,4 @@
1
- import { l as LineDisplay, r as LineKind } from "./line-kind-DOYygKG4.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,29 +1,4 @@
1
- //#region src/domain/errors/cart.error.ts
2
- var CartError = class extends Error {
3
- /** Optional structured context for logging / debugging. */
4
- context;
5
- constructor(message, context) {
6
- super(message);
7
- this.name = new.target.name;
8
- this.context = context;
9
- Object.setPrototypeOf(this, new.target.prototype);
10
- }
11
- /**
12
- * Serialize to a wire-safe shape. Suitable for HTTP error bodies and
13
- * structured logging. Never includes stack frames.
14
- */
15
- toJSON() {
16
- return {
17
- name: this.name,
18
- code: this.code,
19
- category: this.category,
20
- message: this.message,
21
- retryable: this.retryable,
22
- context: this.context
23
- };
24
- }
25
- };
26
- //#endregion
1
+ import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
27
2
  //#region src/domain/errors/kind.error.ts
28
3
  /**
29
4
  * A LineKind rejected a line during validate() or price().
@@ -66,4 +41,4 @@ var UnknownKindError = class extends CartError {
66
41
  }
67
42
  };
68
43
  //#endregion
69
- export { UnknownKindError as n, CartError as r, KindError as t };
44
+ export { UnknownKindError as n, KindError as t };
@@ -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-CCwwWAB6.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-BpEzENX-.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 };
@@ -1,4 +1,4 @@
1
- import { S as PricedLine, _ as PromotionsBridge, f as CatalogBridge, l as InventoryBridge, o as TaxBridge, t as ShippingBridge, u as ReservationRef, x as OperationContext } from "./shipping.bridge-_VwuKCSE.mjs";
1
+ import { C as OperationContext, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, w as PricedLine, y as PromotionsBridge } from "./clock.port-BUe6Dk_M.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { z } from "zod";
4
4
 
@@ -19,10 +19,10 @@ import { z } from "zod";
19
19
  * cache to manage.
20
20
  *
21
21
  * **Staleness.** The snapshot can drift from the live catalog (product
22
- * renamed, image updated). Revalidation at finalize catches price drift
23
- * via `LineKind.revalidate()`. Display drift is almost always acceptable
24
- * — the user already saw the name + image they wanted — but hosts that
25
- * care about absolute freshness can refresh by calling `displayOf()`
22
+ * renamed, image updated). Checkout's pricingHash and expiry checks catch
23
+ * price drift. Display drift is almost always acceptable — the user already
24
+ * saw the name + image they wanted — but hosts that care about absolute
25
+ * freshness can refresh by calling `displayOf()`
26
26
  * again from their own cron or webhook consumer.
27
27
  *
28
28
  * All fields are optional so hosts can populate only what they need.
@@ -70,7 +70,7 @@ interface ValidityPolicy {
70
70
  /**
71
71
  * reprice — silently re-run price() and continue. Suitable for bundles,
72
72
  * group-buy, and other cases where drift is acceptable.
73
- * error — abort finalize with StaleQuoteError; the client must
73
+ * error — abort checkout with StaleQuoteError; the client must
74
74
  * re-display and re-confirm. Required for bids, timeslots,
75
75
  * rentals, and anything auction-like.
76
76
  * extend — treat as indefinitely valid. Only for catalog SKUs where
@@ -187,6 +187,11 @@ interface LineLike<TPayload = unknown> {
187
187
  * one type; adding a new bridge to the engine does not break existing kinds.
188
188
  */
189
189
  interface KindContext extends OperationContext {
190
+ /**
191
+ * Engine clock for deterministic validity windows. Older direct kind tests
192
+ * may omit it; engine-created contexts always provide it.
193
+ */
194
+ readonly clock?: ClockPort;
190
195
  /**
191
196
  * Bridge registry. Keys match the bridge names in CartConfig. Values are
192
197
  * typed via the interface augmentation in `engine-types.ts`.
@@ -1,4 +1,4 @@
1
- import { n as CartEvents, t as createCartEvent } from "./domain-event-DHNkz15G.mjs";
1
+ import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
2
2
  import { InvalidOutboxEventError, OutboxOwnershipError } from "@classytic/primitives/outbox";
3
3
  //#region src/domain/events/event-definition.ts
4
4
  function defineCartEvent(input) {
@@ -1,7 +1,7 @@
1
- import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-2iisZGhb.mjs";
2
- import { C as PricingSnapshot, m as AdjustmentSpec } from "./shipping.bridge-_VwuKCSE.mjs";
3
- import { a as CheckoutFlowState } from "./state-transitions-CbPYzeca.mjs";
4
- import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-CqOJHV-2.mjs";
1
+ import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
2
+ import { T as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-BUe6Dk_M.mjs";
3
+ import { o as CheckoutFlowState } from "./state-transitions-D8CRykBv.mjs";
4
+ import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-D03c2VV5.mjs";
5
5
  import { Money } from "@classytic/primitives/money";
6
6
 
7
7
  //#region src/domain/entities/adjustment.entity.d.ts
@@ -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
@@ -44,11 +44,12 @@ var NotFoundError = class extends CartError {
44
44
  //#endregion
45
45
  //#region src/domain/errors/price-changed.error.ts
46
46
  /**
47
- * The re-run pricing snapshot's hash does not match the `expectedPricingHash`
48
- * the client supplied when initiating finalize. Fired from saga step 3.
47
+ * The stored pricing snapshot's hash does not match the `expectedPricingHash`
48
+ * the client supplied when initiating checkout. Fired from the cheap hash
49
+ * check before the checkout snapshot is frozen.
49
50
  *
50
51
  * This is a safety interlock: the client saw totals X, but by the time the
51
- * saga ran, totals are now Y. Rather than silently charging a different
52
+ * checkout ran, totals are now Y. Rather than silently charging a different
52
53
  * amount, the saga aborts with this error so the client re-displays and
53
54
  * re-confirms.
54
55
  *
@@ -68,28 +69,29 @@ var PriceChangedError = class extends CartError {
68
69
  }
69
70
  };
70
71
  //#endregion
71
- //#region src/domain/errors/state-transition.error.ts
72
+ //#region src/domain/errors/stale-quote.error.ts
72
73
  /**
73
- * A write attempted to transition `checkout.state` along an edge that
74
- * does not exist in the frozen state machine (see plan simplification —
75
- * `open → finalized | canceled`).
74
+ * A priced line's validity window has elapsed. Fired during checkout's
75
+ * freshness check before the snapshot is frozen.
76
76
  *
77
- * Thrown by service methods before the mutation reaches the database.
78
- * Never retryable — the caller either has a bug or is racing another
79
- * writer. A concurrency race manifests as `ConcurrencyError` first via
80
- * the version check; if it reaches here, it is a logic bug.
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.
81
82
  */
82
- var StateTransitionError = class extends CartError {
83
- code = "cart/illegal_state_transition";
84
- category = "state";
85
- retryable = false;
86
- constructor(checkoutId, from, to) {
87
- super(`Illegal checkout state transition on ${checkoutId}: ${from} -> ${to}`, {
88
- checkoutId,
89
- from,
90
- to
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
91
93
  });
92
94
  }
93
95
  };
94
96
  //#endregion
95
- export { ConcurrencyError as i, PriceChangedError as n, NotFoundError as r, StateTransitionError as t };
97
+ export { ConcurrencyError as i, PriceChangedError as n, NotFoundError as r, StaleQuoteError as t };
@@ -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 };
@@ -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 — enforce stored snapshot freshness without extra bridge reads. */
19
+ Revalidate: 2,
20
+ /** Step 3 — compare stored pricingHash with 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 };
@@ -1,7 +1,8 @@
1
- import { t as CheckoutState } from "./cart-status.vo-2iisZGhb.mjs";
2
- import { x as OperationContext } from "./shipping.bridge-_VwuKCSE.mjs";
3
- import { t as KindBridges } from "./line-kind-DOYygKG4.mjs";
4
- import { i as ClockPort, t as IdPort } from "./id.port-CpYO7sc1.mjs";
1
+ import { t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
2
+ import { C as OperationContext, t as ClockPort } from "./clock.port-BUe6Dk_M.mjs";
3
+ import { t as KindBridges } from "./line-kind-CKOWafK0.mjs";
4
+ import { t as IdPort } from "./id.port-DitjeoHg.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
  /**
@@ -16,8 +17,8 @@ import { i as ClockPort, t as IdPort } from "./id.port-CpYO7sc1.mjs";
16
17
  * than a reverse walk of a multi-step chain.
17
18
  */
18
19
  declare const CheckoutStep: {
19
- /** Step 1 — load draft + validate status + version. */readonly LoadDraft: 1; /** Step 2 — re-run kind.revalidate() on stale lines. */
20
- readonly Revalidate: 2; /** Step 3 — re-run pricing pipeline, compare expectedPricingHash. */
20
+ /** Step 1 — load draft + validate status + version. */readonly LoadDraft: 1; /** Step 2 — enforce stored snapshot freshness without extra bridge reads. */
21
+ readonly Revalidate: 2; /** Step 3 — compare stored pricingHash with expectedPricingHash. */
21
22
  readonly Reprice: 3; /** Step 4 — create the checkout document with the frozen snapshot. */
22
23
  readonly CreateCheckout: 4; /** Step 5 — commit (host-called after its own external work succeeds). */
23
24
  readonly Commit: 5;
@@ -28,8 +29,8 @@ type CheckoutStepNumber = (typeof CheckoutStep)[keyof typeof CheckoutStep];
28
29
  /**
29
30
  * Transient checkout flow state stored on the Checkout document.
30
31
  *
31
- * In the simplified later model, the flow is short (load → revalidate →
32
- * reprice → create → commit/cancel) and each method is an atomic service
32
+ * In the simplified later model, the flow is short (load → freshness check →
33
+ * hash check → create → commit/cancel) and each method is an atomic service
33
34
  * call. There is no long-running saga, so this state is almost
34
35
  * decorative — it records the last successful step for diagnostics.
35
36
  *
@@ -120,7 +121,16 @@ interface SagaDependencies {
120
121
  * racing writers see exactly one winner.
121
122
  */
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>;
123
133
  /** Predicate — is `to` a legal transition from `from`? */
124
134
  declare function isLegalCheckoutTransition(from: CheckoutState, to: CheckoutState): boolean;
125
135
  //#endregion
126
- export { CheckoutFlowState as a, SagaStepFn as i, isLegalCheckoutTransition as n, CheckoutStep as o, SagaDependencies as r, CheckoutStepNumber as s, CHECKOUT_STATE_TRANSITIONS as t };
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 };
@@ -1,4 +1,5 @@
1
- import { r as LineKind } from "./line-kind-DOYygKG4.mjs";
1
+ import { r as LineKind } from "./line-kind-CKOWafK0.mjs";
2
+ import { Money } from "@classytic/primitives/money";
2
3
  import { z } from "zod";
3
4
 
4
5
  //#region src/kinds/bundle.kind.d.ts
@@ -31,6 +32,68 @@ declare const bundlePayloadSchema: z.ZodObject<{
31
32
  }, z.core.$strip>;
32
33
  declare const bundleKind: LineKind<BundlePayload>;
33
34
  //#endregion
35
+ //#region src/kinds/service-fee.kind.d.ts
36
+ /**
37
+ * `service-fee` — non-product upsell line for cart-wide add-ons.
38
+ *
39
+ * Models the per-order fees a host wants to surface as first-class line
40
+ * items: gift wrap, paper bag, rush handling, card-payment surcharge,
41
+ * cleaning fee on bookings, etc. Distinct from a product line because:
42
+ *
43
+ * - There is NO catalog SKU behind it. The line carries its own
44
+ * code + label + unit price; the host's "services" config table is
45
+ * the source of truth for valid codes (a 5-10 row JSON or collection
46
+ * in the host, not a catalog product).
47
+ * - It does NOT reserve inventory. There is nothing to ship; the fee
48
+ * ships with the products it accompanies (gift wrap goes in the same
49
+ * box as the gift).
50
+ * - It is NOT product-specific. One toggle on the cart adds the fee to
51
+ * the whole order; no need to attach a `modifierGroup` to every
52
+ * product the way catalog modifiers work.
53
+ *
54
+ * Use a catalog `modifierGroup` instead when the upsell is genuinely
55
+ * per-product (espresso → +decaf shot). Use this kind when the upsell is
56
+ * per-order (any cart → +gift wrap).
57
+ *
58
+ * Survives the cart → checkout snapshot → order trail naturally because
59
+ * `@classytic/order`'s OrderLine carries a free-form `kind: string` and
60
+ * the snapshot fields this kind populates (`sku`, `name`, `unitPrice`,
61
+ * `currency`, `requiresShipping: false`) are exactly the fields the
62
+ * order kernel persists. The order's `kind: 'service-fee'` discriminator
63
+ * lets refund / RMA / fulfillment handlers branch on the line type
64
+ * without inferring from the SKU shape.
65
+ */
66
+ interface ServiceFeePayload {
67
+ /**
68
+ * Stable code for the service the host bills (`gift-wrap`, `paper-bag`,
69
+ * `rush-handling`, `card-surcharge`). The host's services config
70
+ * resolves the code to a price + label; this kind takes both as
71
+ * payload so the cart line carries the full pricing surface
72
+ * end-to-end (no per-render bridge call).
73
+ */
74
+ code: string;
75
+ /**
76
+ * User-facing label rendered on the cart, receipt, and order detail
77
+ * (`Gift wrap`, `Paper bag`). Localized at call-site by the host.
78
+ */
79
+ label: string;
80
+ /**
81
+ * Per-unit price for the service in minor units of the cart's
82
+ * currency (e.g. paisa for BDT). Multiplied by `quantity` for the
83
+ * line total.
84
+ */
85
+ unitPrice: Money;
86
+ }
87
+ declare const serviceFeePayloadSchema: z.ZodObject<{
88
+ code: z.ZodString;
89
+ label: z.ZodString;
90
+ unitPrice: z.ZodObject<{
91
+ amount: z.ZodNumber;
92
+ currency: z.ZodString;
93
+ }, z.core.$strip>;
94
+ }, z.core.$strip>;
95
+ declare const serviceFeeKind: LineKind<ServiceFeePayload>;
96
+ //#endregion
34
97
  //#region src/kinds/sku.kind.d.ts
35
98
  /**
36
99
  * `sku` — the plain retail LineKind.
@@ -111,4 +174,4 @@ declare const variantPayloadSchema: z.ZodObject<{
111
174
  }, z.core.$strip>;
112
175
  declare const variantKind: LineKind<VariantPayload>;
113
176
  //#endregion
114
- export { timeslotKind as a, skuKind as c, BundlePayload as d, bundleKind as f, TimeslotPayload as i, skuPayloadSchema as l, variantKind as n, timeslotPayloadSchema as o, bundlePayloadSchema as p, variantPayloadSchema as r, SkuPayload as s, VariantPayload as t, BundleComponent as u };
177
+ export { timeslotKind as a, skuKind as c, serviceFeeKind as d, serviceFeePayloadSchema as f, bundlePayloadSchema as g, bundleKind as h, TimeslotPayload as i, skuPayloadSchema as l, BundlePayload as m, variantKind as n, timeslotPayloadSchema as o, BundleComponent as p, variantPayloadSchema as r, SkuPayload as s, VariantPayload as t, ServiceFeePayload as u };
@@ -1,4 +1,4 @@
1
- import { t as KindError } from "./kind.error-CCjTB6kW.mjs";
1
+ import { t as KindError } from "./kind.error-DIaJpdUb.mjs";
2
2
  import { z } from "zod";
3
3
  //#region src/kinds/bundle.kind.ts
4
4
  const bundlePayloadSchema = z.object({
@@ -49,7 +49,7 @@ const bundleKind = {
49
49
  amount: 0,
50
50
  currency: unitPrice.currency
51
51
  },
52
- validUntil: new Date(Date.now() + 900 * 1e3),
52
+ validUntil: new Date((ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime() + 900 * 1e3),
53
53
  kindMeta: {
54
54
  bundleRef: typed.payload.bundleRef,
55
55
  componentCount: typed.payload.components.length
@@ -87,7 +87,7 @@ const bundleKind = {
87
87
  postPromo: newTotal,
88
88
  postPromoPostTax: newTotal
89
89
  },
90
- validUntil: new Date(Date.now() + 900 * 1e3)
90
+ validUntil: new Date((ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime() + 900 * 1e3)
91
91
  },
92
92
  delta
93
93
  };
@@ -106,7 +106,89 @@ const bundleKind = {
106
106
  imageUrl: bundle.primaryImage,
107
107
  slug: bundle.slug,
108
108
  variantLabel: `${typed.payload.components.length} items`,
109
- capturedAt: /* @__PURE__ */ new Date()
109
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
110
+ };
111
+ }
112
+ };
113
+ //#endregion
114
+ //#region src/kinds/service-fee.kind.ts
115
+ const serviceFeePayloadSchema = z.object({
116
+ code: z.string().min(1).max(64),
117
+ label: z.string().min(1).max(120),
118
+ unitPrice: z.object({
119
+ amount: z.number().int().nonnegative(),
120
+ currency: z.string().length(3)
121
+ })
122
+ });
123
+ const serviceFeeKind = {
124
+ name: "service-fee",
125
+ payloadSchema: serviceFeePayloadSchema,
126
+ validity: { onStale: "extend" },
127
+ async validate(line) {
128
+ const parsed = serviceFeePayloadSchema.safeParse(line.payload);
129
+ if (!parsed.success) throw new KindError(this.name, "invalid payload shape", { details: { issues: parsed.error.issues } });
130
+ if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
131
+ if (line.currency !== parsed.data.unitPrice.currency) throw new KindError(this.name, `service fee currency ${parsed.data.unitPrice.currency} does not match cart currency ${line.currency}`);
132
+ },
133
+ async price(line) {
134
+ const typed = line;
135
+ const unitPrice = typed.overrideUnitPrice ?? typed.payload.unitPrice;
136
+ const lineTotal = {
137
+ amount: unitPrice.amount * typed.quantity,
138
+ currency: unitPrice.currency
139
+ };
140
+ return {
141
+ lineId: typed.lineId,
142
+ unitPrice,
143
+ quantity: typed.quantity,
144
+ subtotals: {
145
+ prePromo: lineTotal,
146
+ postPromo: lineTotal,
147
+ postPromoPostTax: lineTotal
148
+ },
149
+ discountTotal: {
150
+ amount: 0,
151
+ currency: unitPrice.currency
152
+ },
153
+ taxTotal: {
154
+ amount: 0,
155
+ currency: unitPrice.currency
156
+ },
157
+ validUntil: null
158
+ };
159
+ },
160
+ async revalidate(_line, priced) {
161
+ return {
162
+ status: "unchanged",
163
+ priced
164
+ };
165
+ },
166
+ /**
167
+ * Two adds of the same service code merge by default (gift wrap +
168
+ * gift wrap = qty 2 of gift wrap). Hosts that want each add to stay
169
+ * separate (e.g. distinct rationale per fee) should call addItem with
170
+ * a custom note in the line metadata to differentiate.
171
+ */
172
+ mergeKey(line) {
173
+ const typed = line;
174
+ if (!typed.payload?.code) return null;
175
+ return `service-fee:${typed.payload.code}`;
176
+ },
177
+ /**
178
+ * Display snapshot for the cart UI — there is no catalog product
179
+ * behind a fee, so we synthesize from the payload directly (no
180
+ * bridge call). The receipt / order detail render path uses these
181
+ * fields verbatim.
182
+ */
183
+ async displayOf(line, ctx) {
184
+ const typed = line;
185
+ return {
186
+ name: typed.payload.label,
187
+ imageUrl: void 0,
188
+ slug: typed.payload.code,
189
+ variantLabel: void 0,
190
+ compareAtPrice: void 0,
191
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
110
192
  };
111
193
  }
112
194
  };
@@ -180,7 +262,7 @@ const skuKind = {
180
262
  slug: product.slug,
181
263
  variantLabel: product.variantLabel,
182
264
  compareAtPrice: product.compareAtPrice,
183
- capturedAt: ctx.bridges ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date()
265
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
184
266
  };
185
267
  }
186
268
  };
@@ -234,7 +316,7 @@ const timeslotKind = {
234
316
  amount: 0,
235
317
  currency: unitPrice.currency
236
318
  },
237
- validUntil: new Date(Date.now() + TIMESLOT_VALIDITY_MS),
319
+ validUntil: new Date((ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime() + TIMESLOT_VALIDITY_MS),
238
320
  kindMeta: {
239
321
  startsAt: typed.payload.startsAt,
240
322
  endsAt: typed.payload.endsAt,
@@ -242,8 +324,8 @@ const timeslotKind = {
242
324
  }
243
325
  };
244
326
  },
245
- async revalidate(line, priced, _ctx) {
246
- if (priced.validUntil && priced.validUntil.getTime() <= Date.now()) return {
327
+ async revalidate(_line, priced, ctx) {
328
+ if (priced.validUntil && priced.validUntil.getTime() <= (ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime()) return {
247
329
  status: "invalid",
248
330
  reason: "timeslot hold expired — the slot may no longer be available"
249
331
  };
@@ -282,7 +364,7 @@ const timeslotKind = {
282
364
  hour: "2-digit",
283
365
  minute: "2-digit"
284
366
  })}`,
285
- capturedAt: /* @__PURE__ */ new Date()
367
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
286
368
  };
287
369
  }
288
370
  };
@@ -354,9 +436,9 @@ const variantKind = {
354
436
  slug: product.slug,
355
437
  variantLabel: product.variantLabel,
356
438
  compareAtPrice: product.compareAtPrice,
357
- capturedAt: /* @__PURE__ */ new Date()
439
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
358
440
  };
359
441
  }
360
442
  };
361
443
  //#endregion
362
- export { skuKind as a, bundlePayloadSchema as c, timeslotPayloadSchema as i, variantPayloadSchema as n, skuPayloadSchema as o, timeslotKind as r, bundleKind as s, variantKind as t };
444
+ export { skuKind as a, serviceFeePayloadSchema as c, timeslotPayloadSchema as i, bundleKind as l, variantPayloadSchema as n, skuPayloadSchema as o, timeslotKind as r, serviceFeeKind as s, variantKind as t, bundlePayloadSchema as u };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "0.1.1",
4
- "description": "Framework-agnostic universal cart engine for commerce — drafts, checkouts, reservations, the LineKind strategy, and a disciplined finalization saga. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
3
+ "version": "0.1.3",
4
+ "description": "Framework-agnostic universal cart engine for commerce — drafts, checkouts, reservations, the LineKind strategy, and a disciplined finalization saga. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
5
5
  "author": "Classytic",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -83,16 +83,18 @@
83
83
  "release": "npm run push -- main && npm run release:tag && npm publish"
84
84
  },
85
85
  "peerDependencies": {
86
- "@classytic/mongokit": ">=3.11.0",
87
- "@classytic/primitives": ">=0.1.0",
86
+ "@classytic/mongokit": ">=3.13.0",
87
+ "@classytic/primitives": ">=0.5.0",
88
+ "@classytic/repo-core": ">=0.4.0",
88
89
  "mongoose": ">=9.4.1",
89
90
  "zod": ">=4.0.0"
90
91
  },
91
92
  "devDependencies": {
92
93
  "@biomejs/biome": "^2.4.13",
93
94
  "@classytic/dev-tools": "^0.2.0",
94
- "@classytic/mongokit": "^3.11.0",
95
- "@classytic/primitives": "^0.1.0",
95
+ "@classytic/mongokit": ">=3.13.0",
96
+ "@classytic/primitives": ">=0.5.0",
97
+ "@classytic/repo-core": ">=0.4.0",
96
98
  "@types/node": "^25.5.0",
97
99
  "knip": "^6.7.0",
98
100
  "mongodb-memory-server": "^10.2.3",