@classytic/cart 1.2.0 → 1.3.1

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 (29) hide show
  1. package/CHANGELOG.md +4 -219
  2. package/dist/{cart-event-catalog-Cokx0iOw.d.mts → cart-event-catalog-DZvoNVek.d.mts} +1 -1
  3. package/dist/{clock.port-DrSBrsit.d.mts → clock.port-BFg5X92u.d.mts} +5 -0
  4. package/dist/{define-cart-DESSv8Rt.mjs → define-cart-BKV3M4pm.mjs} +72 -22
  5. package/dist/domain/events/index.d.mts +2 -2
  6. package/dist/domain/index.d.mts +7 -7
  7. package/dist/domain/ports/index.d.mts +1 -1
  8. package/dist/domain/ports/index.mjs +1 -2
  9. package/dist/domain/saga/index.d.mts +1 -1
  10. package/dist/domain/saga/index.mjs +1 -2
  11. package/dist/engine/cart-config.schema.d.mts +10 -9
  12. package/dist/engine/cart-config.schema.mjs +9 -3
  13. package/dist/engine/index.d.mts +1 -1
  14. package/dist/engine/index.mjs +1 -1
  15. package/dist/index.d.mts +18 -18
  16. package/dist/index.mjs +2 -2
  17. package/dist/{internal-event-bus-CC0PxRhB.d.mts → internal-event-bus-BfC4OKwH.d.mts} +15 -5
  18. package/dist/{kind-registry-BkYl0cjc.d.mts → kind-registry-Cb50lwpo.d.mts} +9 -3
  19. package/dist/kinds/index.d.mts +1 -1
  20. package/dist/kinds/index.mjs +1 -2
  21. package/dist/{line-kind-kYeQzpCy.d.mts → line-kind-CY7cabbf.d.mts} +7 -1
  22. package/dist/line-total-CHnkZ3nH.mjs +25 -0
  23. package/dist/{outbox-store-Br7MHuOz.d.mts → outbox-store-Cq7K0Lo6.d.mts} +11 -11
  24. package/dist/{reservation.entity-CLRqLD6X.d.mts → reservation.entity-9V2i4i1l.d.mts} +5 -5
  25. package/dist/{state-transitions-B_ozUaqV.d.mts → state-transitions-B3EPuOae.d.mts} +2 -2
  26. package/dist/{variant.kind-BVmeGR6G.d.mts → variant.kind-DQxxcsib.d.mts} +1 -1
  27. package/dist/{variant.kind-CquIUes6.mjs → variant.kind-_LIXlTwp.mjs} +13 -3
  28. package/package.json +29 -20
  29. package/dist/line-total-6VJQMjGV.mjs +0 -24
package/CHANGELOG.md CHANGED
@@ -1,224 +1,9 @@
1
1
  # Changelog
2
2
 
3
- Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
4
- adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
3
+ ## Unreleased
5
4
 
6
- ## 1.2.0 — 2026-09-04
5
+ ## 1.3.1 — 2026-11-28
7
6
 
8
- ### Added — `DraftRepository.markActiveConvertedForActor`
7
+ Peers raised to the latest published: `@classytic/mongokit >=3.47.0`, `@classytic/primitives >=0.39.0`, `@classytic/repo-core >=0.39.0`, `mongoose >=9.13.1`.
9
8
 
10
- Hosts that place an order without freezing a checkout first have no `checkout.draftId` for `markConverted` to key on, leaving the draft `active` with lines intact — exactly the shape the abandonment sweep selects. `markActiveConvertedForActor(actorRef, ctx)` looks up the actor's active draft and converts it in one call. Returns `false` if no active draft exists or `actorRef` is empty (guard against broad-match on empty string). Best-effort like `markConverted`: a miss does not fail the order.
11
-
12
- ## 1.1.1 — 2026-08-26
13
-
14
- ### Fixed
15
-
16
- - **`LineDisplay.weightGrams` captured from catalog bridge snapshot** — both
17
- `skuKind` and `variantKind` now emit `weightGrams` when the bridge supplies it
18
- (real and positive only; absent stays absent so weight-tiered delivery zones
19
- fall back to the flat charge rather than pricing the cheapest step). The field
20
- was already in the bridge's product shape; the snapshot simply never forwarded
21
- it, so every weight-tiered checkout fell back to flat.
22
- - **`draft.model.ts` declares `weightGrams`** — Mongoose strips unknown paths
23
- silently; without the schema declaration the field would be dropped on every
24
- write. `default: null` preserves the absent/unweighed distinction (no `0`
25
- default).
26
-
27
- ### Changed
28
-
29
- - **Peer floors raised** — mongokit `>=3.35.0`, primitives `>=0.25.0`,
30
- repo-core `>=0.25.0`.
31
-
32
- ## 1.1.0 - 2026-08-17
33
-
34
- ### Changed
35
- - `cleanup/steps.ts`: bare calendar-date `before` param refused — must be a full ISO instant (prevents silent UTC-midnight misfire in non-UTC deployments)
36
- - `define-cart`: `resolveCartTenant` wired; tenant injection centralised
37
- - `inject-tenant` refactored; models and repositories simplified
38
-
39
- ## 1.0.0 - 2026-07-29
40
-
41
- ### Changed
42
- - **License:** relicensed from MIT to the **Classytic Source-Available License** (Community & Commercial). Evaluation/development use remains free; production use now requires a commercial license from Classytic LLC. See `LICENSE`.
43
- - Major bump marks the license change; versions published before 1.0.0 remain under their original MIT terms.
44
-
45
- ## [0.3.3] — unpublished (2026-07-22)
46
-
47
- ### Changed — event infra consolidated onto `@classytic/primitives/event-infra`
48
-
49
- - `InProcessCartEventBus` is now a thin subclass of primitives' shared
50
- `InProcessEventBus` (name `in-process-cart`, `logger: null` — cart's
51
- silent-swallow dialect preserved: handler errors never propagate OR log).
52
- Internal delivery detail: subscriptions are now Set-deduped per handler
53
- across matching patterns (previously per-subscription array order) — no
54
- cart code subscribes one handler under multiple patterns, so delivery is
55
- unchanged in practice. `MemoryOutboxStore` is re-exported from
56
- `@classytic/primitives/event-infra` instead of a local copy (gains
57
- `all()` / `clear()` test helpers). No public API or event-shape changes.
58
- - `@classytic/primitives` peer floor raised to `>=0.13.0` (the
59
- `/event-infra` subpath).
60
-
61
- ## [0.3.2] — unpublished (2026-07-22)
62
-
63
- ### Fixed — `destroy()` was an empty no-op
64
-
65
- - **`engine.destroy()` now actually tears down**: closes the self-created
66
- `InProcessCartEventBus` (skipped when the host injected `eventTransport`).
67
- - `destroy()` follows the fleet ownsBus convention (manufacturing/purchase
68
- pattern): only what the engine itself created is closed; a host-injected
69
- transport is the host's to close. Idempotent — a second call is a no-op.
70
- Mongoose models/connection are untouched (host-owned).
71
- - Lifecycle coverage in `tests/unit/engine-lifecycle.test.ts` (lite mode).
72
-
73
- ## [0.3.1] — 2026-07-16
74
-
75
- ### Fixed
76
-
77
- - injectTenantField no longer force-indexes the tenant field: the compound
78
- prepend makes the tenant the leading key of every index, so the bare single
79
- was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
80
- index audit). A dedicated tenant index is still created when a schema
81
- declares no compounds to prepend. Index-declaration change only.
82
-
83
- ## [0.3.0] — unpublished (2026-07-15)
84
-
85
- ### Changed — kit refresh (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
86
-
87
- - Verified against the mongokit 3.22 sweep. DEFERRED (design note, not a
88
- drive-by): checkout `finalize`/`cancel` are assert-then-`updateWithVersion`
89
- — the version CAS serializes writers, so the window is narrow; converting
90
- to `applyTransition` (state+version compound CAS) needs a pass that
91
- preserves the updateWithVersion helper's semantics.
92
-
93
- ## [0.2.1] - 2026-07-02
94
-
95
- ### Changed (behavioral) — 2026-07-05 addendum
96
-
97
- - **`commit()` is crash-retry convergent.** The finalize CAS runs first and
98
- its tail (`markConverted` on the draft + the `cart.checkout.committed`
99
- event) is non-atomic — a crash in between left the draft looking live
100
- (re-checkout → duplicate order risk) with NO retry path, because a second
101
- `commit()` failed the `finalized → finalized` state assertion. A retry
102
- with the SAME `externalRef` (or none) now re-runs both idempotent tails
103
- and returns the finalized checkout; a DIFFERENT `externalRef` throws
104
- `ConcurrencyError`. `cart.checkout.committed` delivery is at-least-once —
105
- subscribers must already dedupe by `checkoutId`.
106
-
107
- ### Added
108
-
109
- - **`engine.withTransaction(ctx, body)`** — unit-of-work wrapper (transaction
110
- + post-commit event publish), the contract shared with `@classytic/refit`
111
- and `@classytic/review`. Events emitted inside the unit are queued under
112
- `ctx[PENDING_EVENTS]` and flushed to the in-process transport only AFTER
113
- commit — a rollback or retry can't leak ghost events. New exports:
114
- `PENDING_EVENTS`, `flushPending`, `UnmanagedSessionError`; new config:
115
- `allowNonTransactional` (standalone-Mongo dev fallback, explicit opt-in).
116
- - **Boot capability gate** — `createCart` (full mode) asserts the backend
117
- declares `capabilities.upsert` (idempotency lease pattern) at engine
118
- creation instead of failing on the first checkout.
119
- - **Event-catalog no-drift test** (rule 18) — every `CartEvents` constant
120
- must have a Zod definition; orphan definitions also fail.
121
- - **Compensation scenario test** — proves the documented
122
- `cart.checkout.canceled` → `inventory.release()` host wiring end-to-end.
123
- - `PriceChangedErrorContext` — formal type for the error's structured
124
- context (current pricing payload), previously an untyped inline shape.
125
-
126
- ### Changed
127
-
128
- - **`CartEventPublisher`**: a host-owned `ctx.session` without an outbox now
129
- throws typed `UnmanagedSessionError` (was a plain `Error`) unless a
130
- `PENDING_EVENTS` queue is attached; transport publish failures on the
131
- no-session path are now swallowed and logged per P8 (the domain verb no
132
- longer fails after its write landed because a transport hiccuped).
133
- - Safe-integer guard on line-total arithmetic (`unitPrice × quantity`);
134
- idempotency repo now uses mongokit's `isDuplicateKeyError`; `cancel()`
135
- and the timeslot kind's `revalidate` carry explicit contracts (host owns
136
- hold release; validity-window-only revalidation — real slot-locking via
137
- `@classytic/order`'s `BookingBridge`).
138
-
139
- ## [0.2.0]
140
-
141
- ### Changed
142
-
143
- - **`pricingHash` is now hex SHA-256** over the same canonical sorted
144
- line string (was the raw concatenation). The hash is opaque — compare,
145
- never parse. **Migration:** drafts priced before 0.2.0 carry old-format
146
- hashes; the first checkout attempt against them raises
147
- `PriceChangedError` once and the client re-fetches/re-confirms.
148
- Accepted clean break.
149
- - **Guest→user merge is now double-CAS atomic.** `mergeDrafts` retires the
150
- source with a version CAS, then writes the target with a version CAS
151
- (bounded retries) — a concurrent add-to-cart on either draft is retried
152
- into the result instead of silently lost. `DraftRepository.markAbandoned`
153
- gains an optional `{ expectedVersion }`; `replaceLines` gains an
154
- optional `expectedVersion` input.
155
- - **Zombie open checkouts self-heal.** `createFromDraft` CAS-expires an
156
- open checkout older than `checkout.staleOpenCheckoutMs` (new config,
157
- default 10 min) and creates a fresh one; fresh open checkouts are still
158
- returned idempotently. `expireStaleOpenCheckouts` remains the bulk cron
159
- sweep. No TTL deletes — checkout rows stay as audit history.
160
- - **`PriceChangedError` context now includes `currentPricing`** (per-line
161
- `lineId`/`quantity`/`unitPrice`/`subtotals` + `totals`) so hosts render
162
- a price diff without re-fetching the draft.
163
- - **`ctx.signal` is threaded to every mongokit call** — cancelled requests
164
- stop at the driver-call boundary (repo-core 0.6 `QueryOptions.signal`).
165
- - Peer deps: `@classytic/mongokit >= 3.16`, `@classytic/repo-core >= 0.6`.
166
-
167
- ### Added
168
-
169
- - `checkoutConfigSchema` / `CartConfig.checkout.staleOpenCheckoutMs` and
170
- `DEFAULT_STALE_OPEN_CHECKOUT_MS` export.
171
- - Documented host contract: checkout → order → `inventory.commit()`
172
- (CLAUDE.md "Host responsibilities") — `commit()` intentionally does not
173
- commit inventory holds.
174
- - Scenario 10: stale quote → `revalidate()` reprice path (`bundle` kind).
175
-
176
- ## [0.1.0]
177
-
178
- Initial release. Framework-agnostic universal cart engine — mutable drafts,
179
- locked checkout snapshots, composable pricing, and the **LineKind** strategy
180
- that handles every business variation. Zero framework dependencies.
181
-
182
- ### Exports
183
-
184
- - **`.`** (root) — `createCart(config)` engine factory, re-exports of the
185
- most-used services and types.
186
- - **`./domain`** — pure domain types: `Draft`, `Checkout`, `Line`, `Money`,
187
- validity/staleness, idempotency key shapes.
188
- - **`./kinds`** — built-in `sku` LineKind + the generic `LineKind<T>` contract.
189
- - **`./ports`** — 5 bridge ports: `CatalogBridge` (required), `InventoryBridge`,
190
- `PromotionsBridge`, `TaxBridge`, `ShippingBridge`.
191
- - **`./errors`** — typed error classes (`DraftNotFoundError`,
192
- `PriceChangedError`, `InventoryReservationError`, etc.).
193
- - **`./events`** — `cartEventDefinitions`, `OutboxRepository`, payload map;
194
- arc-compatible structural types (no arc import).
195
- - **`./saga`** — checkout state machine (`open → finalized | canceled`),
196
- transition helpers.
197
- - **`./engine`** — engine internals for hosts that want to reach past the
198
- factory.
199
- - **`./schemas`** — Zod schemas for `createCart()` config; exported for hosts
200
- that validate config from env or a database.
201
-
202
- ### Peer dependencies
203
-
204
- - `@classytic/mongokit >= 3.11` — repositories extend `Repository<T>` directly.
205
- - `@classytic/primitives >= 0.1` — `Money`, `OperationContext`, events.
206
- - `@classytic/repo-core >= 0.2` — shared repository abstractions.
207
- - `mongoose >= 9.4` · `zod >= 4`.
208
-
209
- ### Design
210
-
211
- - **No modes / no tiers.** Features light up based on which bridges the host
212
- passes to `createCart()`. Catalog bridge is required; inventory, promo, tax,
213
- shipping are opt-in.
214
- - **Denormalized display snapshot** on every line (`display.name`,
215
- `imageUrl`, `variantLabel`, `compareAtPrice`, `capturedAt`) captured at
216
- add-time by `kind.displayOf()`. UI reads the cart with zero `.populate()`
217
- calls. Drift is cosmetic; price drift is caught via `pricingHash` at checkout.
218
- - **Checkout state machine: 3 states, 2 transitions.** `open → finalized`
219
- (host called `commit`) or `open → canceled`. No payment state inside cart.
220
- - **Idempotent + typed.** Every mutation accepts an idempotency key.
221
- Operations are pure async functions with serializable inputs — agent-ready.
222
- - **Arc-compatible events.** `cartEventDefinitions` are structurally
223
- compatible with arc's `EventDefinitionOutput`; `OutboxRepository` implements
224
- arc's `OutboxStore` without importing arc.
9
+ - Idempotency and reservation repositories read through typed `lean<T>()` results and the id port reads `globalThis.crypto` without a cast. No behaviour change. Consumers: none to change.
@@ -1,4 +1,4 @@
1
- import { _ as CartEventMeta, b as CartEventName, h as CartDomainEvent } from "./outbox-store-Br7MHuOz.mjs";
1
+ import { _ as CartEventMeta, b as CartEventName, h as CartDomainEvent } from "./outbox-store-Cq7K0Lo6.mjs";
2
2
  //#region src/domain/events/event-schema.d.ts
3
3
  /**
4
4
  * EventSchema — minimal JSON-schema-like shape for event payload validation.
@@ -334,6 +334,11 @@ interface ProductSummary {
334
334
  name: string;
335
335
  /** Unit price in minor units. Used by the `sku` and `variant` kinds. */
336
336
  unitPrice: Money;
337
+ /**
338
+ * The quantity increment the product sells in, in the unit `unitPrice` is per (`0.001` kg).
339
+ * Absent = 1, whole units. The catalog's `resolveSalesUnit(...).quantityStep`.
340
+ */
341
+ quantityStep?: number;
337
342
  /** Optional compare-at price for showing strikethrough in the UI. */
338
343
  compareAtPrice?: Money;
339
344
  /**
@@ -4,12 +4,14 @@ import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.m
4
4
  import { n as cryptoIdPort, r as systemClock } from "./id.port-DYAnXbfV.mjs";
5
5
  import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
6
6
  import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-wunwhjap.mjs";
7
- import { t as lineTotal } from "./line-total-6VJQMjGV.mjs";
7
+ import { t as lineTotal } from "./line-total-CHnkZ3nH.mjs";
8
+ import "./engine/cart-config.schema.mjs";
8
9
  import { money } from "@classytic/primitives/money";
9
10
  import { Repository, customIdPlugin, defineModels, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
10
11
  import { CURRENCY_PATTERN, currencyCode } from "@classytic/primitives/currency";
11
12
  import mongoose, { Schema } from "mongoose";
12
13
  import { assertNoLegacyTenantKeys, resolveTenantConfig } from "@classytic/repo-core/tenant";
14
+ import { addQuantity, isOnQuantityGrid, isOnStepStrict, isQuantityStep } from "@classytic/primitives/quantity";
13
15
  import { createHash } from "node:crypto";
14
16
  import { InProcessEventBus } from "@classytic/primitives/event-infra";
15
17
  //#region src/domain/ports/common.ts
@@ -223,8 +225,12 @@ const lineItemSubSchema = new Schema({
223
225
  quantity: {
224
226
  type: Number,
225
227
  required: true,
226
- min: 1
228
+ validate: {
229
+ validator: (v) => v > 0,
230
+ message: "quantity must be > 0"
231
+ }
227
232
  },
233
+ quantityStep: { type: Number },
228
234
  overrideUnitPrice: {
229
235
  type: Schema.Types.Mixed,
230
236
  default: null
@@ -341,7 +347,7 @@ function buildDraftSchema() {
341
347
  },
342
348
  expiresAt: {
343
349
  type: Date,
344
- default: null
350
+ required: true
345
351
  },
346
352
  lastIdempotencyKey: {
347
353
  type: String,
@@ -527,7 +533,10 @@ function buildReservationSchema() {
527
533
  quantity: {
528
534
  type: Number,
529
535
  required: true,
530
- min: 1
536
+ validate: {
537
+ validator: (v) => v > 0,
538
+ message: "quantity must be > 0"
539
+ }
531
540
  },
532
541
  status: {
533
542
  type: String,
@@ -1318,6 +1327,7 @@ var DraftRepository = class extends Repository {
1318
1327
  clock;
1319
1328
  id;
1320
1329
  defaultCurrency;
1330
+ draftRetentionMs;
1321
1331
  eventPublisher;
1322
1332
  constructor(model, plugins, deps) {
1323
1333
  super(model, plugins);
@@ -1326,6 +1336,7 @@ var DraftRepository = class extends Repository {
1326
1336
  this.clock = deps.clock;
1327
1337
  this.id = deps.id;
1328
1338
  this.defaultCurrency = deps.defaultCurrency;
1339
+ this.draftRetentionMs = deps.draftRetentionSeconds * 1e3;
1329
1340
  this.eventPublisher = deps.eventPublisher;
1330
1341
  }
1331
1342
  async findActiveByActor(actorRef, ctx) {
@@ -1362,18 +1373,20 @@ var DraftRepository = class extends Repository {
1362
1373
  async addItem(input, ctx) {
1363
1374
  const draft = await this.getOrCreateDraft(ctx);
1364
1375
  const kind = this.kinds.get(input.kind);
1365
- const quantity = assertPositiveInteger(input.quantity, input.kind);
1376
+ assertPositiveQuantity(input.quantity, input.kind);
1366
1377
  const parsedPayload = kind.payloadSchema.safeParse(input.payload);
1367
1378
  if (!parsedPayload.success) throw new KindError(input.kind, "invalid payload shape", { details: { issues: parsedPayload.error.issues } });
1368
1379
  const newLine = {
1369
1380
  lineId: `line_${this.id.newId()}`,
1370
1381
  kind: input.kind,
1371
- quantity,
1382
+ quantity: input.quantity,
1372
1383
  payload: parsedPayload.data,
1373
1384
  currency: draft.currency,
1374
1385
  overrideUnitPrice: input.overrideUnitPrice
1375
1386
  };
1376
1387
  const kindCtx = this.kindContextFor(ctx);
1388
+ const quantityStep = await resolveQuantityStep(kind.quantityStepOf?.(newLine, kindCtx), input.kind);
1389
+ assertOnStep(newLine.quantity, quantityStep, input.kind);
1377
1390
  await kind.validate(newLine, kindCtx);
1378
1391
  const display = input.display !== void 0 ? input.display : kind.displayOf ? await kind.displayOf(newLine, kindCtx) : null;
1379
1392
  const persistedLine = {
@@ -1381,6 +1394,7 @@ var DraftRepository = class extends Repository {
1381
1394
  kind: newLine.kind,
1382
1395
  payload: newLine.payload,
1383
1396
  quantity: newLine.quantity,
1397
+ ...quantityStep !== 1 ? { quantityStep } : {},
1384
1398
  overrideUnitPrice: newLine.overrideUnitPrice,
1385
1399
  display: display ?? void 0,
1386
1400
  addedAt: this.clock.now()
@@ -1407,7 +1421,7 @@ var DraftRepository = class extends Repository {
1407
1421
  return updated;
1408
1422
  }
1409
1423
  async updateItemQuantity(input, ctx) {
1410
- if (input.quantity < 1) return this.removeItem({
1424
+ if (input.quantity <= 0) return this.removeItem({
1411
1425
  draftPublicId: input.draftPublicId,
1412
1426
  lineId: input.lineId
1413
1427
  }, ctx);
@@ -1415,7 +1429,9 @@ var DraftRepository = class extends Repository {
1415
1429
  const currentLines = draft.lines;
1416
1430
  const existingLine = currentLines.find((l) => l.lineId === input.lineId);
1417
1431
  if (!existingLine) throw new NotFoundError("line", input.lineId, ctx.organizationId);
1418
- const quantity = assertPositiveInteger(input.quantity, existingLine.kind);
1432
+ const quantity = input.quantity;
1433
+ assertPositiveQuantity(quantity, existingLine.kind);
1434
+ assertOnStep(quantity, existingLine.quantityStep ?? 1, existingLine.kind);
1419
1435
  if (existingLine.quantity === quantity) return draft;
1420
1436
  const nextLines = currentLines.map((l) => l.lineId === input.lineId ? {
1421
1437
  ...l,
@@ -1490,7 +1506,8 @@ var DraftRepository = class extends Repository {
1490
1506
  async createForActor(data, ctx) {
1491
1507
  return await this.create({
1492
1508
  ...data,
1493
- version: 0
1509
+ version: 0,
1510
+ expiresAt: this.nextExpiry()
1494
1511
  }, this.writeOptions(ctx));
1495
1512
  }
1496
1513
  /**
@@ -1502,7 +1519,10 @@ var DraftRepository = class extends Repository {
1502
1519
  async updateWithVersion(draftId, expectedVersion, updates, ctx) {
1503
1520
  try {
1504
1521
  return await this.update(draftId, {
1505
- $set: updates,
1522
+ $set: {
1523
+ ...updates,
1524
+ expiresAt: this.nextExpiry()
1525
+ },
1506
1526
  $inc: { version: 1 }
1507
1527
  }, {
1508
1528
  ...this.writeOptions(ctx),
@@ -1528,7 +1548,10 @@ var DraftRepository = class extends Repository {
1528
1548
  async markAbandoned(draftId, ctx, opts = {}) {
1529
1549
  try {
1530
1550
  const updated = await this.update(draftId, {
1531
- $set: { status: "abandoned" },
1551
+ $set: {
1552
+ status: "abandoned",
1553
+ expiresAt: this.nextExpiry()
1554
+ },
1532
1555
  $inc: { version: 1 }
1533
1556
  }, {
1534
1557
  ...this.writeOptions(ctx),
@@ -1590,7 +1613,10 @@ var DraftRepository = class extends Repository {
1590
1613
  async markConverted(draftId, ctx) {
1591
1614
  try {
1592
1615
  await this.update(draftId, {
1593
- $set: { status: "converted" },
1616
+ $set: {
1617
+ status: "converted",
1618
+ expiresAt: this.nextExpiry()
1619
+ },
1594
1620
  $inc: { version: 1 }
1595
1621
  }, this.writeOptions(ctx));
1596
1622
  } catch {}
@@ -1619,6 +1645,10 @@ var DraftRepository = class extends Repository {
1619
1645
  mergeLines(existing, incoming) {
1620
1646
  return incoming.reduce((acc, line) => this.mergeLine(acc, { ...line }), [...existing]);
1621
1647
  }
1648
+ /** The retention deadline every write stamps — the TTL index deletes past it. */
1649
+ nextExpiry() {
1650
+ return new Date(this.clock.now().getTime() + this.draftRetentionMs);
1651
+ }
1622
1652
  readOptions(ctx) {
1623
1653
  return {
1624
1654
  organizationId: ctx.organizationId,
@@ -1671,9 +1701,13 @@ var DraftRepository = class extends Repository {
1671
1701
  if (key === null) return [...existing, incoming];
1672
1702
  const idx = existing.findIndex((l) => this.computeMergeKey(l) === key);
1673
1703
  if (idx === -1) return [...existing, incoming];
1704
+ const quantity = addQuantity(existing[idx].quantity, incoming.quantity);
1705
+ assertOnStep(quantity, incoming.quantityStep ?? 1, incoming.kind);
1706
+ const { quantityStep: _previous, ...base } = existing[idx];
1674
1707
  const merged = {
1675
- ...existing[idx],
1676
- quantity: existing[idx].quantity + incoming.quantity
1708
+ ...base,
1709
+ quantity,
1710
+ ...incoming.quantityStep !== void 0 ? { quantityStep: incoming.quantityStep } : {}
1677
1711
  };
1678
1712
  return existing.map((l, i) => i === idx ? merged : l);
1679
1713
  }
@@ -1710,9 +1744,19 @@ var DraftRepository = class extends Repository {
1710
1744
  function isNotFound$1(err) {
1711
1745
  return typeof err === "object" && err !== null && err.status === 404;
1712
1746
  }
1713
- function assertPositiveInteger(quantity, kind) {
1714
- if (!Number.isInteger(quantity) || quantity < 1) throw new KindError(kind, `quantity must be a positive integer, got ${quantity}`);
1715
- return quantity;
1747
+ function assertPositiveQuantity(quantity, kind) {
1748
+ if (typeof quantity !== "number" || !(quantity > 0) || !isOnQuantityGrid(quantity)) throw new KindError(kind, `quantity must be a positive number with at most 6 decimals, got ${quantity}`);
1749
+ }
1750
+ /** A whole multiple of the line's step; step 1 (no step declared) means a positive integer. */
1751
+ function assertOnStep(quantity, step, kind) {
1752
+ if (!isOnStepStrict(quantity, step)) throw new KindError(kind, step === 1 ? `quantity must be a positive integer, got ${quantity}` : `quantity ${quantity} is not a multiple of the line's step ${step}`);
1753
+ }
1754
+ /** The kind's declared step, absent = 1. A malformed step is the kind's fault and refuses the add. */
1755
+ async function resolveQuantityStep(pending, kind) {
1756
+ const step = pending === void 0 ? void 0 : await pending;
1757
+ if (step === void 0) return 1;
1758
+ if (!isQuantityStep(step)) throw new KindError(kind, `quantityStepOf returned an invalid step: ${String(step)}`);
1759
+ return step;
1716
1760
  }
1717
1761
  //#endregion
1718
1762
  //#region src/repositories/idempotency.repository.ts
@@ -1738,7 +1782,7 @@ var IdempotencyRepository = class extends Repository {
1738
1782
  /** Look up a record by the full composite identity. */
1739
1783
  async findByIdentity(identity, ctx) {
1740
1784
  const session = ctx.session;
1741
- return await this.Model.findOne({
1785
+ return this.Model.findOne({
1742
1786
  organizationId: identity.organizationId,
1743
1787
  cartRef: identity.cartRef,
1744
1788
  operation: identity.operation,
@@ -1755,12 +1799,13 @@ var IdempotencyRepository = class extends Repository {
1755
1799
  async insertInFlight(identity, leaseToken, leaseExpiresAt, ctx) {
1756
1800
  const session = ctx.session;
1757
1801
  try {
1758
- return (await this.Model.create([{
1802
+ const [inserted] = await this.Model.create([{
1759
1803
  ...identity,
1760
1804
  status: "in_flight",
1761
1805
  leaseToken,
1762
1806
  leaseExpiresAt
1763
- }], { session }))[0];
1807
+ }], { session });
1808
+ return inserted ?? null;
1764
1809
  } catch (err) {
1765
1810
  if (isDuplicateKeyError(err)) return null;
1766
1811
  throw err;
@@ -1886,7 +1931,7 @@ var CartEventPublisher = class {
1886
1931
  var ReservationRepository = class extends Repository {
1887
1932
  /** All reservations belonging to a checkout. */
1888
1933
  async findByCheckout(checkoutId, ctx) {
1889
- return await this.findAll({ checkoutId }, this.readOptions(ctx));
1934
+ return this.findAll({ checkoutId }, this.readOptions(ctx));
1890
1935
  }
1891
1936
  /**
1892
1937
  * Expired held reservations for the sweeper. Routed through `getAll` so
@@ -1973,7 +2018,7 @@ function tenantPlugin(tenant) {
1973
2018
  });
1974
2019
  }
1975
2020
  function createCartRepositories(models, config) {
1976
- const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenant, staleOpenCheckoutMs } = config;
2021
+ const { kinds, bridges, clock, id, defaultCurrency, draftRetentionSeconds, events, outbox, plugins = {}, tenant, staleOpenCheckoutMs } = config;
1977
2022
  const eventPublisher = new CartEventPublisher({
1978
2023
  events,
1979
2024
  outbox,
@@ -1997,6 +2042,7 @@ function createCartRepositories(models, config) {
1997
2042
  clock,
1998
2043
  id,
1999
2044
  defaultCurrency,
2045
+ draftRetentionSeconds,
2000
2046
  eventPublisher
2001
2047
  });
2002
2048
  return {
@@ -2116,6 +2162,8 @@ function defineCart(shape) {
2116
2162
  requireKinds(shape);
2117
2163
  const tenant = resolveCartTenant(shape.tenant ?? true);
2118
2164
  const defaultCurrency = currencyCode(shape.defaultCurrency ?? "USD");
2165
+ const draftRetentionSeconds = shape.draftRetentionSeconds ?? 7776e3;
2166
+ if (!Number.isInteger(draftRetentionSeconds) || draftRetentionSeconds <= 0) throw new Error(`defineCart: draftRetentionSeconds must be a positive integer, got ${draftRetentionSeconds}`);
2119
2167
  const modelBlueprint = defineCartModels({
2120
2168
  tenant,
2121
2169
  ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
@@ -2162,6 +2210,7 @@ function defineCart(shape) {
2162
2210
  clock,
2163
2211
  id,
2164
2212
  defaultCurrency,
2213
+ draftRetentionSeconds,
2165
2214
  events,
2166
2215
  ...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
2167
2216
  ...runtime.repositoryPlugins !== void 0 ? { plugins: runtime.repositoryPlugins } : {},
@@ -2174,6 +2223,7 @@ function defineCart(shape) {
2174
2223
  tenant,
2175
2224
  forceRecreate: shape.forceRecreate ?? false,
2176
2225
  defaultCurrency,
2226
+ draftRetentionSeconds,
2177
2227
  allowNonTransactional,
2178
2228
  ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
2179
2229
  ...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
@@ -1,3 +1,3 @@
1
- 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-Br7MHuOz.mjs";
2
- 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-Cokx0iOw.mjs";
1
+ 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-Cq7K0Lo6.mjs";
2
+ 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-DZvoNVek.mjs";
3
3
  export { type CartAggregateType, type CartDomainEvent, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventRegistry, CartEvents, type EventSchema, type EventSchemaProperty, type EventValidationResult, type EventValidator, InvalidOutboxEventError, MemoryOutboxStore, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, defineCartEvent };
@@ -1,13 +1,13 @@
1
1
  import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, g as CartErrorCategory, h as CartError, i as IdempotencyBusyError, l as PriceChangedError, m as ConcurrencyError, n as StateTransitionError, o as SagaError, p as CurrencyMismatchError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../index-BTSo-RLv.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "../cart-status.vo-BoVPaSXX.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-Br7MHuOz.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-Cokx0iOw.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-Cq7K0Lo6.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-DZvoNVek.mjs";
5
5
  import "./events/index.mjs";
6
- import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../clock.port-DrSBrsit.mjs";
7
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-CLRqLD6X.mjs";
8
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../state-transitions-B_ozUaqV.mjs";
9
- 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-kYeQzpCy.mjs";
10
- import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "../kind-registry-BkYl0cjc.mjs";
6
+ import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../clock.port-BFg5X92u.mjs";
7
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-9V2i4i1l.mjs";
8
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../state-transitions-B3EPuOae.mjs";
9
+ 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-CY7cabbf.mjs";
10
+ import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "../kind-registry-Cb50lwpo.mjs";
11
11
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../id.port-DzgWy8sy.mjs";
12
12
  import "./ports/index.mjs";
13
13
  import "./saga/index.mjs";
@@ -1,3 +1,3 @@
1
- import { C as OperationContext, S as BridgeStatus, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../../clock.port-DrSBrsit.mjs";
1
+ import { C as OperationContext, S as BridgeStatus, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../../clock.port-BFg5X92u.mjs";
2
2
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../../id.port-DzgWy8sy.mjs";
3
3
  export { type AdjustmentSpec, type BridgeRef, type BridgeStatus, type CartSnapshot, type CatalogBridge, type ClockPort, type IdPort, type InventoryBridge, type OperationContext, type ProductSummary, type PromotionResult, type PromotionsBridge, type ReservationRef, type ReservationRequest, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, createCounterIdPort, cryptoIdPort, systemClock };
@@ -1,2 +1 @@
1
- import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "../../id.port-DYAnXbfV.mjs";
2
- export { createCounterIdPort, cryptoIdPort, systemClock };
1
+ export { t as createCounterIdPort, n as cryptoIdPort, r as systemClock } from "../../id.port-DYAnXbfV.mjs";
@@ -1,2 +1,2 @@
1
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../../state-transitions-B_ozUaqV.mjs";
1
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../../state-transitions-B3EPuOae.mjs";
2
2
  export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, type CheckoutFlowState, CheckoutStep, type CheckoutStepNumber, type SagaDependencies, type SagaStepFn, isLegalCheckoutTransition };
@@ -1,2 +1 @@
1
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-wunwhjap.mjs";
2
- export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CheckoutStep, isLegalCheckoutTransition };
1
+ export { t as CHECKOUT_MACHINE, n as CHECKOUT_STATE_TRANSITIONS, i as CheckoutStep, r as isLegalCheckoutTransition } from "../../state-transitions-wunwhjap.mjs";
@@ -5,21 +5,23 @@ import { z } from "zod";
5
5
  * fields (kinds, bridges) carry functions and class instances and are validated
6
6
  * structurally by `defineCart` / its bind runtime.
7
7
  */
8
- declare const idempotencyConfigSchema: z.ZodObject<{
8
+ /** Default draft retention: 90 days after the last write. */
9
+ export declare const DEFAULT_DRAFT_RETENTION_SECONDS: number;
10
+ export declare const idempotencyConfigSchema: z.ZodObject<{
9
11
  inlineThresholdBytes: z.ZodDefault<z.ZodNumber>;
10
12
  leaseMs: z.ZodDefault<z.ZodNumber>;
11
13
  retentionSeconds: z.ZodDefault<z.ZodNumber>;
12
14
  }, z.core.$strip>;
13
- declare const reservationConfigSchema: z.ZodObject<{
15
+ export declare const reservationConfigSchema: z.ZodObject<{
14
16
  defaultTtlSeconds: z.ZodDefault<z.ZodNumber>;
15
17
  }, z.core.$strip>;
16
- declare const checkoutConfigSchema: z.ZodObject<{
18
+ export declare const checkoutConfigSchema: z.ZodObject<{
17
19
  staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
18
20
  }, z.core.$strip>;
19
- declare const scopeConfigSchema: z.ZodObject<{
21
+ export declare const scopeConfigSchema: z.ZodObject<{
20
22
  contextKey: z.ZodDefault<z.ZodString>;
21
23
  }, z.core.$strip>;
22
- declare const cartConfigSchema: z.ZodObject<{
24
+ export declare const cartConfigSchema: z.ZodObject<{
23
25
  scope: z.ZodDefault<z.ZodObject<{
24
26
  contextKey: z.ZodDefault<z.ZodString>;
25
27
  }, z.core.$strip>>;
@@ -35,12 +37,11 @@ declare const cartConfigSchema: z.ZodObject<{
35
37
  checkout: z.ZodDefault<z.ZodObject<{
36
38
  staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
37
39
  }, z.core.$strip>>;
38
- draftTtlSeconds: z.ZodOptional<z.ZodNumber>;
40
+ draftRetentionSeconds: z.ZodDefault<z.ZodNumber>;
39
41
  }, z.core.$strip>;
40
42
  /**
41
43
  * The strict config type inferred from the schema. Used for runtime
42
44
  * validation of user-supplied config from env/YAML.
43
45
  */
44
- type CartConfigShape = z.infer<typeof cartConfigSchema>;
45
- //#endregion
46
- export { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
46
+ export type CartConfigShape = z.infer<typeof cartConfigSchema>;
47
+ //#endregion
@@ -6,6 +6,8 @@ import { z } from "zod";
6
6
  * fields (kinds, bridges) carry functions and class instances and are validated
7
7
  * structurally by `defineCart` / its bind runtime.
8
8
  */
9
+ /** Default draft retention: 90 days after the last write. */
10
+ const DEFAULT_DRAFT_RETENTION_SECONDS = 7776e3;
9
11
  const idempotencyConfigSchema = z.object({
10
12
  /** Inline replay payload byte threshold. Default 12KB. */
11
13
  inlineThresholdBytes: z.number().int().positive().default(12288),
@@ -43,8 +45,12 @@ const cartConfigSchema = z.object({
43
45
  }),
44
46
  reservation: reservationConfigSchema.default({ defaultTtlSeconds: 600 }),
45
47
  checkout: checkoutConfigSchema.default({ staleOpenCheckoutMs: 6e5 }),
46
- /** Whether drafts auto-expire via TTL. Default off. */
47
- draftTtlSeconds: z.number().int().positive().optional()
48
+ /**
49
+ * Draft retention: every draft write stamps `expiresAt = now + this`, and the
50
+ * TTL index deletes the draft once it passes. Idle active carts, abandoned and
51
+ * converted drafts all expire. Default 90 days.
52
+ */
53
+ draftRetentionSeconds: z.number().int().positive().default(DEFAULT_DRAFT_RETENTION_SECONDS)
48
54
  });
49
55
  //#endregion
50
- export { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
56
+ export { DEFAULT_DRAFT_RETENTION_SECONDS, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
1
  import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
2
- import { a as defineCart, c as CartEngine, d as CartShape, f as ResolvedCartConfig, i as createCartDomain, l as CartLogger, n as CartBlueprint, o as CartBridges, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime } from "../internal-event-bus-CC0PxRhB.mjs";
2
+ import { a as defineCart, c as CartEngine, d as CartShape, f as ResolvedCartConfig, i as createCartDomain, l as CartLogger, n as CartBlueprint, o as CartBridges, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime } from "../internal-event-bus-BfC4OKwH.mjs";
3
3
  export { type CartBlueprint, type CartBridges, type CartConfigShape, type CartDomain, type CartDomainRuntime, type CartEngine, type CartLogger, type CartRuntime, type CartShape, InProcessCartEventBus, type ResolvedCartConfig, cartConfigSchema, checkoutConfigSchema, createCartDomain, defineCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
- import { n as defineCart, r as InProcessCartEventBus, t as createCartDomain } from "../define-cart-DESSv8Rt.mjs";
1
+ import { n as defineCart, r as InProcessCartEventBus, t as createCartDomain } from "../define-cart-BKV3M4pm.mjs";
2
2
  import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, checkoutConfigSchema, createCartDomain, defineCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
package/dist/index.d.mts CHANGED
@@ -1,16 +1,16 @@
1
1
  import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, g as CartErrorCategory, h as CartError, i as IdempotencyBusyError, l as PriceChangedError, m as ConcurrencyError, n as StateTransitionError, o as SagaError, p as CurrencyMismatchError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "./index-BTSo-RLv.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-BoVPaSXX.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-Br7MHuOz.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-Cokx0iOw.mjs";
5
- import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, b as Address, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, w as PENDING_EVENTS, x as BridgeRef, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
6
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-CLRqLD6X.mjs";
7
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep } from "./state-transitions-B_ozUaqV.mjs";
8
- import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "./line-kind-kYeQzpCy.mjs";
9
- import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-BkYl0cjc.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-Cq7K0Lo6.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-DZvoNVek.mjs";
5
+ import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, b as Address, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, w as PENDING_EVENTS, x as BridgeRef, y as PromotionsBridge } from "./clock.port-BFg5X92u.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-9V2i4i1l.mjs";
7
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep } from "./state-transitions-B3EPuOae.mjs";
8
+ import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "./line-kind-CY7cabbf.mjs";
9
+ import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-Cb50lwpo.mjs";
10
10
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DzgWy8sy.mjs";
11
11
  import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
- import { A as buildReservationSchema, C as DraftRepositoryDeps, D as DefineCartModelsConfig, E as CartModels, F as CheckoutDocument, I as buildCheckoutSchema, M as buildIdempotencySchema, N as DraftDocument, O as defineCartModels, P as buildDraftSchema, S as DraftRepository, T as CartModelName, _ as ReservationRepository, a as defineCart, b as CheckoutRepositoryDeps, c as CartEngine, d as CartShape, f as ResolvedCartConfig, g as createCartRepositories, h as CreateCartRepositoriesConfig, i as createCartDomain, j as IdempotencyDocument, k as ReservationDocument, l as CartLogger, m as CartRepositoryPluginBundle, n as CartBlueprint, o as CartBridges, p as CartRepositories, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime, v as IdempotencyRepository, w as CartEventPublisherDeps, x as DEFAULT_STALE_OPEN_CHECKOUT_MS, y as CheckoutRepository } from "./internal-event-bus-CC0PxRhB.mjs";
13
- import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "./variant.kind-BVmeGR6G.mjs";
12
+ import { A as buildReservationSchema, C as DraftRepositoryDeps, D as DefineCartModelsConfig, E as CartModels, F as CheckoutDocument, I as buildCheckoutSchema, M as buildIdempotencySchema, N as DraftDocument, O as defineCartModels, P as buildDraftSchema, S as DraftRepository, T as CartModelName, _ as ReservationRepository, a as defineCart, b as CheckoutRepositoryDeps, c as CartEngine, d as CartShape, f as ResolvedCartConfig, g as createCartRepositories, h as CreateCartRepositoriesConfig, i as createCartDomain, j as IdempotencyDocument, k as ReservationDocument, l as CartLogger, m as CartRepositoryPluginBundle, n as CartBlueprint, o as CartBridges, p as CartRepositories, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime, v as IdempotencyRepository, w as CartEventPublisherDeps, x as DEFAULT_STALE_OPEN_CHECKOUT_MS, y as CheckoutRepository } from "./internal-event-bus-BfC4OKwH.mjs";
13
+ import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "./variant.kind-DQxxcsib.mjs";
14
14
  import { Money, Money as Money$1, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
15
  import { DomainEvent, EventHandler, EventTransport, EventTransport as EventTransport$1, PublishManyResult } from "@classytic/primitives/events";
16
16
  import { CurrencyCode } from "@classytic/primitives/currency";
@@ -24,7 +24,7 @@ import { CleanupStep } from "@classytic/repo-core/cleanup";
24
24
  * Hosts composing their own outer transaction call this after commit;
25
25
  * most should use `engine.withTransaction(ctx, fn)` instead.
26
26
  */
27
- declare function flushPending(eventTransport: EventTransport$1 | undefined, events: DomainEvent[], logger?: {
27
+ export declare function flushPending(eventTransport: EventTransport$1 | undefined, events: DomainEvent[], logger?: {
28
28
  error(message: string, ...args: unknown[]): void;
29
29
  }): Promise<void>;
30
30
  //#endregion
@@ -40,7 +40,7 @@ declare function flushPending(eventTransport: EventTransport$1 | undefined, even
40
40
  * scopes the query at POLICY priority — pass `skipTenant: true` on `ctx`
41
41
  * for cross-tenant admin sweeps.
42
42
  */
43
- declare function findAbandonedDrafts(opts: {
43
+ export declare function findAbandonedDrafts(opts: {
44
44
  repo: DraftRepository;
45
45
  cutoff: Date;
46
46
  limit?: number;
@@ -50,7 +50,7 @@ declare function findAbandonedDrafts(opts: {
50
50
  * Mark a batch of drafts as abandoned. Returns the count of drafts
51
51
  * successfully transitioned.
52
52
  */
53
- declare function markAbandoned(opts: {
53
+ export declare function markAbandoned(opts: {
54
54
  repo: DraftRepository;
55
55
  draftIds: string[];
56
56
  ctx: OperationContext;
@@ -95,7 +95,7 @@ declare function markAbandoned(opts: {
95
95
  * After merging, the source draft is marked `abandoned` so it's no
96
96
  * longer active.
97
97
  */
98
- declare function mergeDrafts(opts: {
98
+ export declare function mergeDrafts(opts: {
99
99
  repo: DraftRepository;
100
100
  sourcePublicId: string;
101
101
  targetActorRef: string;
@@ -127,7 +127,7 @@ declare function mergeDrafts(opts: {
127
127
  * Unit prices can drift between caches — the pricing hash interlock at
128
128
  * checkout-freeze still catches drift, so reuse here is safe.
129
129
  */
130
- declare function runPricing(opts: {
130
+ export declare function runPricing(opts: {
131
131
  lines: readonly LineItem[];
132
132
  currency: CurrencyCode;
133
133
  kinds: KindRegistry;
@@ -181,7 +181,7 @@ type ResolvedTenant = ResolvedTenantConfig;
181
181
  * A `CartError` subclass so hosts catch cleanup failures with the same
182
182
  * `instanceof CartError` net as every other cart error.
183
183
  */
184
- declare class CleanupError extends CartError {
184
+ export declare class CleanupError extends CartError {
185
185
  readonly code: string;
186
186
  readonly category: CartErrorCategory;
187
187
  readonly retryable: boolean;
@@ -199,7 +199,7 @@ declare class CleanupError extends CartError {
199
199
  * module's docblock. `active` (live) and `converted` (became an order —
200
200
  * business history) are never included.
201
201
  */
202
- declare const DISPOSABLE_DRAFT_STATUSES: readonly DraftStatus[];
202
+ export declare const DISPOSABLE_DRAFT_STATUSES: readonly DraftStatus[];
203
203
  /**
204
204
  * The repository surface the step drives — a structural subset of a
205
205
  * `CartEngine` (`engine.repositories`), so a host can pass the engine's
@@ -214,6 +214,6 @@ interface CartCleanupSteps {
214
214
  /** §4.1 remove-abandoned-carts provider — destructive (hard-delete). */
215
215
  removeAbandonedCarts: CleanupStep;
216
216
  }
217
- declare function createCartCleanupSteps(source: CartCleanupSource): CartCleanupSteps;
217
+ export declare function createCartCleanupSteps(source: CartCleanupSource): CartCleanupSteps;
218
218
  //#endregion
219
- export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBlueprint, type CartBridges, type CartCleanupSource, type CartCleanupSteps, type CartConfigShape, type CartDomain, type CartDomainEvent, type CartDomainRuntime, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartLogger, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartRuntime, type CartShape, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, CleanupError, type ClockPort, ConcurrencyError, type CreateCartRepositoriesConfig, CurrencyMismatchError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DISPOSABLE_DRAFT_STATUSES, type DefineCartModelsConfig, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, PENDING_EVENTS, 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 ResolvedCartConfig, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, UnmanagedSessionError, type ValidityPolicy, type VariantPayload, addMoney, buildCheckoutSchema, buildDraftSchema, buildIdempotencySchema, buildReservationSchema, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCartCleanupSteps, createCartDomain, createCartEvent, createCartEventRegistry, createCartRepositories, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCart, defineCartEvent, defineCartModels, findAbandonedDrafts, flushPending, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
219
+ export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBlueprint, type CartBridges, type CartCleanupSource, type CartCleanupSteps, type CartConfigShape, type CartDomain, type CartDomainEvent, type CartDomainRuntime, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartLogger, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartRuntime, type CartShape, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartRepositoriesConfig, CurrencyMismatchError, DEFAULT_STALE_OPEN_CHECKOUT_MS, type DefineCartModelsConfig, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, PENDING_EVENTS, 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 ResolvedCartConfig, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, UnmanagedSessionError, type ValidityPolicy, type VariantPayload, addMoney, buildCheckoutSchema, buildDraftSchema, buildIdempotencySchema, buildReservationSchema, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCartDomain, createCartEvent, createCartEventRegistry, createCartRepositories, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCart, defineCartEvent, defineCartModels, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, money, multiplyMoney, reservationConfigSchema, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
package/dist/index.mjs CHANGED
@@ -7,10 +7,10 @@ import { t as StateTransitionError } from "./state-transition.error-BssJiRoW.mjs
7
7
  import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-DLxCPOUN.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-DYAnXbfV.mjs";
10
- import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-DESSv8Rt.mjs";
10
+ import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-BKV3M4pm.mjs";
11
11
  import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
12
12
  import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-wunwhjap.mjs";
13
- import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "./variant.kind-CquIUes6.mjs";
13
+ import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "./variant.kind-_LIXlTwp.mjs";
14
14
  import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
15
15
  import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
16
16
  //#region src/services/abandonment.service.ts
@@ -1,7 +1,7 @@
1
- import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-Br7MHuOz.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-DrSBrsit.mjs";
3
- import { l as LineDisplay, r as LineKind } from "./line-kind-kYeQzpCy.mjs";
4
- import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-BkYl0cjc.mjs";
1
+ import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-Cq7K0Lo6.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-BFg5X92u.mjs";
3
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CY7cabbf.mjs";
4
+ import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-Cb50lwpo.mjs";
5
5
  import { t as IdPort } from "./id.port-DzgWy8sy.mjs";
6
6
  import { CartConfigShape } from "./engine/cart-config.schema.mjs";
7
7
  import { Money } from "@classytic/primitives/money";
@@ -79,7 +79,8 @@ interface DraftDocument extends Document {
79
79
  currency: CurrencyCode;
80
80
  pricing: Record<string, unknown> | null;
81
81
  version: number;
82
- expiresAt?: Date | null;
82
+ /** Retention deadline, stamped by every repository write; the TTL index deletes past it. */
83
+ expiresAt: Date;
83
84
  lastIdempotencyKey?: string;
84
85
  metadata?: Record<string, unknown>;
85
86
  privateMetadata?: Record<string, unknown>;
@@ -231,6 +232,8 @@ interface DraftRepositoryDeps {
231
232
  clock: ClockPort;
232
233
  id: IdPort;
233
234
  defaultCurrency: CurrencyCode;
235
+ /** Every draft write stamps `expiresAt = now + this` (seconds). */
236
+ draftRetentionSeconds: number;
234
237
  eventPublisher: CartEventPublisher;
235
238
  }
236
239
  /**
@@ -261,6 +264,7 @@ declare class DraftRepository extends Repository<DraftDocument> {
261
264
  private readonly clock;
262
265
  private readonly id;
263
266
  private readonly defaultCurrency;
267
+ private readonly draftRetentionMs;
264
268
  private readonly eventPublisher;
265
269
  constructor(model: Model<DraftDocument>, plugins: PluginType[], deps: DraftRepositoryDeps);
266
270
  findActiveByActor(actorRef: string, ctx: OperationContext): Promise<DraftDocument | null>;
@@ -358,6 +362,8 @@ declare class DraftRepository extends Repository<DraftDocument> {
358
362
  expectedVersion?: number;
359
363
  }, ctx: OperationContext): Promise<DraftDocument>;
360
364
  mergeLines(existing: readonly LineItem[], incoming: readonly LineItem[]): LineItem[];
365
+ /** The retention deadline every write stamps — the TTL index deletes past it. */
366
+ private nextExpiry;
361
367
  private readOptions;
362
368
  private writeOptions;
363
369
  private price;
@@ -595,6 +601,8 @@ interface CreateCartRepositoriesConfig {
595
601
  id: IdPort;
596
602
  /** Validated + branded once at the config edge in `defineCart`. */
597
603
  defaultCurrency: CurrencyCode;
604
+ /** Seconds after a draft's last write before its TTL removes it. */
605
+ draftRetentionSeconds: number;
598
606
  events: EventTransport;
599
607
  tenant: ResolvedTenantConfig;
600
608
  outbox?: OutboxStore;
@@ -718,6 +726,8 @@ interface ResolvedCartConfig {
718
726
  forceRecreate: boolean;
719
727
  /** Validated + branded once at the config edge in `defineCart`. */
720
728
  defaultCurrency: CurrencyCode;
729
+ /** Seconds after a draft's last write before its TTL removes it. */
730
+ draftRetentionSeconds: number;
721
731
  collectionPrefix?: string;
722
732
  allowNonTransactional: boolean;
723
733
  staleOpenCheckoutMs?: number;
@@ -1,4 +1,4 @@
1
- import { l as LineDisplay, r as LineKind } from "./line-kind-kYeQzpCy.mjs";
1
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CY7cabbf.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  //#region src/domain/entities/line-item.entity.d.ts
4
4
  /**
@@ -28,8 +28,14 @@ interface LineItem<TPayload = unknown> {
28
28
  * the draft service boundary.
29
29
  */
30
30
  payload: TPayload;
31
- /** Units. Always a positive integer. */
31
+ /** Quantity in the item's unit: a positive multiple of `quantityStep`. */
32
32
  quantity: number;
33
+ /**
34
+ * The increment the line sells in (`0.001` for rice by the kg), from the kind's
35
+ * `quantityStepOf` at add time. Absent = 1: whole units, the rule for every kind that
36
+ * declares no step.
37
+ */
38
+ quantityStep?: number;
33
39
  /**
34
40
  * Optional unit-price override — when the host wants to force a price
35
41
  * regardless of what the kind would compute. Used by admin tools and
@@ -109,7 +115,7 @@ interface IdempotencyReplay {
109
115
  * Using a literal rather than null keeps the composite index unique-safe
110
116
  * under MongoDB semantics (nulls are considered equal by the unique index).
111
117
  */
112
- declare const CART_REF_NEW: "new";
118
+ declare const CART_REF_NEW: 'new';
113
119
  /**
114
120
  * Convenience type — the pricing totals referenced from an idempotency record
115
121
  * for fast UI display on replay hits. Not part of the replay payload itself;
@@ -1,2 +1,2 @@
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-BVmeGR6G.mjs";
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-DQxxcsib.mjs";
2
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 @@
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-CquIUes6.mjs";
2
- export { bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
1
+ export { l as bundleKind, u as bundlePayloadSchema, s as serviceFeeKind, c as serviceFeePayloadSchema, a as skuKind, o as skuPayloadSchema, r as timeslotKind, i as timeslotPayloadSchema, t as variantKind, n as variantPayloadSchema } from "../variant.kind-_LIXlTwp.mjs";
@@ -1,4 +1,4 @@
1
- import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
1
+ import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-BFg5X92u.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { z } from "zod";
4
4
  //#region src/domain/value-objects/line-display.vo.d.ts
@@ -178,6 +178,12 @@ interface LineKind<TPayload = unknown> {
178
178
  * previous behavior.
179
179
  */
180
180
  mergeKey?(line: LineLike<TPayload>): string | null;
181
+ /**
182
+ * Optional — the quantity increment this line sells in (`0.001` for rice by the kg). The draft
183
+ * repository checks every quantity against it and stores it on the line. Omitted, or
184
+ * `undefined`, means 1: whole units only.
185
+ */
186
+ quantityStepOf?(line: LineLike<TPayload>, ctx: KindContext): Promise<number | undefined>;
181
187
  }
182
188
  /**
183
189
  * The minimal shape the kind receives. Deliberately not the full LineItem
@@ -0,0 +1,25 @@
1
+ import { resolvePriceBasisTotal } from "@classytic/primitives/price-basis";
2
+ //#region src/domain/value-objects/line-total.ts
3
+ /**
4
+ * `unitPrice × quantity` in minor units — the one multiply both the fresh `kind.price()` path and
5
+ * the incremental reprice (`rebuildSubtotals`) use. A fractional quantity (2.35 kg) is extended
6
+ * exactly on the 6-dp grid and rounded once, half-even.
7
+ *
8
+ * Throws `RangeError` past `Number.MAX_SAFE_INTEGER` (on the FIRST add, not a later reprice), and
9
+ * primitives' `PriceBasisError` for a quantity off the grid.
10
+ */
11
+ /** A fractional `unitPrice × quantity`, exact on the 6-dp grid; a negative price keeps its sign. */
12
+ function extendMinor(unitPrice, quantity) {
13
+ const magnitude = resolvePriceBasisTotal(Math.abs(unitPrice), quantity);
14
+ return unitPrice < 0 && magnitude !== 0 ? -magnitude : magnitude;
15
+ }
16
+ function lineTotal(unitPrice, quantity) {
17
+ const amount = Number.isInteger(quantity) ? unitPrice.amount * quantity : extendMinor(unitPrice.amount, quantity);
18
+ if (!Number.isSafeInteger(amount)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${quantity} exceeds Number.MAX_SAFE_INTEGER`);
19
+ return {
20
+ amount,
21
+ currency: unitPrice.currency
22
+ };
23
+ }
24
+ //#endregion
25
+ export { lineTotal as t };
@@ -16,17 +16,17 @@ import { MemoryOutboxStore } from "@classytic/primitives/memory-outbox";
16
16
  * as a `CartEventDefinition` via `defineCartEvent()`.
17
17
  */
18
18
  declare const CartEvents: {
19
- readonly DRAFT_CREATED: "cart.draft.created";
20
- readonly DRAFT_ITEM_ADDED: "cart.draft.item_added";
21
- readonly DRAFT_ITEM_UPDATED: "cart.draft.item_updated";
22
- readonly DRAFT_ITEM_REMOVED: "cart.draft.item_removed";
23
- readonly DRAFT_PROMO_APPLIED: "cart.draft.promo_applied";
24
- readonly DRAFT_MERGED: "cart.draft.merged";
25
- readonly DRAFT_ABANDONED: "cart.draft.abandoned";
26
- readonly DRAFT_EXPIRED: "cart.draft.expired";
27
- readonly CHECKOUT_CREATED: "cart.checkout.created";
28
- readonly CHECKOUT_COMMITTED: "cart.checkout.committed";
29
- readonly CHECKOUT_CANCELED: "cart.checkout.canceled";
19
+ readonly DRAFT_CREATED: 'cart.draft.created';
20
+ readonly DRAFT_ITEM_ADDED: 'cart.draft.item_added';
21
+ readonly DRAFT_ITEM_UPDATED: 'cart.draft.item_updated';
22
+ readonly DRAFT_ITEM_REMOVED: 'cart.draft.item_removed';
23
+ readonly DRAFT_PROMO_APPLIED: 'cart.draft.promo_applied';
24
+ readonly DRAFT_MERGED: 'cart.draft.merged';
25
+ readonly DRAFT_ABANDONED: 'cart.draft.abandoned';
26
+ readonly DRAFT_EXPIRED: 'cart.draft.expired';
27
+ readonly CHECKOUT_CREATED: 'cart.checkout.created';
28
+ readonly CHECKOUT_COMMITTED: 'cart.checkout.committed';
29
+ readonly CHECKOUT_CANCELED: 'cart.checkout.canceled';
30
30
  };
31
31
  type CartEventName = (typeof CartEvents)[keyof typeof CartEvents];
32
32
  interface CartEventPayloadBase {
@@ -1,7 +1,7 @@
1
1
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-BoVPaSXX.mjs";
2
- import { E as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-DrSBrsit.mjs";
3
- import { o as CheckoutFlowState } from "./state-transitions-B_ozUaqV.mjs";
4
- import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-BkYl0cjc.mjs";
2
+ import { E as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-BFg5X92u.mjs";
3
+ import { o as CheckoutFlowState } from "./state-transitions-B3EPuOae.mjs";
4
+ import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-Cb50lwpo.mjs";
5
5
  import { Money } from "@classytic/primitives/money";
6
6
  //#region src/domain/entities/adjustment.entity.d.ts
7
7
  /**
@@ -124,8 +124,8 @@ interface Draft {
124
124
  pricing: PricingSnapshot | null;
125
125
  /** Optimistic-lock version. Incremented on every write. */
126
126
  version: number;
127
- /** Optional TTL — opt-in per plan Open Question #4. */
128
- expiresAt?: Date;
127
+ /** Retention deadline, restamped on every write; the TTL index deletes past it. */
128
+ expiresAt: Date;
129
129
  /** Idempotency key of the operation that last mutated this draft. */
130
130
  lastIdempotencyKey?: string;
131
131
  /** Public metadata bag for host extensibility. */
@@ -1,6 +1,6 @@
1
1
  import { t as CheckoutState } from "./cart-status.vo-BoVPaSXX.mjs";
2
- import { C as OperationContext, t as ClockPort } from "./clock.port-DrSBrsit.mjs";
3
- import { t as KindBridges } from "./line-kind-kYeQzpCy.mjs";
2
+ import { C as OperationContext, t as ClockPort } from "./clock.port-BFg5X92u.mjs";
3
+ import { t as KindBridges } from "./line-kind-CY7cabbf.mjs";
4
4
  import { t as IdPort } from "./id.port-DzgWy8sy.mjs";
5
5
  //#region src/domain/saga/saga-steps.d.ts
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { r as LineKind } from "./line-kind-kYeQzpCy.mjs";
1
+ import { r as LineKind } from "./line-kind-CY7cabbf.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { CurrencyCode } from "@classytic/primitives/currency";
4
4
  import { z } from "zod";
@@ -1,5 +1,5 @@
1
1
  import { t as KindError } from "./kind.error-BoyoVjKx.mjs";
2
- import { t as lineTotal } from "./line-total-6VJQMjGV.mjs";
2
+ import { t as lineTotal } from "./line-total-CHnkZ3nH.mjs";
3
3
  import { isCurrencyCode } from "@classytic/primitives/currency";
4
4
  import { z } from "zod";
5
5
  //#region src/kinds/bundle.kind.ts
@@ -198,7 +198,7 @@ const skuKind = {
198
198
  async validate(line, ctx) {
199
199
  const parsed = skuPayloadSchema.safeParse(line.payload);
200
200
  if (!parsed.success) throw new KindError(this.name, "invalid payload shape", { details: { issues: parsed.error.issues } });
201
- if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
201
+ if (!(line.quantity > 0)) throw new KindError(this.name, `quantity must be > 0, got ${line.quantity}`);
202
202
  if (line.overrideUnitPrice && line.overrideUnitPrice.currency !== line.currency) throw new KindError(this.name, `override unit price currency ${line.overrideUnitPrice.currency} does not match cart currency ${line.currency}`);
203
203
  const product = await ctx.bridges.catalog.resolve(parsed.data.skuRef, ctx);
204
204
  if (!product) throw new KindError(this.name, `unknown skuRef: ${parsed.data.skuRef}`);
@@ -236,6 +236,11 @@ const skuKind = {
236
236
  priced
237
237
  };
238
238
  },
239
+ /** The product's step (`0.001` kg for loose rice); the draft repository checks quantities against it. */
240
+ async quantityStepOf(line, ctx) {
241
+ const typed = line;
242
+ return (await ctx.bridges.catalog.resolve(typed.payload.skuRef, ctx))?.quantityStep;
243
+ },
239
244
  mergeKey(line) {
240
245
  const typed = line;
241
246
  if (!typed.payload?.skuRef) return null;
@@ -384,7 +389,7 @@ const variantKind = {
384
389
  async validate(line, ctx) {
385
390
  const parsed = variantPayloadSchema.safeParse(line.payload);
386
391
  if (!parsed.success) throw new KindError(this.name, "invalid variant payload", { details: { issues: parsed.error.issues } });
387
- if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
392
+ if (!(line.quantity > 0)) throw new KindError(this.name, `quantity must be > 0, got ${line.quantity}`);
388
393
  if (line.overrideUnitPrice && line.overrideUnitPrice.currency !== line.currency) throw new KindError(this.name, `override unit price currency ${line.overrideUnitPrice.currency} does not match cart currency ${line.currency}`);
389
394
  const product = await ctx.bridges.catalog.resolve(parsed.data.variantSku, ctx);
390
395
  if (!product) throw new KindError(this.name, `unknown variant SKU: ${parsed.data.variantSku}`);
@@ -422,6 +427,11 @@ const variantKind = {
422
427
  priced
423
428
  };
424
429
  },
430
+ /** The product's step (`0.001` kg for loose rice); the draft repository checks quantities against it. */
431
+ async quantityStepOf(line, ctx) {
432
+ const typed = line;
433
+ return (await ctx.bridges.catalog.resolve(typed.payload.variantSku, ctx))?.quantityStep;
434
+ },
425
435
  mergeKey(line) {
426
436
  const { productRef, variantSku } = line.payload ?? {};
427
437
  if (!productRef || !variantSku) return null;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "1.2.0",
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": "1.3.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.",
5
5
  "author": "Classytic",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -13,38 +13,47 @@
13
13
  },
14
14
  "exports": {
15
15
  ".": {
16
+ "@classytic/source": "./src/index.ts",
16
17
  "types": "./dist/index.d.mts",
17
18
  "default": "./dist/index.mjs"
18
19
  },
19
20
  "./domain": {
21
+ "@classytic/source": "./src/domain/index.ts",
20
22
  "types": "./dist/domain/index.d.mts",
21
23
  "default": "./dist/domain/index.mjs"
22
24
  },
23
25
  "./kinds": {
26
+ "@classytic/source": "./src/kinds/index.ts",
24
27
  "types": "./dist/kinds/index.d.mts",
25
28
  "default": "./dist/kinds/index.mjs"
26
29
  },
27
30
  "./ports": {
31
+ "@classytic/source": "./src/domain/ports/index.ts",
28
32
  "types": "./dist/domain/ports/index.d.mts",
29
33
  "default": "./dist/domain/ports/index.mjs"
30
34
  },
31
35
  "./errors": {
36
+ "@classytic/source": "./src/domain/errors/index.ts",
32
37
  "types": "./dist/domain/errors/index.d.mts",
33
38
  "default": "./dist/domain/errors/index.mjs"
34
39
  },
35
40
  "./events": {
41
+ "@classytic/source": "./src/domain/events/index.ts",
36
42
  "types": "./dist/domain/events/index.d.mts",
37
43
  "default": "./dist/domain/events/index.mjs"
38
44
  },
39
45
  "./saga": {
46
+ "@classytic/source": "./src/domain/saga/index.ts",
40
47
  "types": "./dist/domain/saga/index.d.mts",
41
48
  "default": "./dist/domain/saga/index.mjs"
42
49
  },
43
50
  "./engine": {
51
+ "@classytic/source": "./src/engine/index.ts",
44
52
  "types": "./dist/engine/index.d.mts",
45
53
  "default": "./dist/engine/index.mjs"
46
54
  },
47
55
  "./schemas": {
56
+ "@classytic/source": "./src/engine/cart-config.schema.ts",
48
57
  "types": "./dist/engine/cart-config.schema.d.mts",
49
58
  "default": "./dist/engine/cart-config.schema.mjs"
50
59
  }
@@ -83,27 +92,27 @@
83
92
  "release": "npm run push -- main && npm run release:tag && npm publish"
84
93
  },
85
94
  "peerDependencies": {
86
- "@classytic/mongokit": ">=3.36.0",
87
- "@classytic/primitives": ">=0.26.4",
88
- "@classytic/repo-core": ">=0.26.0",
89
- "mongoose": ">=9.4.1",
95
+ "@classytic/mongokit": ">=3.47.0",
96
+ "@classytic/primitives": ">=0.39.0",
97
+ "@classytic/repo-core": ">=0.39.0",
98
+ "mongoose": ">=9.13.1",
90
99
  "zod": ">=4.0.0"
91
100
  },
92
101
  "devDependencies": {
93
- "@biomejs/biome": "^2.4.13",
94
- "@classytic/dev-tools": "^0.2.0",
95
- "@classytic/mongokit": "^3.36.0",
96
- "@classytic/primitives": "^0.26.4",
97
- "@classytic/repo-core": "^0.26.0",
98
- "@types/node": "^25.5.0",
99
- "knip": "^6.7.0",
100
- "mongodb-memory-server": "^10.2.3",
101
- "mongoose": "^9.4.1",
102
- "publint": "^0.3.23",
103
- "tsdown": "^0.22.14",
104
- "typescript": "^5.7.0",
105
- "vitest": "^3.0.0",
106
- "zod": "^4.3.6"
102
+ "@biomejs/biome": "^2.5.15",
103
+ "@classytic/dev-tools": "^0.2.1",
104
+ "@classytic/mongokit": "^3.47.0",
105
+ "@classytic/primitives": "^0.39.0",
106
+ "@classytic/repo-core": "^0.39.0",
107
+ "@types/node": "^26.6.5",
108
+ "knip": "^6.41.0",
109
+ "mongodb-memory-server": "^11.4.0",
110
+ "mongoose": "^9.13.1",
111
+ "publint": "^0.3.25",
112
+ "tsdown": "^0.23.1",
113
+ "typescript": "^7.0.2",
114
+ "vitest": "^5.0.4",
115
+ "zod": "^4.6.7"
107
116
  },
108
117
  "keywords": [
109
118
  "cart",
@@ -1,24 +0,0 @@
1
- //#region src/domain/value-objects/line-total.ts
2
- /**
3
- * Multiply a unit price by a line quantity, guarding the safe-integer range.
4
- *
5
- * Minor-unit money must stay within `Number.MAX_SAFE_INTEGER` — past 2^53 the
6
- * multiplication silently loses precision, which is worse than failing loud.
7
- * Both the fresh `kind.price()` path and the incremental reprice path
8
- * (`rebuildSubtotals`) route their `unitPrice × quantity` through here, so a
9
- * huge quantity throws on the FIRST add, not only when a later reprice happens
10
- * to re-multiply it.
11
- *
12
- * Throws `RangeError` (same shape/message as the pre-existing reprice guard)
13
- * so both paths fail identically.
14
- */
15
- function lineTotal(unitPrice, quantity) {
16
- const amount = unitPrice.amount * quantity;
17
- if (!Number.isSafeInteger(amount)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${quantity} exceeds Number.MAX_SAFE_INTEGER`);
18
- return {
19
- amount,
20
- currency: unitPrice.currency
21
- };
22
- }
23
- //#endregion
24
- export { lineTotal as t };