@classytic/cart 0.3.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +188 -147
- package/LICENSE +75 -21
- package/dist/{cart-event-catalog-BxDJhtTM.d.mts → cart-event-catalog-Cokx0iOw.d.mts} +1 -2
- package/dist/cart.error-xi5OT4Sz.mjs +52 -0
- package/dist/{clock.port-CNu2wgdA.d.mts → clock.port-DrSBrsit.d.mts} +9 -5
- package/dist/{create-cart-zgAh3UVt.mjs → define-cart-Cr9VMeVc.mjs} +362 -236
- package/dist/domain/errors/index.d.mts +2 -2
- package/dist/domain/errors/index.mjs +6 -6
- package/dist/domain/events/index.d.mts +2 -2
- package/dist/domain/events/index.mjs +2 -2
- package/dist/domain/index.d.mts +14 -11
- package/dist/domain/index.mjs +12 -12
- package/dist/domain/ports/index.d.mts +3 -3
- package/dist/domain/ports/index.mjs +1 -1
- package/dist/domain/saga/index.d.mts +1 -1
- package/dist/domain/saga/index.mjs +1 -1
- package/dist/engine/cart-config.schema.d.mts +3 -4
- package/dist/engine/cart-config.schema.mjs +7 -7
- package/dist/engine/index.d.mts +3 -3
- package/dist/engine/index.mjs +3 -3
- package/dist/{errors-BNPgUilS.mjs → errors-Dj8itvAh.mjs} +1 -1
- package/dist/{id.port-BhbFZJPm.mjs → id.port-DYAnXbfV.mjs} +1 -1
- package/dist/{index-wh5Q7UY1.d.mts → index-BTSo-RLv.d.mts} +41 -3
- package/dist/index.d.mts +88 -24
- package/dist/index.mjs +195 -14
- package/dist/{internal-event-bus-DFcwV79F.d.mts → internal-event-bus-BA-WrtE0.d.mts} +200 -179
- package/dist/{kind-registry-DG2iCCH1.d.mts → kind-registry-DFvNDb81.d.mts} +3 -5
- package/dist/{kind-registry-Bvrj3P1Q.mjs → kind-registry-DQYqRQZU.mjs} +1 -1
- package/dist/{kind.error-DIaJpdUb.mjs → kind.error-BoyoVjKx.mjs} +1 -1
- package/dist/kinds/index.d.mts +1 -1
- package/dist/kinds/index.mjs +1 -1
- package/dist/{line-kind-B1mU1iJp.d.mts → line-kind-BW2zLNSr.d.mts} +3 -4
- package/dist/line-total-6VJQMjGV.mjs +24 -0
- package/dist/{outbox-store-CBt9fSYh.d.mts → outbox-store-Br7MHuOz.d.mts} +3 -18
- package/dist/{outbox-store-CWW8ppxS.mjs → outbox-store-DLxCPOUN.mjs} +2 -30
- package/dist/{reservation.entity-DLMxgpLE.d.mts → reservation.entity-BEeYbRUY.d.mts} +4 -5
- package/dist/{state-transition.error-2fRLh3p0.mjs → state-transition.error-BssJiRoW.mjs} +1 -1
- package/dist/{state-transitions-D19wZe-w.d.mts → state-transitions-BQ2Nhxnb.d.mts} +14 -11
- package/dist/{state-transitions-Defw8gAt.mjs → state-transitions-wunwhjap.mjs} +1 -1
- package/dist/{unmanaged-session.error-C9Z1Yh9j.mjs → unmanaged-session.error-DIRT2PR3.mjs} +31 -2
- package/dist/{variant.kind-q-yv-vnQ.d.mts → variant.kind-CClf8MTF.d.mts} +3 -3
- package/dist/{variant.kind-BHiivO9B.mjs → variant.kind-NmWSslu-.mjs} +23 -32
- package/package.json +10 -9
- package/dist/cart.error-BwWy4RlY.mjs +0 -27
- package/dist/index-2Ag-54t8.d.mts +0 -1
- /package/dist/{cart-status.vo-CNJw4aaB.d.mts → cart-status.vo-BoVPaSXX.d.mts} +0 -0
- /package/dist/{domain-event-CIEORKF6.mjs → domain-event-DBFsiHNJ.mjs} +0 -0
- /package/dist/{id.port-DitjeoHg.d.mts → id.port-DzgWy8sy.d.mts} +0 -0
- /package/dist/{idempotency-key.vo-D0lJsvGn.mjs → idempotency-key.vo-BoRvSIxx.mjs} +0 -0
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { t as KindError } from "./kind.error-
|
|
3
|
-
import { n as CartEvents, t as createCartEvent } from "./domain-event-
|
|
4
|
-
import { n as cryptoIdPort, r as systemClock } from "./id.port-
|
|
5
|
-
import { t as createKindRegistry } from "./kind-registry-
|
|
6
|
-
import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-
|
|
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 {
|
|
9
|
-
import {
|
|
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
|
-
import { resolveTenantConfig } from "@classytic/repo-core/tenant";
|
|
12
|
+
import { assertNoLegacyTenantKeys, 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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
352
|
-
return connection.model("CartDraft", schema, collection);
|
|
359
|
+
return schema;
|
|
353
360
|
}
|
|
354
361
|
//#endregion
|
|
355
362
|
//#region src/models/idempotency.model.ts
|
|
356
|
-
|
|
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:
|
|
430
|
-
|
|
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
|
|
@@ -440,15 +450,9 @@ function createIdempotencyModel(connection, opts = {}) {
|
|
|
440
450
|
* own without a mongoose dependency.
|
|
441
451
|
*/
|
|
442
452
|
function resolveCartTenant(input = {}) {
|
|
443
|
-
|
|
444
|
-
if ("
|
|
445
|
-
|
|
446
|
-
return resolveTenantConfig({
|
|
447
|
-
enabled: legacy.multiTenant !== false,
|
|
448
|
-
fieldType: legacy.tenantFieldType ?? "objectId"
|
|
449
|
-
});
|
|
450
|
-
}
|
|
451
|
-
return resolveTenantConfig(input);
|
|
453
|
+
const resolved = resolveTenantConfig(input);
|
|
454
|
+
if (resolved.strategy === "custom") throw new Error("[cart] tenant.strategy 'custom' is unsupported: cart repositories require one concrete tenant field");
|
|
455
|
+
return resolved;
|
|
452
456
|
}
|
|
453
457
|
/**
|
|
454
458
|
* Inject the tenant field into a Mongoose schema, and (when `enabled` +
|
|
@@ -476,7 +480,11 @@ function injectTenantField(schema, tenant) {
|
|
|
476
480
|
}
|
|
477
481
|
//#endregion
|
|
478
482
|
//#region src/models/reservation.model.ts
|
|
479
|
-
|
|
483
|
+
/**
|
|
484
|
+
* Build the Reservation schema — pure, connection-free. Registration + collection
|
|
485
|
+
* naming + tenant injection are performed by `defineCartModels` at bind time.
|
|
486
|
+
*/
|
|
487
|
+
function buildReservationSchema() {
|
|
480
488
|
const schema = new Schema({
|
|
481
489
|
publicId: {
|
|
482
490
|
type: String,
|
|
@@ -557,96 +565,83 @@ function createReservationModel(connection, opts = {}) {
|
|
|
557
565
|
expiresAt: 1
|
|
558
566
|
});
|
|
559
567
|
schema.index({ checkoutId: 1 });
|
|
560
|
-
|
|
561
|
-
return connection.model("CartReservation", schema, collection);
|
|
568
|
+
return schema;
|
|
562
569
|
}
|
|
563
570
|
//#endregion
|
|
564
571
|
//#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
572
|
/**
|
|
578
|
-
*
|
|
573
|
+
* Cart model specification — the ONE authoritative place the cart model set is
|
|
574
|
+
* described.
|
|
579
575
|
*
|
|
580
|
-
*
|
|
581
|
-
* `
|
|
576
|
+
* `defineCartModels(config)` returns a connection-free mongokit `ModelBlueprint`;
|
|
577
|
+
* `defineCart` binds it during engine construction. Collision handling, tenant
|
|
578
|
+
* injection, collection naming and auto-index policy live here once
|
|
579
|
+
* (PACKAGE_RULES §20/§21). A name collision surfaces as mongokit's typed
|
|
580
|
+
* `ModelCollisionError` — there is no cart-specific collision error.
|
|
582
581
|
*/
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
582
|
+
/** Registered Mongoose model name for each cart model bag key. */
|
|
583
|
+
const MODEL_NAME = {
|
|
584
|
+
Draft: "CartDraft",
|
|
585
|
+
Checkout: "CartCheckout",
|
|
586
|
+
Reservation: "CartReservation",
|
|
587
|
+
Idempotency: "CartIdempotency"
|
|
588
|
+
};
|
|
589
|
+
/** Physical collection base name (before `collectionPrefix`) for each model. */
|
|
590
|
+
const COLLECTION = {
|
|
591
|
+
Draft: "cart_drafts",
|
|
592
|
+
Checkout: "cart_checkouts",
|
|
593
|
+
Reservation: "cart_reservations",
|
|
594
|
+
Idempotency: "cart_idempotency"
|
|
595
|
+
};
|
|
596
|
+
/** Pure schema builders — no connection, no registration. */
|
|
597
|
+
const SCHEMA_BUILDER = {
|
|
598
|
+
Draft: buildDraftSchema,
|
|
599
|
+
Checkout: buildCheckoutSchema,
|
|
600
|
+
Reservation: buildReservationSchema,
|
|
601
|
+
Idempotency: buildIdempotencySchema
|
|
602
|
+
};
|
|
603
|
+
function resolveAutoIndex(key, autoIndex) {
|
|
604
|
+
if (autoIndex === void 0) return void 0;
|
|
605
|
+
if (typeof autoIndex === "boolean") return autoIndex;
|
|
606
|
+
return autoIndex[key];
|
|
589
607
|
}
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
const
|
|
596
|
-
const
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
608
|
+
/**
|
|
609
|
+
* Describe the cart model set as a connection-free blueprint. Pure — builds no
|
|
610
|
+
* schema and registers nothing until `.bind(connection)`.
|
|
611
|
+
*/
|
|
612
|
+
function defineCartModels(config = {}) {
|
|
613
|
+
const tenant = config.tenant ?? resolveCartTenant(true);
|
|
614
|
+
const prefix = config.collectionPrefix ?? "";
|
|
615
|
+
return defineModels({
|
|
616
|
+
models: [
|
|
617
|
+
"Draft",
|
|
618
|
+
"Checkout",
|
|
619
|
+
"Reservation",
|
|
620
|
+
"Idempotency"
|
|
621
|
+
].map((key) => ({
|
|
622
|
+
name: MODEL_NAME[key],
|
|
623
|
+
collection: `${prefix}${COLLECTION[key]}`,
|
|
624
|
+
schema: () => {
|
|
625
|
+
const schema = SCHEMA_BUILDER[key]();
|
|
626
|
+
injectTenantField(schema, tenant);
|
|
627
|
+
const autoIndex = resolveAutoIndex(key, config.autoIndex);
|
|
628
|
+
if (autoIndex !== void 0) schema.set("autoIndex", autoIndex);
|
|
629
|
+
return schema;
|
|
630
|
+
},
|
|
631
|
+
existing: config.forceRecreate ? {
|
|
632
|
+
mode: "replace",
|
|
633
|
+
environment: "test"
|
|
634
|
+
} : { mode: "throw" }
|
|
635
|
+
})),
|
|
636
|
+
assemble: (models) => Object.freeze({
|
|
637
|
+
Draft: models.get("CartDraft"),
|
|
638
|
+
Checkout: models.get("CartCheckout"),
|
|
639
|
+
Reservation: models.get("CartReservation"),
|
|
640
|
+
Idempotency: models.get("CartIdempotency")
|
|
641
|
+
})
|
|
642
|
+
});
|
|
605
643
|
}
|
|
606
644
|
//#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
645
|
//#region src/repositories/checkout.repository.ts
|
|
651
646
|
/**
|
|
652
647
|
* Default zombie window for open checkouts — matches the package's
|
|
@@ -1175,12 +1170,25 @@ async function runPricing(opts) {
|
|
|
1175
1170
|
adjustments
|
|
1176
1171
|
};
|
|
1177
1172
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1173
|
+
/**
|
|
1174
|
+
* Sum a list of minor-unit money into a single total.
|
|
1175
|
+
*
|
|
1176
|
+
* Every input MUST share `currency` — the pricing pipeline assumes a draft's
|
|
1177
|
+
* one currency, and a blind reduce that stamped the result with `moneys[0]`
|
|
1178
|
+
* would silently fold a divergent-currency line (e.g. an EUR override on a USD
|
|
1179
|
+
* draft) into the grand total and freeze the wrong number into checkout. We
|
|
1180
|
+
* assert instead of guess, throwing `CurrencyMismatchError` on any divergence.
|
|
1181
|
+
*
|
|
1182
|
+
* Exported (module-level, NOT via the package barrel) for direct unit testing
|
|
1183
|
+
* of the single-currency invariant.
|
|
1184
|
+
*/
|
|
1185
|
+
function sumMoney(moneys, currency) {
|
|
1186
|
+
let amount = 0;
|
|
1187
|
+
for (const m of moneys) {
|
|
1188
|
+
if (m.currency !== currency) throw new CurrencyMismatchError(currency, m.currency, { helper: "sumMoney" });
|
|
1189
|
+
amount += m.amount;
|
|
1190
|
+
}
|
|
1191
|
+
return money(amount, currency);
|
|
1184
1192
|
}
|
|
1185
1193
|
/**
|
|
1186
1194
|
* Can the prior priced entry be reused for this line?
|
|
@@ -1206,20 +1214,15 @@ function canReuse(line, prior) {
|
|
|
1206
1214
|
*/
|
|
1207
1215
|
function rebuildSubtotals(prior, line, currency) {
|
|
1208
1216
|
const unitPrice = prior.unitPrice;
|
|
1209
|
-
const
|
|
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
|
-
};
|
|
1217
|
+
const total = lineTotal(unitPrice, line.quantity);
|
|
1215
1218
|
return {
|
|
1216
1219
|
lineId: line.lineId,
|
|
1217
1220
|
unitPrice,
|
|
1218
1221
|
quantity: line.quantity,
|
|
1219
1222
|
subtotals: {
|
|
1220
|
-
prePromo:
|
|
1221
|
-
postPromo:
|
|
1222
|
-
postPromoPostTax:
|
|
1223
|
+
prePromo: total,
|
|
1224
|
+
postPromo: total,
|
|
1225
|
+
postPromoPostTax: total
|
|
1223
1226
|
},
|
|
1224
1227
|
discountTotal: {
|
|
1225
1228
|
amount: 0,
|
|
@@ -1798,6 +1801,49 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1798
1801
|
}
|
|
1799
1802
|
};
|
|
1800
1803
|
//#endregion
|
|
1804
|
+
//#region src/engine/cart-event-publisher.ts
|
|
1805
|
+
var CartEventPublisher = class {
|
|
1806
|
+
events;
|
|
1807
|
+
outbox;
|
|
1808
|
+
clock;
|
|
1809
|
+
logger;
|
|
1810
|
+
constructor(deps) {
|
|
1811
|
+
this.events = deps.events;
|
|
1812
|
+
this.outbox = deps.outbox;
|
|
1813
|
+
this.clock = deps.clock;
|
|
1814
|
+
this.logger = deps.logger ?? console;
|
|
1815
|
+
}
|
|
1816
|
+
async emit(type, payload, ctx, options = {}) {
|
|
1817
|
+
const event = createCartEvent(type, {
|
|
1818
|
+
...payload,
|
|
1819
|
+
emittedAt: this.clock.now().toISOString(),
|
|
1820
|
+
correlationId: ctx.correlationId,
|
|
1821
|
+
organizationId: ctx.organizationId,
|
|
1822
|
+
actorRef: ctx.actorRef
|
|
1823
|
+
}, {
|
|
1824
|
+
timestamp: this.clock.now(),
|
|
1825
|
+
resource: options.resource,
|
|
1826
|
+
resourceId: options.resourceId,
|
|
1827
|
+
userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
|
|
1828
|
+
organizationId: ctx.organizationId,
|
|
1829
|
+
correlationId: ctx.correlationId,
|
|
1830
|
+
aggregate: options.aggregate
|
|
1831
|
+
});
|
|
1832
|
+
const pending = ctx[PENDING_EVENTS];
|
|
1833
|
+
if (this.outbox) await this.outbox.save(event, { session: ctx.session });
|
|
1834
|
+
else if (ctx.session && !pending) throw new UnmanagedSessionError();
|
|
1835
|
+
if (pending) {
|
|
1836
|
+
pending.push(event);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
if (!ctx.session) try {
|
|
1840
|
+
await this.events.publish(event);
|
|
1841
|
+
} catch (err) {
|
|
1842
|
+
this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
//#endregion
|
|
1801
1847
|
//#region src/repositories/reservation.repository.ts
|
|
1802
1848
|
/**
|
|
1803
1849
|
* ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
|
|
@@ -1886,23 +1932,23 @@ function isNotFound(err) {
|
|
|
1886
1932
|
}
|
|
1887
1933
|
//#endregion
|
|
1888
1934
|
//#region src/repositories/index.ts
|
|
1889
|
-
function tenantPlugin(
|
|
1935
|
+
function tenantPlugin(tenant) {
|
|
1890
1936
|
return multiTenantPlugin({
|
|
1891
|
-
tenantField:
|
|
1892
|
-
contextKey:
|
|
1937
|
+
tenantField: tenant.tenantField,
|
|
1938
|
+
contextKey: tenant.contextKey,
|
|
1893
1939
|
required: false,
|
|
1894
1940
|
skipWhen: (ctx) => ctx.skipTenant === true,
|
|
1895
|
-
fieldType
|
|
1941
|
+
fieldType: tenant.fieldType
|
|
1896
1942
|
});
|
|
1897
1943
|
}
|
|
1898
1944
|
function createCartRepositories(models, config) {
|
|
1899
|
-
const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {},
|
|
1945
|
+
const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenant, staleOpenCheckoutMs } = config;
|
|
1900
1946
|
const eventPublisher = new CartEventPublisher({
|
|
1901
1947
|
events,
|
|
1902
1948
|
outbox,
|
|
1903
1949
|
clock
|
|
1904
1950
|
});
|
|
1905
|
-
const tenantPlugins =
|
|
1951
|
+
const tenantPlugins = tenant.enabled ? [tenantPlugin(tenant)] : [];
|
|
1906
1952
|
const draft = new DraftRepository(models.Draft, [
|
|
1907
1953
|
...tenantPlugins,
|
|
1908
1954
|
customIdPlugin({
|
|
@@ -1958,127 +2004,207 @@ function createCartRepositories(models, config) {
|
|
|
1958
2004
|
}
|
|
1959
2005
|
//#endregion
|
|
1960
2006
|
//#region src/engine/internal-event-bus.ts
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
const sub = {
|
|
1982
|
-
pattern,
|
|
1983
|
-
handler
|
|
1984
|
-
};
|
|
1985
|
-
this.subs.push(sub);
|
|
1986
|
-
return () => {
|
|
1987
|
-
this.subs = this.subs.filter((s) => s !== sub);
|
|
1988
|
-
};
|
|
1989
|
-
}
|
|
1990
|
-
async close() {
|
|
1991
|
-
this.subs = [];
|
|
2007
|
+
/**
|
|
2008
|
+
* InProcessCartEventBus — default transport for CartEngine when no external
|
|
2009
|
+
* transport is provided. Thin subclass of primitives' shared
|
|
2010
|
+
* `InProcessEventBus` (`@classytic/primitives/event-infra`, 0.13.0) —
|
|
2011
|
+
* structurally identical to Arc's `MemoryEventTransport`, so the two are
|
|
2012
|
+
* interchangeable.
|
|
2013
|
+
*
|
|
2014
|
+
* Cart dialect preserved: handler errors are swallowed silently
|
|
2015
|
+
* (`logger: null`) — event emission never propagates OR logs errors.
|
|
2016
|
+
*
|
|
2017
|
+
* Not durable — lost on process restart. For durability, use a
|
|
2018
|
+
* host-provided durable outbox plus a relay worker, or plug in Arc's
|
|
2019
|
+
* EventOutbox.
|
|
2020
|
+
*/
|
|
2021
|
+
var InProcessCartEventBus = class extends InProcessEventBus {
|
|
2022
|
+
constructor() {
|
|
2023
|
+
super({
|
|
2024
|
+
name: "in-process-cart",
|
|
2025
|
+
logger: null
|
|
2026
|
+
});
|
|
1992
2027
|
}
|
|
1993
2028
|
};
|
|
1994
2029
|
//#endregion
|
|
1995
|
-
//#region src/engine/
|
|
1996
|
-
/**
|
|
2030
|
+
//#region src/engine/define-cart.ts
|
|
2031
|
+
/**
|
|
2032
|
+
* `defineCart` — the DESCRIBE/BIND blueprint for the cart engine
|
|
2033
|
+
* (STANDARDIZATION-PLAN §6, Phase 5). Splits construction into two phases:
|
|
2034
|
+
*
|
|
2035
|
+
* - **describe** (`defineCart(shape)`): pure. Builds the kind registry and
|
|
2036
|
+
* freezes the model names via mongokit's `defineModels()`. No connection,
|
|
2037
|
+
* no schema built, no I/O — safe at import / module-composition time.
|
|
2038
|
+
* - **bind** (`blueprint.bind(connection, runtime)`): compiles the schemas on
|
|
2039
|
+
* the supplied connection, registers the models, wires repositories +
|
|
2040
|
+
* transport, verifies capabilities, and returns the frozen `CartEngine`.
|
|
2041
|
+
*
|
|
2042
|
+
* The legitimate connectionless / domain-only use case (kinds + events + clock
|
|
2043
|
+
* WITHOUT persistence) is an EXPLICIT separate surface — `createCartDomain(shape)`
|
|
2044
|
+
* — not a "lite" engine returned by `bind`, and not connection duck-typing.
|
|
2045
|
+
*
|
|
2046
|
+
* This is the sole construction API — there is no `createCart` wrapper.
|
|
2047
|
+
*/
|
|
2048
|
+
/** Runtime capabilities cart's atomic paths require at boot. */
|
|
1997
2049
|
const REQUIRED_CAPABILITIES = ["upsert"];
|
|
1998
2050
|
/**
|
|
1999
2051
|
* Boot gate (PACKAGE_RULES "Runtime capabilities") — the idempotency store's
|
|
2000
|
-
* insert-in-flight/lease pattern needs atomic upserts; fail loud at
|
|
2001
|
-
*
|
|
2052
|
+
* insert-in-flight/lease pattern needs atomic upserts; fail loud at bind time,
|
|
2053
|
+
* not with a cryptic driver error on the first checkout.
|
|
2002
2054
|
*/
|
|
2003
2055
|
function assertCartCapabilities(repositories) {
|
|
2004
2056
|
const caps = repositories.draft.capabilities;
|
|
2005
|
-
if (!caps) throw new Error("
|
|
2057
|
+
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.");
|
|
2006
2058
|
const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
|
|
2007
|
-
if (missing.length > 0) throw new Error(`
|
|
2059
|
+
if (missing.length > 0) throw new Error(`defineCart.bind: backend missing required capabilities: ${missing.join(", ")}. The idempotency lease pattern needs atomic upserts.`);
|
|
2060
|
+
}
|
|
2061
|
+
function requireKinds(shape) {
|
|
2062
|
+
if (!shape.kinds || shape.kinds.length === 0) throw new Error("defineCart: shape.kinds must contain at least one LineKind");
|
|
2008
2063
|
}
|
|
2009
2064
|
/**
|
|
2010
|
-
*
|
|
2011
|
-
*
|
|
2012
|
-
* Repositories are the primary API. All domain logic (addItem, checkout,
|
|
2013
|
-
* commit, cancel) lives directly on the repository classes. Multi-tenant
|
|
2014
|
-
* scoping and `publicId` generation are handled by mongokit plugins wired
|
|
2015
|
-
* inside `createCartRepositories`, so callers just pass the connection
|
|
2016
|
-
* and bridges.
|
|
2065
|
+
* Describe the cart engine. Pure — registers no model, builds no schema,
|
|
2066
|
+
* performs no I/O.
|
|
2017
2067
|
*/
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
}
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
bridges: config.bridges,
|
|
2045
|
-
clock,
|
|
2046
|
-
id,
|
|
2047
|
-
defaultCurrency,
|
|
2048
|
-
events,
|
|
2049
|
-
outbox: config.outbox,
|
|
2050
|
-
plugins: config.repositoryPlugins,
|
|
2051
|
-
tenantFieldType,
|
|
2052
|
-
multiTenant,
|
|
2053
|
-
staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
|
|
2054
|
-
});
|
|
2055
|
-
assertCartCapabilities(repositories);
|
|
2056
|
-
mode = "full";
|
|
2057
|
-
}
|
|
2058
|
-
const allowNonTransactional = config.allowNonTransactional ?? false;
|
|
2068
|
+
function defineCart(shape) {
|
|
2069
|
+
/**
|
|
2070
|
+
* The pre-consolidation tenant keys are REFUSED, never absorbed.
|
|
2071
|
+
*
|
|
2072
|
+
* This entry reads `shape.tenant`, so a leftover `multiTenant` is invisible and
|
|
2073
|
+
* the `?? true` default applies repo-core's defaults instead. Both outcomes
|
|
2074
|
+
* return plausible data:
|
|
2075
|
+
* - `multiTenant: false` -> tenancy ON, and the host loses its company-wide reads;
|
|
2076
|
+
* - `multiTenant: { tenantField: 'business' }` -> scoping on `organizationId`,
|
|
2077
|
+
* a field those documents do not carry.
|
|
2078
|
+
*
|
|
2079
|
+
* tsc cannot cover this: excess-property checking does not fire for a typed
|
|
2080
|
+
* variable, a spread, or a shape handed over from a dependency's dist — which is
|
|
2081
|
+
* how every real host composes one. Hence a describe-time check, shared from
|
|
2082
|
+
* repo-core so the nine kernels making this same rename cannot each forget it.
|
|
2083
|
+
*/
|
|
2084
|
+
assertNoLegacyTenantKeys(shape, "defineCart", [["tenantFieldType", "tenant.fieldType"]]);
|
|
2085
|
+
requireKinds(shape);
|
|
2086
|
+
const tenant = resolveCartTenant(shape.tenant ?? true);
|
|
2087
|
+
const defaultCurrency = currencyCode(shape.defaultCurrency ?? "USD");
|
|
2088
|
+
const modelBlueprint = defineCartModels({
|
|
2089
|
+
tenant,
|
|
2090
|
+
...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
|
|
2091
|
+
...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
|
|
2092
|
+
...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {}
|
|
2093
|
+
});
|
|
2059
2094
|
return {
|
|
2060
|
-
|
|
2095
|
+
id: "cart",
|
|
2096
|
+
modelNames: modelBlueprint.modelNames,
|
|
2097
|
+
bind(connection, runtime) {
|
|
2098
|
+
if (!runtime || !runtime.bridges) throw new Error("defineCart.bind: runtime.bridges is required");
|
|
2099
|
+
if (!runtime.bridges.catalog) throw new Error("defineCart.bind: runtime.bridges.catalog is required");
|
|
2100
|
+
/**
|
|
2101
|
+
* VERIFY (boot gate) — an injected outbox MUST enlist `ctx.session`.
|
|
2102
|
+
*
|
|
2103
|
+
* Checked here with the other argument checks, BEFORE the model blueprint binds: a
|
|
2104
|
+
* cheaper error should report before a costlier one, and a bind refused here must
|
|
2105
|
+
* leave the connection's model registry untouched.
|
|
2106
|
+
*
|
|
2107
|
+
* `OutboxWriteOptions.session` is best-effort BY CONTRACT (see
|
|
2108
|
+
* `@classytic/primitives/outbox`), so a hand-rolled store satisfies `OutboxStore`
|
|
2109
|
+
* and then keeps the row when the transaction aborts. `CartEventPublisher.emit`
|
|
2110
|
+
* saves under `ctx.session` unconditionally so it cannot: a surviving
|
|
2111
|
+
* `cart.checkout.committed` is the one event a host is told to hook for order
|
|
2112
|
+
* creation and reservation commit, so a rolled-back checkout would create an order
|
|
2113
|
+
* and burn inventory holds for a basket that is still open. Nothing throws.
|
|
2114
|
+
*
|
|
2115
|
+
* Cart already refuses a bare host session with no outbox and no queue
|
|
2116
|
+
* (`UnmanagedSessionError`, per call). That guard cannot see this one: a store IS
|
|
2117
|
+
* present and `save()` resolves.
|
|
2118
|
+
*/
|
|
2119
|
+
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.");
|
|
2120
|
+
const kinds = createKindRegistry(shape.kinds);
|
|
2121
|
+
const clock = runtime.clock ?? systemClock;
|
|
2122
|
+
const id = runtime.id ?? cryptoIdPort;
|
|
2123
|
+
const logger = runtime.logger ?? console;
|
|
2124
|
+
const staleOpenCheckoutMs = shape.checkout?.staleOpenCheckoutMs;
|
|
2125
|
+
const ownsBus = runtime.eventTransport === void 0;
|
|
2126
|
+
const events = runtime.eventTransport ?? new InProcessCartEventBus();
|
|
2127
|
+
const models = modelBlueprint.bind(connection);
|
|
2128
|
+
const repositories = createCartRepositories(models, {
|
|
2129
|
+
kinds,
|
|
2130
|
+
bridges: runtime.bridges,
|
|
2131
|
+
clock,
|
|
2132
|
+
id,
|
|
2133
|
+
defaultCurrency,
|
|
2134
|
+
events,
|
|
2135
|
+
...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
|
|
2136
|
+
...runtime.repositoryPlugins !== void 0 ? { plugins: runtime.repositoryPlugins } : {},
|
|
2137
|
+
tenant,
|
|
2138
|
+
...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
|
|
2139
|
+
});
|
|
2140
|
+
assertCartCapabilities(repositories);
|
|
2141
|
+
const allowNonTransactional = runtime.allowNonTransactional ?? false;
|
|
2142
|
+
const resolved = {
|
|
2143
|
+
tenant,
|
|
2144
|
+
forceRecreate: shape.forceRecreate ?? false,
|
|
2145
|
+
defaultCurrency,
|
|
2146
|
+
allowNonTransactional,
|
|
2147
|
+
...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
|
|
2148
|
+
...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
|
|
2149
|
+
};
|
|
2150
|
+
let closed = false;
|
|
2151
|
+
const close = async () => {
|
|
2152
|
+
if (closed) return;
|
|
2153
|
+
closed = true;
|
|
2154
|
+
if (ownsBus) await events.close?.();
|
|
2155
|
+
};
|
|
2156
|
+
const engine = {
|
|
2157
|
+
config: Object.freeze(resolved),
|
|
2158
|
+
kinds,
|
|
2159
|
+
events,
|
|
2160
|
+
clock,
|
|
2161
|
+
id,
|
|
2162
|
+
models,
|
|
2163
|
+
repositories,
|
|
2164
|
+
withTransaction(ctx, body) {
|
|
2165
|
+
return runUnit({
|
|
2166
|
+
connection,
|
|
2167
|
+
eventTransport: events,
|
|
2168
|
+
logger,
|
|
2169
|
+
allowNonTransactional
|
|
2170
|
+
}, ctx, body);
|
|
2171
|
+
},
|
|
2172
|
+
async syncIndexes() {
|
|
2173
|
+
await Promise.all(Object.values(models).map((m) => m.createIndexes()));
|
|
2174
|
+
},
|
|
2175
|
+
close
|
|
2176
|
+
};
|
|
2177
|
+
return Object.freeze(engine);
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* `createCartDomain(shape, runtime?)` — the EXPLICIT connectionless domain-only
|
|
2183
|
+
* surface (STANDARDIZATION-PLAN §Phase 5). Builds the kind registry, event
|
|
2184
|
+
* transport, clock and id WITHOUT touching a connection, registering a model,
|
|
2185
|
+
* or wiring a repository. Use it to exercise the LineKind contract or emit
|
|
2186
|
+
* events without persistence. It is NOT a degraded engine — it deliberately
|
|
2187
|
+
* exposes no `models`/`repositories`/`withTransaction`.
|
|
2188
|
+
*/
|
|
2189
|
+
function createCartDomain(shape, runtime = {}) {
|
|
2190
|
+
requireKinds(shape);
|
|
2191
|
+
const kinds = createKindRegistry(shape.kinds);
|
|
2192
|
+
const clock = runtime.clock ?? systemClock;
|
|
2193
|
+
const id = runtime.id ?? cryptoIdPort;
|
|
2194
|
+
const ownsBus = runtime.eventTransport === void 0;
|
|
2195
|
+
const events = runtime.eventTransport ?? new InProcessCartEventBus();
|
|
2196
|
+
let closed = false;
|
|
2197
|
+
return Object.freeze({
|
|
2061
2198
|
kinds,
|
|
2062
2199
|
events,
|
|
2063
2200
|
clock,
|
|
2064
2201
|
id,
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
connection: config.connection,
|
|
2072
|
-
eventTransport: events,
|
|
2073
|
-
logger: console,
|
|
2074
|
-
allowNonTransactional
|
|
2075
|
-
}, ctx, body);
|
|
2076
|
-
},
|
|
2077
|
-
async syncIndexes() {
|
|
2078
|
-
await Promise.all(Object.values(models).map((m) => m.createIndexes()));
|
|
2079
|
-
},
|
|
2080
|
-
async destroy() {}
|
|
2081
|
-
};
|
|
2202
|
+
async close() {
|
|
2203
|
+
if (closed) return;
|
|
2204
|
+
closed = true;
|
|
2205
|
+
if (ownsBus) await events.close?.();
|
|
2206
|
+
}
|
|
2207
|
+
});
|
|
2082
2208
|
}
|
|
2083
2209
|
//#endregion
|
|
2084
|
-
export {
|
|
2210
|
+
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 };
|