@classytic/cart 0.2.1 → 1.0.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 (49) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +75 -21
  3. package/dist/{cart-event-catalog-BxDJhtTM.d.mts → cart-event-catalog-Cokx0iOw.d.mts} +1 -2
  4. package/dist/cart.error-xi5OT4Sz.mjs +52 -0
  5. package/dist/{clock.port-CNu2wgdA.d.mts → clock.port-DrSBrsit.d.mts} +9 -5
  6. package/dist/{create-cart-BeW0xAqD.mjs → define-cart-BPq2kb_V.mjs} +344 -224
  7. package/dist/domain/errors/index.d.mts +2 -2
  8. package/dist/domain/errors/index.mjs +6 -6
  9. package/dist/domain/events/index.d.mts +2 -2
  10. package/dist/domain/events/index.mjs +2 -2
  11. package/dist/domain/index.d.mts +14 -11
  12. package/dist/domain/index.mjs +12 -12
  13. package/dist/domain/ports/index.d.mts +3 -3
  14. package/dist/domain/ports/index.mjs +1 -1
  15. package/dist/domain/saga/index.d.mts +1 -1
  16. package/dist/domain/saga/index.mjs +1 -1
  17. package/dist/engine/cart-config.schema.d.mts +3 -4
  18. package/dist/engine/cart-config.schema.mjs +7 -7
  19. package/dist/engine/index.d.mts +3 -3
  20. package/dist/engine/index.mjs +3 -3
  21. package/dist/{errors-7Pd0yATM.mjs → errors-Dj8itvAh.mjs} +1 -4
  22. package/dist/{id.port-BhbFZJPm.mjs → id.port-DYAnXbfV.mjs} +1 -1
  23. package/dist/{index-BB0XzkXF.d.mts → index-BTSo-RLv.d.mts} +41 -4
  24. package/dist/index.d.mts +75 -17
  25. package/dist/index.mjs +180 -15
  26. package/dist/{internal-event-bus-DhQKi9KS.d.mts → internal-event-bus-Bu7Xj7j6.d.mts} +203 -170
  27. package/dist/{kind-registry-DG2iCCH1.d.mts → kind-registry-DFvNDb81.d.mts} +3 -5
  28. package/dist/{kind-registry-Bvrj3P1Q.mjs → kind-registry-DQYqRQZU.mjs} +1 -1
  29. package/dist/{kind.error-DIaJpdUb.mjs → kind.error-BoyoVjKx.mjs} +1 -1
  30. package/dist/kinds/index.d.mts +1 -1
  31. package/dist/kinds/index.mjs +1 -1
  32. package/dist/{line-kind-B1mU1iJp.d.mts → line-kind-BW2zLNSr.d.mts} +3 -4
  33. package/dist/line-total-6VJQMjGV.mjs +24 -0
  34. package/dist/{outbox-store-CBt9fSYh.d.mts → outbox-store-Br7MHuOz.d.mts} +3 -18
  35. package/dist/{outbox-store-CWW8ppxS.mjs → outbox-store-DLxCPOUN.mjs} +2 -30
  36. package/dist/{reservation.entity-DLMxgpLE.d.mts → reservation.entity-BEeYbRUY.d.mts} +4 -5
  37. package/dist/{state-transition.error-2fRLh3p0.mjs → state-transition.error-BssJiRoW.mjs} +1 -1
  38. package/dist/{state-transitions-D19wZe-w.d.mts → state-transitions-BQ2Nhxnb.d.mts} +14 -11
  39. package/dist/{state-transitions-Defw8gAt.mjs → state-transitions-wunwhjap.mjs} +1 -1
  40. package/dist/{unmanaged-session.error-C9Z1Yh9j.mjs → unmanaged-session.error-DIRT2PR3.mjs} +31 -2
  41. package/dist/{variant.kind-q-yv-vnQ.d.mts → variant.kind-CClf8MTF.d.mts} +3 -3
  42. package/dist/{variant.kind-BHiivO9B.mjs → variant.kind-NmWSslu-.mjs} +23 -32
  43. package/package.json +10 -9
  44. package/dist/cart.error-BwWy4RlY.mjs +0 -27
  45. package/dist/index-2Ag-54t8.d.mts +0 -1
  46. /package/dist/{cart-status.vo-CNJw4aaB.d.mts → cart-status.vo-BoVPaSXX.d.mts} +0 -0
  47. /package/dist/{domain-event-CIEORKF6.mjs → domain-event-DBFsiHNJ.mjs} +0 -0
  48. /package/dist/{id.port-DitjeoHg.d.mts → id.port-DzgWy8sy.d.mts} +0 -0
  49. /package/dist/{idempotency-key.vo-D0lJsvGn.mjs → idempotency-key.vo-BoRvSIxx.mjs} +0 -0
@@ -1,16 +1,17 @@
1
- import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-C9Z1Yh9j.mjs";
2
- import { t as KindError } from "./kind.error-DIaJpdUb.mjs";
3
- import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
4
- import { n as cryptoIdPort, r as systemClock } from "./id.port-BhbFZJPm.mjs";
5
- import { t as createKindRegistry } from "./kind-registry-Bvrj3P1Q.mjs";
6
- import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-Defw8gAt.mjs";
1
+ import { a as CurrencyMismatchError, i as NotFoundError, n as StaleQuoteError, o as ConcurrencyError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-DIRT2PR3.mjs";
2
+ import { t as KindError } from "./kind.error-BoyoVjKx.mjs";
3
+ import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.mjs";
4
+ import { n as cryptoIdPort, r as systemClock } from "./id.port-DYAnXbfV.mjs";
5
+ import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
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
8
  import { money } from "@classytic/primitives/money";
8
- import { matchEventPattern } from "@classytic/primitives/events";
9
- import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
10
- import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
9
+ import { Repository, customIdPlugin, defineModels, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
10
+ import { CURRENCY_PATTERN, currencyCode } from "@classytic/primitives/currency";
11
11
  import mongoose, { Schema } from "mongoose";
12
12
  import { resolveTenantConfig } from "@classytic/repo-core/tenant";
13
13
  import { createHash } from "node:crypto";
14
+ import { InProcessEventBus } from "@classytic/primitives/event-infra";
14
15
  //#region src/domain/ports/common.ts
15
16
  /**
16
17
  * Internal: key under which the post-commit event-publish queue is threaded
@@ -75,7 +76,11 @@ async function flushPending(eventTransport, events, logger) {
75
76
  }
76
77
  //#endregion
77
78
  //#region src/models/checkout.model.ts
78
- function createCheckoutModel(connection, opts = {}) {
79
+ /**
80
+ * Build the Checkout schema — pure, connection-free. Registration + collection
81
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
82
+ */
83
+ function buildCheckoutSchema() {
79
84
  const schema = new Schema({
80
85
  publicId: {
81
86
  type: String,
@@ -160,8 +165,7 @@ function createCheckoutModel(connection, opts = {}) {
160
165
  draftId: 1,
161
166
  state: 1
162
167
  });
163
- const collection = (opts.collectionPrefix ?? "") + "cart_checkouts";
164
- return connection.model("CartCheckout", schema, collection);
168
+ return schema;
165
169
  }
166
170
  //#endregion
167
171
  //#region src/models/draft.model.ts
@@ -270,7 +274,11 @@ const adjustmentSubSchema = new Schema({
270
274
  default: () => /* @__PURE__ */ new Date()
271
275
  }
272
276
  }, { _id: false });
273
- function createDraftModel(connection, opts = {}) {
277
+ /**
278
+ * Build the Draft schema — pure, connection-free. Registration + collection
279
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
280
+ */
281
+ function buildDraftSchema() {
274
282
  const schema = new Schema({
275
283
  publicId: {
276
284
  type: String,
@@ -348,12 +356,15 @@ function createDraftModel(connection, opts = {}) {
348
356
  expireAfterSeconds: 0,
349
357
  partialFilterExpression: { expiresAt: { $exists: true } }
350
358
  });
351
- const collection = (opts.collectionPrefix ?? "") + "cart_drafts";
352
- return connection.model("CartDraft", schema, collection);
359
+ return schema;
353
360
  }
354
361
  //#endregion
355
362
  //#region src/models/idempotency.model.ts
356
- function createIdempotencyModel(connection, opts = {}) {
363
+ /**
364
+ * Build the Idempotency schema — pure, connection-free. Registration + collection
365
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
366
+ */
367
+ function buildIdempotencySchema() {
357
368
  const schema = new Schema({
358
369
  cartRef: {
359
370
  type: String,
@@ -426,9 +437,8 @@ function createIdempotencyModel(connection, opts = {}) {
426
437
  actorRef: 1,
427
438
  idempotencyKey: 1
428
439
  }, { unique: true });
429
- schema.index({ createdAt: 1 }, { expireAfterSeconds: 1440 * 60 });
430
- const collection = (opts.collectionPrefix ?? "") + "cart_idempotency";
431
- return connection.model("CartIdempotency", schema, collection);
440
+ schema.index({ createdAt: 1 }, { expireAfterSeconds: 86400 });
441
+ return schema;
432
442
  }
433
443
  //#endregion
434
444
  //#region src/models/inject-tenant.ts
@@ -461,7 +471,6 @@ function injectTenantField(schema, tenant) {
461
471
  schema.add({ [tenant.tenantField]: {
462
472
  type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
463
473
  ...tenant.enabled && tenant.required ? { required: true } : {},
464
- index: true,
465
474
  ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
466
475
  } });
467
476
  if (!tenant.enabled || !isFieldStrategy) return;
@@ -473,10 +482,15 @@ function injectTenantField(schema, tenant) {
473
482
  for (const [key, val] of Object.entries(fields)) newFields[key] = val;
474
483
  indexEntry[0] = newFields;
475
484
  }
485
+ if (!(existingIndexes ?? []).some(([fields]) => Object.keys(fields)[0] === tenant.tenantField)) schema.index({ [tenant.tenantField]: 1 });
476
486
  }
477
487
  //#endregion
478
488
  //#region src/models/reservation.model.ts
479
- function createReservationModel(connection, opts = {}) {
489
+ /**
490
+ * Build the Reservation schema — pure, connection-free. Registration + collection
491
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
492
+ */
493
+ function buildReservationSchema() {
480
494
  const schema = new Schema({
481
495
  publicId: {
482
496
  type: String,
@@ -557,96 +571,86 @@ function createReservationModel(connection, opts = {}) {
557
571
  expiresAt: 1
558
572
  });
559
573
  schema.index({ checkoutId: 1 });
560
- const collection = (opts.collectionPrefix ?? "") + "cart_reservations";
561
- return connection.model("CartReservation", schema, collection);
574
+ return schema;
562
575
  }
563
576
  //#endregion
564
577
  //#region src/models/index.ts
565
- const CART_MODEL_NAMES = [
566
- "CartDraft",
567
- "CartCheckout",
568
- "CartReservation",
569
- "CartIdempotency"
570
- ];
571
- var CartModelCollisionError = class extends Error {
572
- constructor(name) {
573
- super(`[cart] Mongoose model "${name}" already exists on this connection. For hot-reload / test fixtures, pass \`forceRecreate: true\` to clobber the existing model. For two cart engines, use two Mongoose connections (\`mongoose.createConnection(...)\`) — each has its own model registry.`);
574
- this.name = "CartModelCollisionError";
575
- }
576
- };
577
578
  /**
578
- * Apply `autoIndex` schema option to a set of models.
579
+ * Cart model specification — the ONE authoritative place the cart model set is
580
+ * described.
579
581
  *
580
- * Mongoose 9 defers `Model.init()` until the first query, so setting
581
- * `schema.autoIndex` after `connection.model()` is safe.
582
+ * `defineCartModels(config)` returns a connection-free mongokit `ModelBlueprint`;
583
+ * `defineCart` binds it during engine construction. Collision handling, tenant
584
+ * injection, collection naming and auto-index policy live here once
585
+ * (PACKAGE_RULES §20/§21). A name collision surfaces as mongokit's typed
586
+ * `ModelCollisionError` — there is no cart-specific collision error.
582
587
  */
583
- function applyAutoIndex(models, autoIndex) {
584
- if (autoIndex === void 0) return;
585
- for (const [name, model] of Object.entries(models)) {
586
- const value = typeof autoIndex === "boolean" ? autoIndex : autoIndex[name] ?? void 0;
587
- if (value !== void 0) model.schema.set("autoIndex", value);
588
- }
588
+ /** Registered Mongoose model name for each cart model bag key. */
589
+ const MODEL_NAME = {
590
+ Draft: "CartDraft",
591
+ Checkout: "CartCheckout",
592
+ Reservation: "CartReservation",
593
+ Idempotency: "CartIdempotency"
594
+ };
595
+ /** Physical collection base name (before `collectionPrefix`) for each model. */
596
+ const COLLECTION = {
597
+ Draft: "cart_drafts",
598
+ Checkout: "cart_checkouts",
599
+ Reservation: "cart_reservations",
600
+ Idempotency: "cart_idempotency"
601
+ };
602
+ /** Pure schema builders — no connection, no registration. */
603
+ const SCHEMA_BUILDER = {
604
+ Draft: buildDraftSchema,
605
+ Checkout: buildCheckoutSchema,
606
+ Reservation: buildReservationSchema,
607
+ Idempotency: buildIdempotencySchema
608
+ };
609
+ function resolveAutoIndex(key, autoIndex) {
610
+ if (autoIndex === void 0) return void 0;
611
+ if (typeof autoIndex === "boolean") return autoIndex;
612
+ return autoIndex[key];
589
613
  }
590
- function createCartModels(connection, options = {}) {
591
- if (options.forceRecreate) {
592
- for (const name of CART_MODEL_NAMES) if (connection.models[name]) connection.deleteModel(name);
593
- } else for (const name of CART_MODEL_NAMES) if (connection.models[name]) throw new CartModelCollisionError(name);
594
- const tenant = resolveCartTenant(options);
595
- const modelOpts = options.collectionPrefix !== void 0 ? { collectionPrefix: options.collectionPrefix } : {};
596
- const models = {
597
- Draft: createDraftModel(connection, modelOpts),
598
- Checkout: createCheckoutModel(connection, modelOpts),
599
- Reservation: createReservationModel(connection, modelOpts),
600
- Idempotency: createIdempotencyModel(connection, modelOpts)
601
- };
602
- for (const model of Object.values(models)) injectTenantField(model.schema, tenant);
603
- applyAutoIndex(models, options.autoIndex);
604
- return models;
614
+ /**
615
+ * Describe the cart model set as a connection-free blueprint. Pure — builds no
616
+ * schema and registers nothing until `.bind(connection)`.
617
+ */
618
+ function defineCartModels(config = {}) {
619
+ const tenant = resolveCartTenant({
620
+ multiTenant: config.multiTenant,
621
+ tenantFieldType: config.tenantFieldType ?? "objectId"
622
+ });
623
+ const prefix = config.collectionPrefix ?? "";
624
+ return defineModels({
625
+ models: [
626
+ "Draft",
627
+ "Checkout",
628
+ "Reservation",
629
+ "Idempotency"
630
+ ].map((key) => ({
631
+ name: MODEL_NAME[key],
632
+ collection: `${prefix}${COLLECTION[key]}`,
633
+ schema: () => {
634
+ const schema = SCHEMA_BUILDER[key]();
635
+ injectTenantField(schema, tenant);
636
+ const autoIndex = resolveAutoIndex(key, config.autoIndex);
637
+ if (autoIndex !== void 0) schema.set("autoIndex", autoIndex);
638
+ return schema;
639
+ },
640
+ existing: config.forceRecreate ? {
641
+ mode: "replace",
642
+ environment: "test"
643
+ } : { mode: "throw" }
644
+ })),
645
+ assemble: (models) => Object.freeze({
646
+ Draft: models.get("CartDraft"),
647
+ Checkout: models.get("CartCheckout"),
648
+ Reservation: models.get("CartReservation"),
649
+ Idempotency: models.get("CartIdempotency")
650
+ })
651
+ });
605
652
  }
606
653
  //#endregion
607
- //#region src/engine/cart-event-publisher.ts
608
- var CartEventPublisher = class {
609
- events;
610
- outbox;
611
- clock;
612
- logger;
613
- constructor(deps) {
614
- this.events = deps.events;
615
- this.outbox = deps.outbox;
616
- this.clock = deps.clock;
617
- this.logger = deps.logger ?? console;
618
- }
619
- async emit(type, payload, ctx, options = {}) {
620
- const event = createCartEvent(type, {
621
- ...payload,
622
- emittedAt: this.clock.now().toISOString(),
623
- correlationId: ctx.correlationId,
624
- organizationId: ctx.organizationId,
625
- actorRef: ctx.actorRef
626
- }, {
627
- timestamp: this.clock.now(),
628
- resource: options.resource,
629
- resourceId: options.resourceId,
630
- userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
631
- organizationId: ctx.organizationId,
632
- correlationId: ctx.correlationId,
633
- aggregate: options.aggregate
634
- });
635
- const pending = ctx[PENDING_EVENTS];
636
- if (this.outbox) await this.outbox.save(event, { session: ctx.session });
637
- else if (ctx.session && !pending) throw new UnmanagedSessionError();
638
- if (pending) {
639
- pending.push(event);
640
- return;
641
- }
642
- if (!ctx.session) try {
643
- await this.events.publish(event);
644
- } catch (err) {
645
- this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
646
- }
647
- }
648
- };
649
- //#endregion
650
654
  //#region src/repositories/checkout.repository.ts
651
655
  /**
652
656
  * Default zombie window for open checkouts — matches the package's
@@ -1175,12 +1179,25 @@ async function runPricing(opts) {
1175
1179
  adjustments
1176
1180
  };
1177
1181
  }
1178
- function sumMoney(moneys, fallbackCurrency) {
1179
- if (moneys.length === 0) return money(0, fallbackCurrency);
1180
- return {
1181
- amount: moneys.reduce((sum, m) => sum + m.amount, 0),
1182
- currency: moneys[0].currency
1183
- };
1182
+ /**
1183
+ * Sum a list of minor-unit money into a single total.
1184
+ *
1185
+ * Every input MUST share `currency` — the pricing pipeline assumes a draft's
1186
+ * one currency, and a blind reduce that stamped the result with `moneys[0]`
1187
+ * would silently fold a divergent-currency line (e.g. an EUR override on a USD
1188
+ * draft) into the grand total and freeze the wrong number into checkout. We
1189
+ * assert instead of guess, throwing `CurrencyMismatchError` on any divergence.
1190
+ *
1191
+ * Exported (module-level, NOT via the package barrel) for direct unit testing
1192
+ * of the single-currency invariant.
1193
+ */
1194
+ function sumMoney(moneys, currency) {
1195
+ let amount = 0;
1196
+ for (const m of moneys) {
1197
+ if (m.currency !== currency) throw new CurrencyMismatchError(currency, m.currency, { helper: "sumMoney" });
1198
+ amount += m.amount;
1199
+ }
1200
+ return money(amount, currency);
1184
1201
  }
1185
1202
  /**
1186
1203
  * Can the prior priced entry be reused for this line?
@@ -1206,20 +1223,15 @@ function canReuse(line, prior) {
1206
1223
  */
1207
1224
  function rebuildSubtotals(prior, line, currency) {
1208
1225
  const unitPrice = prior.unitPrice;
1209
- const rawTotal = unitPrice.amount * line.quantity;
1210
- if (!Number.isSafeInteger(rawTotal)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${line.quantity} exceeds Number.MAX_SAFE_INTEGER`);
1211
- const lineTotal = {
1212
- amount: rawTotal,
1213
- currency
1214
- };
1226
+ const total = lineTotal(unitPrice, line.quantity);
1215
1227
  return {
1216
1228
  lineId: line.lineId,
1217
1229
  unitPrice,
1218
1230
  quantity: line.quantity,
1219
1231
  subtotals: {
1220
- prePromo: lineTotal,
1221
- postPromo: lineTotal,
1222
- postPromoPostTax: lineTotal
1232
+ prePromo: total,
1233
+ postPromo: total,
1234
+ postPromoPostTax: total
1223
1235
  },
1224
1236
  discountTotal: {
1225
1237
  amount: 0,
@@ -1798,6 +1810,49 @@ var IdempotencyRepository = class extends Repository {
1798
1810
  }
1799
1811
  };
1800
1812
  //#endregion
1813
+ //#region src/engine/cart-event-publisher.ts
1814
+ var CartEventPublisher = class {
1815
+ events;
1816
+ outbox;
1817
+ clock;
1818
+ logger;
1819
+ constructor(deps) {
1820
+ this.events = deps.events;
1821
+ this.outbox = deps.outbox;
1822
+ this.clock = deps.clock;
1823
+ this.logger = deps.logger ?? console;
1824
+ }
1825
+ async emit(type, payload, ctx, options = {}) {
1826
+ const event = createCartEvent(type, {
1827
+ ...payload,
1828
+ emittedAt: this.clock.now().toISOString(),
1829
+ correlationId: ctx.correlationId,
1830
+ organizationId: ctx.organizationId,
1831
+ actorRef: ctx.actorRef
1832
+ }, {
1833
+ timestamp: this.clock.now(),
1834
+ resource: options.resource,
1835
+ resourceId: options.resourceId,
1836
+ userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
1837
+ organizationId: ctx.organizationId,
1838
+ correlationId: ctx.correlationId,
1839
+ aggregate: options.aggregate
1840
+ });
1841
+ const pending = ctx[PENDING_EVENTS];
1842
+ if (this.outbox) await this.outbox.save(event, { session: ctx.session });
1843
+ else if (ctx.session && !pending) throw new UnmanagedSessionError();
1844
+ if (pending) {
1845
+ pending.push(event);
1846
+ return;
1847
+ }
1848
+ if (!ctx.session) try {
1849
+ await this.events.publish(event);
1850
+ } catch (err) {
1851
+ this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
1852
+ }
1853
+ }
1854
+ };
1855
+ //#endregion
1801
1856
  //#region src/repositories/reservation.repository.ts
1802
1857
  /**
1803
1858
  * ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
@@ -1807,9 +1862,6 @@ var IdempotencyRepository = class extends Repository {
1807
1862
  * sweeper drives the active release loop via `findExpiredHeld`.
1808
1863
  */
1809
1864
  var ReservationRepository = class extends Repository {
1810
- constructor(model, plugins) {
1811
- super(model, plugins);
1812
- }
1813
1865
  /** All reservations belonging to a checkout. */
1814
1866
  async findByCheckout(checkoutId, ctx) {
1815
1867
  return await this.findAll({ checkoutId }, this.readOptions(ctx));
@@ -1961,127 +2013,195 @@ function createCartRepositories(models, config) {
1961
2013
  }
1962
2014
  //#endregion
1963
2015
  //#region src/engine/internal-event-bus.ts
1964
- var InProcessCartEventBus = class {
1965
- name = "in-process-cart";
1966
- subs = [];
1967
- async publish(event) {
1968
- const matching = this.subs.filter((s) => matchEventPattern(s.pattern, event.type));
1969
- for (const sub of matching) try {
1970
- await sub.handler(event);
1971
- } catch {}
1972
- }
1973
- async publishMany(events) {
1974
- const results = /* @__PURE__ */ new Map();
1975
- for (const event of events) try {
1976
- await this.publish(event);
1977
- results.set(event.meta.id, null);
1978
- } catch (err) {
1979
- results.set(event.meta.id, err instanceof Error ? err : new Error(String(err)));
1980
- }
1981
- return results;
1982
- }
1983
- async subscribe(pattern, handler) {
1984
- const sub = {
1985
- pattern,
1986
- handler
1987
- };
1988
- this.subs.push(sub);
1989
- return () => {
1990
- this.subs = this.subs.filter((s) => s !== sub);
1991
- };
1992
- }
1993
- async close() {
1994
- this.subs = [];
2016
+ /**
2017
+ * InProcessCartEventBus — default transport for CartEngine when no external
2018
+ * transport is provided. Thin subclass of primitives' shared
2019
+ * `InProcessEventBus` (`@classytic/primitives/event-infra`, 0.13.0) —
2020
+ * structurally identical to Arc's `MemoryEventTransport`, so the two are
2021
+ * interchangeable.
2022
+ *
2023
+ * Cart dialect preserved: handler errors are swallowed silently
2024
+ * (`logger: null`) — event emission never propagates OR logs errors.
2025
+ *
2026
+ * Not durable — lost on process restart. For durability, use a
2027
+ * host-provided durable outbox plus a relay worker, or plug in Arc's
2028
+ * EventOutbox.
2029
+ */
2030
+ var InProcessCartEventBus = class extends InProcessEventBus {
2031
+ constructor() {
2032
+ super({
2033
+ name: "in-process-cart",
2034
+ logger: null
2035
+ });
1995
2036
  }
1996
2037
  };
1997
2038
  //#endregion
1998
- //#region src/engine/create-cart.ts
1999
- /** Runtime capabilities cart's atomic paths require at boot (full mode). */
2039
+ //#region src/engine/define-cart.ts
2040
+ /**
2041
+ * `defineCart` — the DESCRIBE/BIND blueprint for the cart engine
2042
+ * (STANDARDIZATION-PLAN §6, Phase 5). Splits construction into two phases:
2043
+ *
2044
+ * - **describe** (`defineCart(shape)`): pure. Builds the kind registry and
2045
+ * freezes the model names via mongokit's `defineModels()`. No connection,
2046
+ * no schema built, no I/O — safe at import / module-composition time.
2047
+ * - **bind** (`blueprint.bind(connection, runtime)`): compiles the schemas on
2048
+ * the supplied connection, registers the models, wires repositories +
2049
+ * transport, verifies capabilities, and returns the frozen `CartEngine`.
2050
+ *
2051
+ * The legitimate connectionless / domain-only use case (kinds + events + clock
2052
+ * WITHOUT persistence) is an EXPLICIT separate surface — `createCartDomain(shape)`
2053
+ * — not a "lite" engine returned by `bind`, and not connection duck-typing.
2054
+ *
2055
+ * This is the sole construction API — there is no `createCart` wrapper.
2056
+ */
2057
+ /** Runtime capabilities cart's atomic paths require at boot. */
2000
2058
  const REQUIRED_CAPABILITIES = ["upsert"];
2001
2059
  /**
2002
2060
  * Boot gate (PACKAGE_RULES "Runtime capabilities") — the idempotency store's
2003
- * insert-in-flight/lease pattern needs atomic upserts; fail loud at engine
2004
- * creation, not with a cryptic driver error on the first checkout.
2061
+ * insert-in-flight/lease pattern needs atomic upserts; fail loud at bind time,
2062
+ * not with a cryptic driver error on the first checkout.
2005
2063
  */
2006
2064
  function assertCartCapabilities(repositories) {
2007
2065
  const caps = repositories.draft.capabilities;
2008
- if (!caps) throw new Error("createCart: the wired repository backend declares no `capabilities` descriptor (repo-core 0.6 / mongokit 3.16+). Upgrade the kit.");
2066
+ if (!caps) throw new Error("defineCart.bind: the wired repository backend declares no `capabilities` descriptor (repo-core 0.6 / mongokit 3.16+). Upgrade the kit.");
2009
2067
  const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
2010
- if (missing.length > 0) throw new Error(`createCart: backend missing required capabilities: ${missing.join(", ")}. The idempotency lease pattern needs atomic upserts.`);
2068
+ if (missing.length > 0) throw new Error(`defineCart.bind: backend missing required capabilities: ${missing.join(", ")}. The idempotency lease pattern needs atomic upserts.`);
2069
+ }
2070
+ function requireKinds(shape) {
2071
+ if (!shape.kinds || shape.kinds.length === 0) throw new Error("defineCart: shape.kinds must contain at least one LineKind");
2011
2072
  }
2012
2073
  /**
2013
- * createCart() — build a cart engine.
2014
- *
2015
- * Repositories are the primary API. All domain logic (addItem, checkout,
2016
- * commit, cancel) lives directly on the repository classes. Multi-tenant
2017
- * scoping and `publicId` generation are handled by mongokit plugins wired
2018
- * inside `createCartRepositories`, so callers just pass the connection
2019
- * and bridges.
2074
+ * Describe the cart engine. Pure — registers no model, builds no schema,
2075
+ * performs no I/O.
2020
2076
  */
2021
- async function createCart(config) {
2022
- if (!config.connection) throw new Error("createCart: config.connection is required");
2023
- if (!config.kinds || config.kinds.length === 0) throw new Error("createCart: config.kinds must contain at least one LineKind");
2024
- if (!config.bridges) throw new Error("createCart: config.bridges is required");
2025
- if (!config.bridges.catalog) throw new Error("createCart: config.bridges.catalog is required");
2026
- const kinds = createKindRegistry(config.kinds);
2027
- const events = config.eventTransport ?? new InProcessCartEventBus();
2028
- const clock = config.clock ?? systemClock;
2029
- const id = config.id ?? cryptoIdPort;
2030
- const defaultCurrency = config.defaultCurrency ?? "USD";
2031
- const tenantFieldType = config.tenantFieldType ?? "objectId";
2032
- const isRealConnection = typeof config.connection.model === "function";
2033
- let models = {};
2034
- let repositories = {};
2035
- let mode = "lite";
2036
- const multiTenant = config.multiTenant ?? true;
2037
- if (isRealConnection) {
2038
- models = createCartModels(config.connection, {
2039
- tenantFieldType,
2040
- multiTenant,
2041
- autoIndex: config.autoIndex,
2042
- ...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
2043
- ...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
2044
- });
2045
- repositories = createCartRepositories(models, {
2046
- kinds,
2047
- bridges: config.bridges,
2048
- clock,
2049
- id,
2050
- defaultCurrency,
2051
- events,
2052
- outbox: config.outbox,
2053
- plugins: config.repositoryPlugins,
2054
- tenantFieldType,
2055
- multiTenant,
2056
- staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
2057
- });
2058
- assertCartCapabilities(repositories);
2059
- mode = "full";
2060
- }
2061
- const allowNonTransactional = config.allowNonTransactional ?? false;
2077
+ function defineCart(shape) {
2078
+ requireKinds(shape);
2079
+ const multiTenant = shape.multiTenant ?? true;
2080
+ const tenantFieldType = shape.tenantFieldType ?? "objectId";
2081
+ const defaultCurrency = currencyCode(shape.defaultCurrency ?? "USD");
2082
+ const modelBlueprint = defineCartModels({
2083
+ multiTenant,
2084
+ tenantFieldType,
2085
+ ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
2086
+ ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
2087
+ ...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {}
2088
+ });
2062
2089
  return {
2063
- config: Object.freeze({ ...config }),
2090
+ id: "cart",
2091
+ modelNames: modelBlueprint.modelNames,
2092
+ bind(connection, runtime) {
2093
+ if (!runtime || !runtime.bridges) throw new Error("defineCart.bind: runtime.bridges is required");
2094
+ if (!runtime.bridges.catalog) throw new Error("defineCart.bind: runtime.bridges.catalog is required");
2095
+ /**
2096
+ * VERIFY (boot gate) — an injected outbox MUST enlist `ctx.session`.
2097
+ *
2098
+ * Checked here with the other argument checks, BEFORE the model blueprint binds: a
2099
+ * cheaper error should report before a costlier one, and a bind refused here must
2100
+ * leave the connection's model registry untouched.
2101
+ *
2102
+ * `OutboxWriteOptions.session` is best-effort BY CONTRACT (see
2103
+ * `@classytic/primitives/outbox`), so a hand-rolled store satisfies `OutboxStore`
2104
+ * and then keeps the row when the transaction aborts. `CartEventPublisher.emit`
2105
+ * saves under `ctx.session` unconditionally so it cannot: a surviving
2106
+ * `cart.checkout.committed` is the one event a host is told to hook for order
2107
+ * creation and reservation commit, so a rolled-back checkout would create an order
2108
+ * and burn inventory holds for a basket that is still open. Nothing throws.
2109
+ *
2110
+ * Cart already refuses a bare host session with no outbox and no queue
2111
+ * (`UnmanagedSessionError`, per call). That guard cannot see this one: a store IS
2112
+ * present and `save()` resolves.
2113
+ */
2114
+ if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new Error("defineCart.bind: the configured OutboxStore does not declare `transactionalSave: true`, so it does not promise that `save()` enlists `ctx.session` (see @classytic/primitives/outbox — the option is best-effort by contract). Cart writes every event row inside the caller's transaction; a store that ignores the session emits checkout events for baskets that rolled back. Arc's `repositoryAsOutboxStore` declares it; the in-memory `MemoryOutboxStore` must not — pass no outbox instead.");
2115
+ const kinds = createKindRegistry(shape.kinds);
2116
+ const clock = runtime.clock ?? systemClock;
2117
+ const id = runtime.id ?? cryptoIdPort;
2118
+ const logger = runtime.logger ?? console;
2119
+ const staleOpenCheckoutMs = shape.checkout?.staleOpenCheckoutMs;
2120
+ const ownsBus = runtime.eventTransport === void 0;
2121
+ const events = runtime.eventTransport ?? new InProcessCartEventBus();
2122
+ const models = modelBlueprint.bind(connection);
2123
+ const repositories = createCartRepositories(models, {
2124
+ kinds,
2125
+ bridges: runtime.bridges,
2126
+ clock,
2127
+ id,
2128
+ defaultCurrency,
2129
+ events,
2130
+ ...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
2131
+ ...runtime.repositoryPlugins !== void 0 ? { plugins: runtime.repositoryPlugins } : {},
2132
+ tenantFieldType,
2133
+ multiTenant,
2134
+ ...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
2135
+ });
2136
+ assertCartCapabilities(repositories);
2137
+ const allowNonTransactional = runtime.allowNonTransactional ?? false;
2138
+ const resolved = {
2139
+ multiTenant,
2140
+ tenantFieldType,
2141
+ forceRecreate: shape.forceRecreate ?? false,
2142
+ defaultCurrency,
2143
+ allowNonTransactional,
2144
+ ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
2145
+ ...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
2146
+ };
2147
+ let closed = false;
2148
+ const close = async () => {
2149
+ if (closed) return;
2150
+ closed = true;
2151
+ if (ownsBus) await events.close?.();
2152
+ };
2153
+ const engine = {
2154
+ config: Object.freeze(resolved),
2155
+ kinds,
2156
+ events,
2157
+ clock,
2158
+ id,
2159
+ models,
2160
+ repositories,
2161
+ withTransaction(ctx, body) {
2162
+ return runUnit({
2163
+ connection,
2164
+ eventTransport: events,
2165
+ logger,
2166
+ allowNonTransactional
2167
+ }, ctx, body);
2168
+ },
2169
+ async syncIndexes() {
2170
+ await Promise.all(Object.values(models).map((m) => m.createIndexes()));
2171
+ },
2172
+ close
2173
+ };
2174
+ return Object.freeze(engine);
2175
+ }
2176
+ };
2177
+ }
2178
+ /**
2179
+ * `createCartDomain(shape, runtime?)` — the EXPLICIT connectionless domain-only
2180
+ * surface (STANDARDIZATION-PLAN §Phase 5). Builds the kind registry, event
2181
+ * transport, clock and id WITHOUT touching a connection, registering a model,
2182
+ * or wiring a repository. Use it to exercise the LineKind contract or emit
2183
+ * events without persistence. It is NOT a degraded engine — it deliberately
2184
+ * exposes no `models`/`repositories`/`withTransaction`.
2185
+ */
2186
+ function createCartDomain(shape, runtime = {}) {
2187
+ requireKinds(shape);
2188
+ const kinds = createKindRegistry(shape.kinds);
2189
+ const clock = runtime.clock ?? systemClock;
2190
+ const id = runtime.id ?? cryptoIdPort;
2191
+ const ownsBus = runtime.eventTransport === void 0;
2192
+ const events = runtime.eventTransport ?? new InProcessCartEventBus();
2193
+ let closed = false;
2194
+ return Object.freeze({
2064
2195
  kinds,
2065
2196
  events,
2066
2197
  clock,
2067
2198
  id,
2068
- models,
2069
- repositories,
2070
- mode,
2071
- withTransaction(ctx, body) {
2072
- if (mode !== "full") throw new Error("cart.withTransaction requires full mode (a real Mongoose connection)");
2073
- return runUnit({
2074
- connection: config.connection,
2075
- eventTransport: events,
2076
- logger: console,
2077
- allowNonTransactional
2078
- }, ctx, body);
2079
- },
2080
- async syncIndexes() {
2081
- await Promise.all(Object.values(models).map((m) => m.createIndexes()));
2082
- },
2083
- async destroy() {}
2084
- };
2199
+ async close() {
2200
+ if (closed) return;
2201
+ closed = true;
2202
+ if (ownsBus) await events.close?.();
2203
+ }
2204
+ });
2085
2205
  }
2086
2206
  //#endregion
2087
- export { IdempotencyRepository as a, CheckoutRepository as c, createReservationModel as d, createIdempotencyModel as f, PENDING_EVENTS as g, flushPending as h, ReservationRepository as i, DEFAULT_STALE_OPEN_CHECKOUT_MS as l, createCheckoutModel as m, InProcessCartEventBus as n, DraftRepository as o, createDraftModel as p, createCartRepositories as r, runPricing as s, createCart as t, createCartModels as u };
2207
+ export { PENDING_EVENTS as _, ReservationRepository as a, runPricing as c, defineCartModels as d, buildReservationSchema as f, flushPending as g, buildCheckoutSchema as h, createCartRepositories as i, CheckoutRepository as l, buildDraftSchema as m, defineCart as n, IdempotencyRepository as o, buildIdempotencySchema as p, InProcessCartEventBus as r, DraftRepository as s, createCartDomain as t, DEFAULT_STALE_OPEN_CHECKOUT_MS as u };