@classytic/cart 0.1.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 (47) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -0
  4. package/dist/bundle.kind-BdgnyKZt.d.mts +114 -0
  5. package/dist/bundle.kind-DFydSxV_.mjs +362 -0
  6. package/dist/cart-event-catalog-BIbi2Q_n.d.mts +109 -0
  7. package/dist/cart-event-catalog-BOP9aDhL.mjs +301 -0
  8. package/dist/cart-status.vo-2iisZGhb.d.mts +46 -0
  9. package/dist/create-cart-q3CXxPP7.mjs +1751 -0
  10. package/dist/domain/errors/index.d.mts +2 -0
  11. package/dist/domain/errors/index.mjs +4 -0
  12. package/dist/domain/events/index.d.mts +3 -0
  13. package/dist/domain/events/index.mjs +3 -0
  14. package/dist/domain/index.d.mts +12 -0
  15. package/dist/domain/index.mjs +15 -0
  16. package/dist/domain/ports/index.d.mts +3 -0
  17. package/dist/domain/ports/index.mjs +2 -0
  18. package/dist/domain/saga/index.d.mts +2 -0
  19. package/dist/domain/saga/index.mjs +3 -0
  20. package/dist/domain-event-DHNkz15G.mjs +57 -0
  21. package/dist/engine/cart-config.schema.d.mts +41 -0
  22. package/dist/engine/cart-config.schema.mjs +40 -0
  23. package/dist/engine/index.d.mts +3 -0
  24. package/dist/engine/index.mjs +3 -0
  25. package/dist/errors-CHR9RlbY.mjs +97 -0
  26. package/dist/id.port-C3rlDAKP.mjs +29 -0
  27. package/dist/id.port-DPXLrqb2.d.mts +64 -0
  28. package/dist/idempotency-key.vo-D0lJsvGn.mjs +9 -0
  29. package/dist/idempotency-record.entity-DIFXjN1V.d.mts +221 -0
  30. package/dist/index-DEHBdV_z.d.mts +1 -0
  31. package/dist/index-Doi5uzux.d.mts +231 -0
  32. package/dist/index.d.mts +103 -0
  33. package/dist/index.mjs +92 -0
  34. package/dist/internal-event-bus-IkUfQJxn.d.mts +661 -0
  35. package/dist/kind-registry-Ba4PO4WC.mjs +35 -0
  36. package/dist/kind.error-CCjTB6kW.mjs +69 -0
  37. package/dist/kinds/index.d.mts +2 -0
  38. package/dist/kinds/index.mjs +2 -0
  39. package/dist/line-item.entity-B3M_i-pw.d.mts +157 -0
  40. package/dist/line-kind-Bndo6IS8.d.mts +231 -0
  41. package/dist/not-found.error-B6WYnAjX.mjs +95 -0
  42. package/dist/outbox-store-CTWz9pvG.d.mts +155 -0
  43. package/dist/saga-step-fn-Cyob38iU.d.mts +135 -0
  44. package/dist/saga-steps-B27LI7xp.mjs +27 -0
  45. package/dist/shipping.bridge-DD4A_O0O.d.mts +538 -0
  46. package/dist/state-transitions-CpJpZZTK.mjs +21 -0
  47. package/package.json +114 -0
@@ -0,0 +1,231 @@
1
+ import { t as CheckoutState } from "./cart-status.vo-2iisZGhb.mjs";
2
+
3
+ //#region src/domain/errors/cart.error.d.ts
4
+ /**
5
+ * Base class for every error the cart engine emits.
6
+ *
7
+ * Rules:
8
+ * - Every subclass sets a `code` that is stable across versions (for client
9
+ * branching and i18n) and a `category` that signals how a host should
10
+ * surface the failure (validation vs concurrency vs system vs external).
11
+ * - `retryable` tells the caller whether minting a new idempotency key and
12
+ * re-running the operation is a reasonable next step. Errors with
13
+ * `retryable: false` will replay verbatim if the caller retries with the
14
+ * same key — see plan §2 Failed-op replay rule.
15
+ * - All subclasses extend this via `Error` prototype chain so `instanceof`
16
+ * works under ESM and Node 22+.
17
+ */
18
+ type CartErrorCategory = 'validation' | 'concurrency' | 'state' | 'external' | 'system' | 'not_found';
19
+ declare abstract class CartError extends Error {
20
+ abstract readonly code: string;
21
+ abstract readonly category: CartErrorCategory;
22
+ abstract readonly retryable: boolean;
23
+ /** Optional structured context for logging / debugging. */
24
+ readonly context?: Record<string, unknown>;
25
+ constructor(message: string, context?: Record<string, unknown>);
26
+ /**
27
+ * Serialize to a wire-safe shape. Suitable for HTTP error bodies and
28
+ * structured logging. Never includes stack frames.
29
+ */
30
+ toJSON(): {
31
+ name: string;
32
+ code: string;
33
+ category: CartErrorCategory;
34
+ message: string;
35
+ retryable: boolean;
36
+ context?: Record<string, unknown>;
37
+ };
38
+ }
39
+ //#endregion
40
+ //#region src/domain/errors/concurrency.error.d.ts
41
+ /**
42
+ * Optimistic-lock mismatch. Thrown when a mutation attempts to update a
43
+ * document with a stale `version` — another writer committed first.
44
+ *
45
+ * Host should re-read the draft/checkout and retry with the fresh state.
46
+ * Retryable, but the caller MUST mint a new idempotency key for the retry
47
+ * (the previous attempt's key is locked to the stale version number).
48
+ */
49
+ declare class ConcurrencyError extends CartError {
50
+ readonly code = "cart/concurrency_version_mismatch";
51
+ readonly category: CartErrorCategory;
52
+ readonly retryable = true;
53
+ constructor(resource: 'draft' | 'checkout' | 'reservation', expectedVersion: number, resourceId: string);
54
+ }
55
+ //#endregion
56
+ //#region src/domain/errors/reservation.error.d.ts
57
+ /**
58
+ * Inventory / slot reservation could not be secured. Thrown from the saga's
59
+ * step 5 (InventoryBridge.reserve) and from compensating `release` when the
60
+ * bridge reports the reservation no longer exists.
61
+ *
62
+ * Category is `external` because the decision is owned by the inventory
63
+ * system, not cart.
64
+ */
65
+ declare class ReservationError extends CartError {
66
+ readonly code = "cart/reservation_failed";
67
+ readonly category: CartErrorCategory;
68
+ readonly retryable: boolean;
69
+ constructor(message: string, opts: {
70
+ retryable: boolean;
71
+ bridgeError?: unknown;
72
+ lineIds?: string[];
73
+ });
74
+ }
75
+ //#endregion
76
+ //#region src/domain/errors/stale-quote.error.d.ts
77
+ /**
78
+ * A priced line's validity window has elapsed and its LineKind's revalidate()
79
+ * returned `invalid`. Fired from the saga's step 2 (revalidation).
80
+ *
81
+ * Example: a bid line whose underlying auction moved to a new highest bid
82
+ * while the user was reviewing the cart.
83
+ *
84
+ * Clients should re-read the cart, show the updated state, and confirm again.
85
+ * Retryable with a new idempotency key.
86
+ */
87
+ declare class StaleQuoteError extends CartError {
88
+ readonly code = "cart/stale_quote";
89
+ readonly category: CartErrorCategory;
90
+ readonly retryable = true;
91
+ constructor(lineId: string, kind: string, reason: string, details?: Record<string, unknown>);
92
+ }
93
+ //#endregion
94
+ //#region src/domain/errors/price-changed.error.d.ts
95
+ /**
96
+ * The re-run pricing snapshot's hash does not match the `expectedPricingHash`
97
+ * the client supplied when initiating finalize. Fired from saga step 3.
98
+ *
99
+ * This is a safety interlock: the client saw totals X, but by the time the
100
+ * saga ran, totals are now Y. Rather than silently charging a different
101
+ * amount, the saga aborts with this error so the client re-displays and
102
+ * re-confirms.
103
+ *
104
+ * Retryable with a new idempotency key AND a new expectedPricingHash matching
105
+ * the new snapshot.
106
+ */
107
+ declare class PriceChangedError extends CartError {
108
+ readonly code = "cart/price_changed";
109
+ readonly category: CartErrorCategory;
110
+ readonly retryable = true;
111
+ constructor(expectedHash: string, actualHash: string, context?: Record<string, unknown>);
112
+ }
113
+ //#endregion
114
+ //#region src/domain/errors/saga.error.d.ts
115
+ /**
116
+ * Structured failure in the finalization saga.
117
+ *
118
+ * Carries the step at which the failure occurred and the compensation state
119
+ * so operators and hosts can tell "we failed at step 7 and compensation
120
+ * walked back through 6 and 5 successfully" vs "we failed at step 9 and
121
+ * compensation itself is now stuck at step 7".
122
+ *
123
+ * The saga service catches this, persists `sagaState` onto the checkout, and
124
+ * re-throws so the caller sees the same shape.
125
+ */
126
+ type SagaFailurePhase = 'forward' | 'compensating' | 'compensation_stuck';
127
+ declare class SagaError extends CartError {
128
+ readonly code = "cart/saga_failure";
129
+ readonly category: CartErrorCategory;
130
+ readonly retryable: boolean;
131
+ constructor(message: string, opts: {
132
+ checkoutId: string;
133
+ failedStep: number;
134
+ phase: SagaFailurePhase;
135
+ cause?: unknown;
136
+ retryable: boolean;
137
+ completedSteps: number[];
138
+ compensatedSteps?: number[];
139
+ });
140
+ }
141
+ /**
142
+ * Raised when a retry attempts to execute an operation that is already
143
+ * `in_flight` in the idempotency collection and the lease has not yet
144
+ * expired. The caller should back off and retry later — by then the lease
145
+ * will have settled or expired.
146
+ */
147
+ declare class IdempotencyBusyError extends CartError {
148
+ readonly code = "cart/idempotency_busy";
149
+ readonly category: CartErrorCategory;
150
+ readonly retryable = true;
151
+ constructor(operation: string, leaseExpiresAt: Date);
152
+ }
153
+ /**
154
+ * Raised when the idempotency record points at a `cart_operation_results`
155
+ * document that does not exist, or when a stored record is otherwise
156
+ * malformed. This is data corruption, not a recoverable state.
157
+ */
158
+ declare class IdempotencyStorageError extends CartError {
159
+ readonly code = "cart/idempotency_storage_corruption";
160
+ readonly category: CartErrorCategory;
161
+ readonly retryable = false;
162
+ constructor(message: string, context: Record<string, unknown>);
163
+ }
164
+ //#endregion
165
+ //#region src/domain/errors/kind.error.d.ts
166
+ /**
167
+ * A LineKind rejected a line during validate() or price().
168
+ *
169
+ * Used for both:
170
+ * - User-facing validation failures ("quantity exceeds max per line")
171
+ * - Configuration failures ("kind 'timeslot' is not registered")
172
+ *
173
+ * `retryable: false` by default because changing the input will require a
174
+ * new idempotency key anyway.
175
+ */
176
+ declare class KindError extends CartError {
177
+ readonly code: string;
178
+ readonly category: CartErrorCategory;
179
+ readonly retryable = false;
180
+ constructor(kind: string, reason: string, opts?: {
181
+ code?: string;
182
+ details?: Record<string, unknown>;
183
+ });
184
+ }
185
+ /**
186
+ * A kind referenced by a line is not registered in the engine's kind
187
+ * registry. This is a configuration bug — the host forgot to register the
188
+ * kind or registered it under a different name. Always fatal, never
189
+ * retryable.
190
+ */
191
+ declare class UnknownKindError extends CartError {
192
+ readonly code = "cart/unknown_kind";
193
+ readonly category: CartErrorCategory;
194
+ readonly retryable = false;
195
+ constructor(kind: string, registered: string[]);
196
+ }
197
+ //#endregion
198
+ //#region src/domain/errors/state-transition.error.d.ts
199
+ /**
200
+ * A write attempted to transition `checkout.state` along an edge that
201
+ * does not exist in the frozen state machine (see plan simplification —
202
+ * `open → finalized | canceled`).
203
+ *
204
+ * Thrown by service methods before the mutation reaches the database.
205
+ * Never retryable — the caller either has a bug or is racing another
206
+ * writer. A concurrency race manifests as `ConcurrencyError` first via
207
+ * the version check; if it reaches here, it is a logic bug.
208
+ */
209
+ declare class StateTransitionError extends CartError {
210
+ readonly code = "cart/illegal_state_transition";
211
+ readonly category: CartErrorCategory;
212
+ readonly retryable = false;
213
+ constructor(checkoutId: string, from: CheckoutState, to: CheckoutState);
214
+ }
215
+ //#endregion
216
+ //#region src/domain/errors/not-found.error.d.ts
217
+ /**
218
+ * The requested draft, checkout, or reservation does not exist (or is not
219
+ * visible under the caller's organizationId scope).
220
+ *
221
+ * Retryable is false — the resource simply does not exist. If the host
222
+ * thinks it should, the bug is upstream.
223
+ */
224
+ declare class NotFoundError extends CartError {
225
+ readonly code = "cart/not_found";
226
+ readonly category: CartErrorCategory;
227
+ readonly retryable = false;
228
+ constructor(resource: 'draft' | 'checkout' | 'reservation' | 'line', ref: string, organizationId?: string);
229
+ }
230
+ //#endregion
231
+ export { IdempotencyBusyError as a, SagaFailurePhase as c, ReservationError as d, ConcurrencyError as f, UnknownKindError as i, PriceChangedError as l, CartErrorCategory as m, StateTransitionError as n, IdempotencyStorageError as o, CartError as p, KindError as r, SagaError as s, NotFoundError as t, StaleQuoteError as u };
@@ -0,0 +1,103 @@
1
+ import { a as IdempotencyBusyError, c as SagaFailurePhase, d as ReservationError, f as ConcurrencyError, i as UnknownKindError, l as PriceChangedError, m as CartErrorCategory, n as StateTransitionError, o as IdempotencyStorageError, p as CartError, r as KindError, s as SagaError, t as NotFoundError, u as StaleQuoteError } from "./index-Doi5uzux.mjs";
2
+ import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-2iisZGhb.mjs";
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-CTWz9pvG.mjs";
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-BIbi2Q_n.mjs";
5
+ import { a as IdempotencyIdentity, c as TotalsSnapshot, i as CART_REF_NEW, n as KindRegistry, o as IdempotencyReplay, r as createKindRegistry, s as OperationName, t as LineItem } from "./line-item.entity-B3M_i-pw.mjs";
6
+ import { C as PricingSnapshot, S as PricedLine, _ as ProductSummary, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as PromotionResult, f as PromotionsBridge, g as CatalogBridge, h as ReservationRequest, i as ShippingQuoteRequest, l as AdjustmentSpec, m as ReservationRef, n as ShippingMethod, o as TaxBridge, p as InventoryBridge, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as CartSnapshot, v as Address, x as OperationContext, y as BridgeRef } from "./shipping.bridge-DD4A_O0O.mjs";
7
+ 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-Bndo6IS8.mjs";
8
+ import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DPXLrqb2.mjs";
9
+ import { a as CheckoutFlowState, c as CheckoutStepNumber, i as isLegalCheckoutTransition, l as SagaStep, n as SagaStepFn, o as SagaState, r as CHECKOUT_STATE_TRANSITIONS, s as CheckoutStep, t as SagaDependencies, u as SagaStepNumber } from "./saga-step-fn-Cyob38iU.mjs";
10
+ import { a as Adjustment, i as Draft, n as Reservation, r as Checkout, t as IdempotencyRecord } from "./idempotency-record.entity-DIFXjN1V.mjs";
11
+ import { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
+ import { C as DraftDocument, S as createCheckoutModel, _ as IdempotencyDocument, a as CartEngine, b as createReservationModel, c as createCartRepositories, d as CheckoutRepository, f as DraftRepository, g as createCartModels, h as CreateCartModelsOptions, i as CartConfig, l as IdempotencyRepository, m as CartModels, n as createCart, o as CartRepositories, p as CartModelName, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as createIdempotencyModel, w as createDraftModel, x as CheckoutDocument, y as ReservationDocument } from "./internal-event-bus-IkUfQJxn.mjs";
13
+ import { a as TimeslotPayload, c as VariantPayload, d as SkuPayload, f as skuKind, i as bundlePayloadSchema, l as variantKind, n as BundlePayload, o as timeslotKind, p as skuPayloadSchema, r as bundleKind, s as timeslotPayloadSchema, t as BundleComponent, u as variantPayloadSchema } from "./bundle.kind-BdgnyKZt.mjs";
14
+ import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
+ import { EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
16
+
17
+ //#region src/services/pricing.service.d.ts
18
+ /**
19
+ * Pricing pipeline — composable, bridge-activated.
20
+ *
21
+ * Steps run in frozen order. Each step only runs if its bridge is present.
22
+ * No bridge = no step = no overhead.
23
+ *
24
+ * 1. kind.price() — per-line base + kind-specific pricing
25
+ * 2. promo-apply — PromotionsBridge.evaluate() if present
26
+ * 3. tax — TaxBridge.calculate() if present
27
+ * 4. shipping — ShippingBridge.quote() if present
28
+ * 5. rounding — final integer-money rounding (always runs)
29
+ *
30
+ * Incremental repricing:
31
+ * Callers may pass `previous` — the pricing snapshot from before the
32
+ * mutation. Lines whose (lineId + payload) are unchanged reuse the prior
33
+ * `unitPrice` and `validUntil` without hitting the catalog; only new or
34
+ * payload-changed lines pay a fresh `kind.price()` call. Promo, tax, and
35
+ * shipping always re-run because they depend on cart composition. This
36
+ * means a 10-line cart + "remove one" = ZERO catalog reads in step 1
37
+ * (all 9 remaining lines reuse their priced entries).
38
+ *
39
+ * Unit prices can drift between caches — the pricing hash interlock at
40
+ * checkout-freeze still catches drift, so reuse here is safe.
41
+ */
42
+ declare function runPricing(opts: {
43
+ lines: readonly LineItem[];
44
+ currency: string;
45
+ kinds: KindRegistry;
46
+ bridges: CartBridges;
47
+ clock: ClockPort;
48
+ ctx: OperationContext; /** Prior snapshot to reuse unchanged per-line prices from. */
49
+ previous?: PricingSnapshot | null;
50
+ }): Promise<{
51
+ snapshot: PricingSnapshot;
52
+ adjustments: Adjustment[];
53
+ }>;
54
+ //#endregion
55
+ //#region src/services/merge.service.d.ts
56
+ /**
57
+ * Merge a guest (session-scoped) draft into an authenticated user's
58
+ * active draft on login.
59
+ *
60
+ * Merge strategy: iterate the source's lines. For each line, if a line
61
+ * with the same `(kind, skuRef)` exists in the target, increment the
62
+ * target's quantity. Otherwise, append. Display snapshots carry over
63
+ * from the source since they're already captured.
64
+ *
65
+ * After merging, the source draft is marked `abandoned` so it's no
66
+ * longer active.
67
+ */
68
+ declare function mergeDrafts(opts: {
69
+ repo: DraftRepository;
70
+ sourcePublicId: string;
71
+ targetActorRef: string;
72
+ ctx: OperationContext;
73
+ }): Promise<DraftDocument>;
74
+ //#endregion
75
+ //#region src/services/abandonment.service.d.ts
76
+ /**
77
+ * Abandonment query primitives. Hosts call these from their own cron
78
+ * or worker — cart does not ship a scheduler.
79
+ */
80
+ /**
81
+ * Find drafts that have been active but not updated since `cutoff`.
82
+ * Returns up to `limit` drafts, sorted by `updatedAt` ascending (oldest
83
+ * first). Routes through mongokit's `getAll` so the multi-tenant plugin
84
+ * scopes the query at POLICY priority — pass `skipTenant: true` on `ctx`
85
+ * for cross-tenant admin sweeps.
86
+ */
87
+ declare function findAbandonedDrafts(opts: {
88
+ repo: DraftRepository;
89
+ cutoff: Date;
90
+ limit?: number;
91
+ ctx: OperationContext;
92
+ }): Promise<DraftDocument[]>;
93
+ /**
94
+ * Mark a batch of drafts as abandoned. Returns the count of drafts
95
+ * successfully transitioned.
96
+ */
97
+ declare function markAbandoned(opts: {
98
+ repo: DraftRepository;
99
+ draftIds: string[];
100
+ ctx: OperationContext;
101
+ }): Promise<number>;
102
+ //#endregion
103
+ 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 CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type Draft, type DraftDocument, DraftRepository, 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 RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaState, SagaStep, type SagaStepFn, type SagaStepNumber, 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 };
package/dist/index.mjs ADDED
@@ -0,0 +1,92 @@
1
+ import { t as CART_REF_NEW } from "./idempotency-key.vo-D0lJsvGn.mjs";
2
+ import { n as UnknownKindError, r as CartError, t as KindError } from "./kind.error-CCjTB6kW.mjs";
3
+ import { i as ConcurrencyError, n as StateTransitionError, r as PriceChangedError, t as NotFoundError } from "./not-found.error-B6WYnAjX.mjs";
4
+ import { a as ReservationError, i as StaleQuoteError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-CHR9RlbY.mjs";
5
+ import { n as CartEvents, t as createCartEvent } from "./domain-event-DHNkz15G.mjs";
6
+ import { a as OutboxOwnershipError, i as MemoryOutboxStore, n as cartEventsByName, o as createCartEventRegistry, r as InvalidOutboxEventError, s as defineCartEvent, t as cartEventDefinitions } from "./cart-event-catalog-BOP9aDhL.mjs";
7
+ import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-C3rlDAKP.mjs";
8
+ import { t as createKindRegistry } from "./kind-registry-Ba4PO4WC.mjs";
9
+ import { n as SagaStep, t as CheckoutStep } from "./saga-steps-B27LI7xp.mjs";
10
+ import { n as isLegalCheckoutTransition, t as CHECKOUT_STATE_TRANSITIONS } from "./state-transitions-CpJpZZTK.mjs";
11
+ import { a as ReservationRepository, c as runPricing, d as createReservationModel, f as createCheckoutModel, i as IdempotencyRepository, l as createCartModels, n as InProcessCartEventBus, o as CheckoutRepository, p as createDraftModel, r as createCartRepositories, s as DraftRepository, t as createCart, u as createIdempotencyModel } from "./create-cart-q3CXxPP7.mjs";
12
+ import { a as variantKind, c as skuPayloadSchema, i as timeslotPayloadSchema, n as bundlePayloadSchema, o as variantPayloadSchema, r as timeslotKind, s as skuKind, t as bundleKind } from "./bundle.kind-DFydSxV_.mjs";
13
+ import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
14
+ import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
+ //#region src/services/merge.service.ts
16
+ /**
17
+ * Merge a guest (session-scoped) draft into an authenticated user's
18
+ * active draft on login.
19
+ *
20
+ * Merge strategy: iterate the source's lines. For each line, if a line
21
+ * with the same `(kind, skuRef)` exists in the target, increment the
22
+ * target's quantity. Otherwise, append. Display snapshots carry over
23
+ * from the source since they're already captured.
24
+ *
25
+ * After merging, the source draft is marked `abandoned` so it's no
26
+ * longer active.
27
+ */
28
+ async function mergeDrafts(opts) {
29
+ const { repo, sourcePublicId, targetActorRef, ctx } = opts;
30
+ const source = await repo.findByPublicId(sourcePublicId, ctx);
31
+ if (!source || source.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
32
+ const targetCtx = {
33
+ ...ctx,
34
+ actorRef: targetActorRef
35
+ };
36
+ const target = await repo.findActiveByActor(targetActorRef, targetCtx);
37
+ if (!target) return repo.updateWithVersion(source._id, source.version, {
38
+ actorRef: targetActorRef,
39
+ actorKind: "user"
40
+ }, ctx);
41
+ const sourceLines = source.lines;
42
+ const currentTargetLines = target.lines;
43
+ const mergedLines = repo.mergeLines(currentTargetLines, sourceLines);
44
+ const updated = await repo.replaceLines({
45
+ draftPublicId: target.publicId,
46
+ lines: mergedLines
47
+ }, targetCtx);
48
+ await repo.markAbandoned(source._id, ctx);
49
+ return updated;
50
+ }
51
+ //#endregion
52
+ //#region src/services/abandonment.service.ts
53
+ /**
54
+ * Abandonment query primitives. Hosts call these from their own cron
55
+ * or worker — cart does not ship a scheduler.
56
+ */
57
+ /**
58
+ * Find drafts that have been active but not updated since `cutoff`.
59
+ * Returns up to `limit` drafts, sorted by `updatedAt` ascending (oldest
60
+ * first). Routes through mongokit's `getAll` so the multi-tenant plugin
61
+ * scopes the query at POLICY priority — pass `skipTenant: true` on `ctx`
62
+ * for cross-tenant admin sweeps.
63
+ */
64
+ async function findAbandonedDrafts(opts) {
65
+ const { repo, cutoff, limit = 100, ctx } = opts;
66
+ return (await repo.getAll({
67
+ filters: {
68
+ status: "active",
69
+ updatedAt: { $lt: cutoff },
70
+ "lines.0": { $exists: true }
71
+ },
72
+ sort: { updatedAt: 1 },
73
+ page: 1,
74
+ limit,
75
+ countStrategy: "none"
76
+ }, {
77
+ organizationId: ctx.organizationId,
78
+ skipTenant: ctx.skipTenant,
79
+ lean: true
80
+ })).docs;
81
+ }
82
+ /**
83
+ * Mark a batch of drafts as abandoned. Returns the count of drafts
84
+ * successfully transitioned.
85
+ */
86
+ async function markAbandoned(opts) {
87
+ let count = 0;
88
+ for (const id of opts.draftIds) if (await opts.repo.markAbandoned(id, opts.ctx)) count++;
89
+ return count;
90
+ }
91
+ //#endregion
92
+ 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, SagaStep, 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 };