@classytic/cart 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +109 -0
- package/dist/bundle.kind-BdgnyKZt.d.mts +114 -0
- package/dist/bundle.kind-DFydSxV_.mjs +362 -0
- package/dist/cart-event-catalog-BIbi2Q_n.d.mts +109 -0
- package/dist/cart-event-catalog-BOP9aDhL.mjs +301 -0
- package/dist/cart-status.vo-2iisZGhb.d.mts +46 -0
- package/dist/create-cart-q3CXxPP7.mjs +1751 -0
- package/dist/domain/errors/index.d.mts +2 -0
- package/dist/domain/errors/index.mjs +4 -0
- package/dist/domain/events/index.d.mts +3 -0
- package/dist/domain/events/index.mjs +3 -0
- package/dist/domain/index.d.mts +12 -0
- package/dist/domain/index.mjs +15 -0
- package/dist/domain/ports/index.d.mts +3 -0
- package/dist/domain/ports/index.mjs +2 -0
- package/dist/domain/saga/index.d.mts +2 -0
- package/dist/domain/saga/index.mjs +3 -0
- package/dist/domain-event-DHNkz15G.mjs +57 -0
- package/dist/engine/cart-config.schema.d.mts +41 -0
- package/dist/engine/cart-config.schema.mjs +40 -0
- package/dist/engine/index.d.mts +3 -0
- package/dist/engine/index.mjs +3 -0
- package/dist/errors-CHR9RlbY.mjs +97 -0
- package/dist/id.port-C3rlDAKP.mjs +29 -0
- package/dist/id.port-DPXLrqb2.d.mts +64 -0
- package/dist/idempotency-key.vo-D0lJsvGn.mjs +9 -0
- package/dist/idempotency-record.entity-DIFXjN1V.d.mts +221 -0
- package/dist/index-DEHBdV_z.d.mts +1 -0
- package/dist/index-Doi5uzux.d.mts +231 -0
- package/dist/index.d.mts +103 -0
- package/dist/index.mjs +92 -0
- package/dist/internal-event-bus-IkUfQJxn.d.mts +661 -0
- package/dist/kind-registry-Ba4PO4WC.mjs +35 -0
- package/dist/kind.error-CCjTB6kW.mjs +69 -0
- package/dist/kinds/index.d.mts +2 -0
- package/dist/kinds/index.mjs +2 -0
- package/dist/line-item.entity-B3M_i-pw.d.mts +157 -0
- package/dist/line-kind-Bndo6IS8.d.mts +231 -0
- package/dist/not-found.error-B6WYnAjX.mjs +95 -0
- package/dist/outbox-store-CTWz9pvG.d.mts +155 -0
- package/dist/saga-step-fn-Cyob38iU.d.mts +135 -0
- package/dist/saga-steps-B27LI7xp.mjs +27 -0
- package/dist/shipping.bridge-DD4A_O0O.d.mts +538 -0
- package/dist/state-transitions-CpJpZZTK.mjs +21 -0
- package/package.json +114 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//#region src/domain/errors/cart.error.ts
|
|
2
|
+
var CartError = class extends Error {
|
|
3
|
+
/** Optional structured context for logging / debugging. */
|
|
4
|
+
context;
|
|
5
|
+
constructor(message, context) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = new.target.name;
|
|
8
|
+
this.context = context;
|
|
9
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Serialize to a wire-safe shape. Suitable for HTTP error bodies and
|
|
13
|
+
* structured logging. Never includes stack frames.
|
|
14
|
+
*/
|
|
15
|
+
toJSON() {
|
|
16
|
+
return {
|
|
17
|
+
name: this.name,
|
|
18
|
+
code: this.code,
|
|
19
|
+
category: this.category,
|
|
20
|
+
message: this.message,
|
|
21
|
+
retryable: this.retryable,
|
|
22
|
+
context: this.context
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/domain/errors/kind.error.ts
|
|
28
|
+
/**
|
|
29
|
+
* A LineKind rejected a line during validate() or price().
|
|
30
|
+
*
|
|
31
|
+
* Used for both:
|
|
32
|
+
* - User-facing validation failures ("quantity exceeds max per line")
|
|
33
|
+
* - Configuration failures ("kind 'timeslot' is not registered")
|
|
34
|
+
*
|
|
35
|
+
* `retryable: false` by default because changing the input will require a
|
|
36
|
+
* new idempotency key anyway.
|
|
37
|
+
*/
|
|
38
|
+
var KindError = class extends CartError {
|
|
39
|
+
code;
|
|
40
|
+
category = "validation";
|
|
41
|
+
retryable = false;
|
|
42
|
+
constructor(kind, reason, opts = {}) {
|
|
43
|
+
super(`LineKind '${kind}' rejected the line: ${reason}`, {
|
|
44
|
+
kind,
|
|
45
|
+
reason,
|
|
46
|
+
...opts.details
|
|
47
|
+
});
|
|
48
|
+
this.code = opts.code ?? "cart/kind_rejected";
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* A kind referenced by a line is not registered in the engine's kind
|
|
53
|
+
* registry. This is a configuration bug — the host forgot to register the
|
|
54
|
+
* kind or registered it under a different name. Always fatal, never
|
|
55
|
+
* retryable.
|
|
56
|
+
*/
|
|
57
|
+
var UnknownKindError = class extends CartError {
|
|
58
|
+
code = "cart/unknown_kind";
|
|
59
|
+
category = "system";
|
|
60
|
+
retryable = false;
|
|
61
|
+
constructor(kind, registered) {
|
|
62
|
+
super(`Unknown LineKind '${kind}'. Registered kinds: ${registered.join(", ") || "<none>"}`, {
|
|
63
|
+
kind,
|
|
64
|
+
registered
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
//#endregion
|
|
69
|
+
export { UnknownKindError as n, CartError as r, KindError as t };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as TimeslotPayload, c as VariantPayload, d as SkuPayload, f as skuKind, i as bundlePayloadSchema, l as variantKind, n as BundlePayload, o as timeslotKind, p as skuPayloadSchema, r as bundleKind, s as timeslotPayloadSchema, t as BundleComponent, u as variantPayloadSchema } from "../bundle.kind-BdgnyKZt.mjs";
|
|
2
|
+
export { type BundleComponent, type BundlePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as variantKind, c as skuPayloadSchema, i as timeslotPayloadSchema, n as bundlePayloadSchema, o as variantPayloadSchema, r as timeslotKind, s as skuKind, t as bundleKind } from "../bundle.kind-DFydSxV_.mjs";
|
|
2
|
+
export { bundleKind, bundlePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { l as LineDisplay, r as LineKind } from "./line-kind-Bndo6IS8.mjs";
|
|
2
|
+
import * as _$_classytic_primitives_money0 from "@classytic/primitives/money";
|
|
3
|
+
import { Money } from "@classytic/primitives/money";
|
|
4
|
+
|
|
5
|
+
//#region src/domain/value-objects/idempotency-key.vo.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The closed set of operations that participate in the idempotency contract.
|
|
8
|
+
*
|
|
9
|
+
* Every mutating operation the cart engine exposes MUST be listed here. The
|
|
10
|
+
* composite identity `(organizationId, cartRef, operation, actorRef, idempotencyKey)`
|
|
11
|
+
* makes it impossible to reuse a key across operations on the same cart by
|
|
12
|
+
* the same actor — reuse collides on the `operation` segment.
|
|
13
|
+
*
|
|
14
|
+
* See plan §2 — Idempotency identity is composite.
|
|
15
|
+
*/
|
|
16
|
+
type OperationName = 'draft.create' | 'draft.addItem' | 'draft.updateItem' | 'draft.removeItem' | 'draft.applyPromoCode' | 'draft.merge' | 'checkout.start' | 'checkout.authorize' | 'checkout.finalize' | 'checkout.cancel' | 'checkout.capture';
|
|
17
|
+
/**
|
|
18
|
+
* Idempotency identity — all five fields are required.
|
|
19
|
+
*
|
|
20
|
+
* organizationId — branch scope, string (Better Auth convention, see §1)
|
|
21
|
+
* cartRef — draft/checkout publicId or the literal 'new' for creation
|
|
22
|
+
* operation — from the OperationName enum
|
|
23
|
+
* actorRef — userId (authenticated) or sessionId (guest). Never null.
|
|
24
|
+
* idempotencyKey — host-supplied, required for all mutating ops
|
|
25
|
+
*/
|
|
26
|
+
interface IdempotencyIdentity {
|
|
27
|
+
organizationId: string;
|
|
28
|
+
cartRef: string | 'new';
|
|
29
|
+
operation: OperationName;
|
|
30
|
+
actorRef: string;
|
|
31
|
+
idempotencyKey: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Idempotency replay payload — the exact bytes the first attempt produced.
|
|
35
|
+
*
|
|
36
|
+
* Stored inline on the idempotency record when serialized size ≤ threshold
|
|
37
|
+
* (default 12KB, configurable). Above the threshold, the record stores a
|
|
38
|
+
* pointer to `cart_operation_results` with the same TTL.
|
|
39
|
+
*
|
|
40
|
+
* Failed operations replay the cached error verbatim until the record TTLs
|
|
41
|
+
* out. See plan §2 — Failed-op replay rule.
|
|
42
|
+
*/
|
|
43
|
+
interface IdempotencyReplay {
|
|
44
|
+
status: 'succeeded' | 'failed';
|
|
45
|
+
resultInline?: {
|
|
46
|
+
payload: string;
|
|
47
|
+
httpStatus?: number;
|
|
48
|
+
etag?: string;
|
|
49
|
+
};
|
|
50
|
+
resultPointer?: {
|
|
51
|
+
collection: 'cart_operation_results';
|
|
52
|
+
docId: string;
|
|
53
|
+
};
|
|
54
|
+
error?: {
|
|
55
|
+
code: string;
|
|
56
|
+
message: string;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Sentinel for the cart-creation operation where no cartRef exists yet.
|
|
61
|
+
* Using a literal rather than null keeps the composite index unique-safe
|
|
62
|
+
* under MongoDB semantics (nulls are considered equal by the unique index).
|
|
63
|
+
*/
|
|
64
|
+
declare const CART_REF_NEW: "new";
|
|
65
|
+
/**
|
|
66
|
+
* Convenience type — the pricing totals referenced from an idempotency record
|
|
67
|
+
* for fast UI display on replay hits. Not part of the replay payload itself;
|
|
68
|
+
* this is just a projection returned from `DraftRepository.addItem`.
|
|
69
|
+
*/
|
|
70
|
+
interface TotalsSnapshot {
|
|
71
|
+
subtotal: Money;
|
|
72
|
+
discount: Money;
|
|
73
|
+
tax: Money;
|
|
74
|
+
shipping: Money;
|
|
75
|
+
grandTotal: Money;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/domain/kinds/kind-registry.d.ts
|
|
79
|
+
/**
|
|
80
|
+
* KindRegistry — the engine's lookup table of registered LineKinds.
|
|
81
|
+
*
|
|
82
|
+
* Built once at `createCart()` time from `config.kinds` and treated as
|
|
83
|
+
* immutable thereafter. Looking up an unknown kind throws UnknownKindError.
|
|
84
|
+
*
|
|
85
|
+
* Not a class — a frozen object literal — so it can be tree-shaken and so
|
|
86
|
+
* tests can build throwaway registries without instantiation noise.
|
|
87
|
+
*/
|
|
88
|
+
interface KindRegistry {
|
|
89
|
+
/** Look up a kind by name. Throws if unknown. */
|
|
90
|
+
get(name: string): LineKind;
|
|
91
|
+
/** Non-throwing variant. */
|
|
92
|
+
tryGet(name: string): LineKind | undefined;
|
|
93
|
+
/** List of registered kind names for diagnostics. */
|
|
94
|
+
list(): readonly string[];
|
|
95
|
+
/** Total count of registered kinds. */
|
|
96
|
+
readonly size: number;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Build a KindRegistry from a list of LineKind implementations.
|
|
100
|
+
*
|
|
101
|
+
* Throws at construction if two kinds share a name — the engine will not
|
|
102
|
+
* silently overwrite. Hosts that want to override a built-in kind must
|
|
103
|
+
* remove the built-in from their `config.kinds` array explicitly.
|
|
104
|
+
*/
|
|
105
|
+
declare function createKindRegistry(kinds: readonly LineKind[]): KindRegistry;
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/domain/entities/line-item.entity.d.ts
|
|
108
|
+
/**
|
|
109
|
+
* LineItem — a single row inside a Draft or Checkout.
|
|
110
|
+
*
|
|
111
|
+
* Structurally identical on both entities (drafts carry mutable lines;
|
|
112
|
+
* checkouts carry frozen snapshots). The `kind` field selects which
|
|
113
|
+
* LineKind strategy owns the payload's schema, validation, pricing,
|
|
114
|
+
* reservation, and finalization.
|
|
115
|
+
*
|
|
116
|
+
* `payload` is intentionally `unknown` at the entity layer — the kind's
|
|
117
|
+
* zod schema narrows it at the boundary. Downstream consumers that know
|
|
118
|
+
* the kind cast via helpers.
|
|
119
|
+
*
|
|
120
|
+
* **`display` is the denormalized UI snapshot.** Populated by
|
|
121
|
+
* `LineKind.displayOf()` at add-time, it lets the UI render the cart
|
|
122
|
+
* without a second catalog call per line. See `LineDisplay` for the
|
|
123
|
+
* full contract.
|
|
124
|
+
*/
|
|
125
|
+
interface LineItem<TPayload = unknown> {
|
|
126
|
+
/** Stable line ID — ObjectId string form, generated at creation. */
|
|
127
|
+
lineId: string;
|
|
128
|
+
/** Kind name — key into the KindRegistry. */
|
|
129
|
+
kind: string;
|
|
130
|
+
/**
|
|
131
|
+
* Opaque kind-specific data. Validated by the kind's payloadSchema at
|
|
132
|
+
* the draft service boundary.
|
|
133
|
+
*/
|
|
134
|
+
payload: TPayload;
|
|
135
|
+
/** Units. Always a positive integer. */
|
|
136
|
+
quantity: number;
|
|
137
|
+
/**
|
|
138
|
+
* Optional unit-price override — when the host wants to force a price
|
|
139
|
+
* regardless of what the kind would compute. Used by admin tools and
|
|
140
|
+
* special-deal flows. Kinds that honor overrides do so in their price()
|
|
141
|
+
* implementation; kinds that reject overrides throw KindError.
|
|
142
|
+
*/
|
|
143
|
+
overrideUnitPrice?: _$_classytic_primitives_money0.Money;
|
|
144
|
+
/**
|
|
145
|
+
* Denormalized display snapshot for UI rendering. Populated by the
|
|
146
|
+
* kind's `displayOf()` method at add-time. Kept fresh via
|
|
147
|
+
* `LineKind.revalidate()` when the line becomes stale. Optional —
|
|
148
|
+
* hosts that prefer live-read rendering can leave it unset.
|
|
149
|
+
*/
|
|
150
|
+
display?: LineDisplay;
|
|
151
|
+
/** Created-at timestamp. */
|
|
152
|
+
addedAt: Date;
|
|
153
|
+
/** Optional metadata — public-facing. */
|
|
154
|
+
metadata?: Record<string, unknown>;
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
export { IdempotencyIdentity as a, TotalsSnapshot as c, CART_REF_NEW as i, KindRegistry as n, IdempotencyReplay as o, createKindRegistry as r, OperationName as s, LineItem as t };
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { S as PricedLine, f as PromotionsBridge, g as CatalogBridge, m as ReservationRef, o as TaxBridge, p as InventoryBridge, t as ShippingBridge, x as OperationContext } from "./shipping.bridge-DD4A_O0O.mjs";
|
|
2
|
+
import { Money } from "@classytic/primitives/money";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
//#region src/domain/value-objects/line-display.vo.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* LineDisplay — the denormalized snapshot stored on each cart line for
|
|
8
|
+
* UI rendering.
|
|
9
|
+
*
|
|
10
|
+
* **The point of this value object.** Without it, every cart render has
|
|
11
|
+
* to call `CatalogBridge.resolve()` per line to get name / image / slug.
|
|
12
|
+
* That is exactly the `.populate()` anti-pattern cart is designed to
|
|
13
|
+
* eliminate. With it, the UI renders directly from the draft document —
|
|
14
|
+
* one read, zero joins.
|
|
15
|
+
*
|
|
16
|
+
* Populated by the LineKind's optional `displayOf()` method at add-time,
|
|
17
|
+
* stored on `LineItem.display`, cleaned up with the draft itself (TTL,
|
|
18
|
+
* abandonment, or conversion to checkout). There is no separate display
|
|
19
|
+
* cache to manage.
|
|
20
|
+
*
|
|
21
|
+
* **Staleness.** The snapshot can drift from the live catalog (product
|
|
22
|
+
* renamed, image updated). Revalidation at finalize catches price drift
|
|
23
|
+
* via `LineKind.revalidate()`. Display drift is almost always acceptable
|
|
24
|
+
* — the user already saw the name + image they wanted — but hosts that
|
|
25
|
+
* care about absolute freshness can refresh by calling `displayOf()`
|
|
26
|
+
* again from their own cron or webhook consumer.
|
|
27
|
+
*
|
|
28
|
+
* All fields are optional so hosts can populate only what they need.
|
|
29
|
+
* Cart never requires a display snapshot — lines without one just can't
|
|
30
|
+
* render standalone.
|
|
31
|
+
*/
|
|
32
|
+
interface LineDisplay {
|
|
33
|
+
/** Human-readable product name. */
|
|
34
|
+
name?: string;
|
|
35
|
+
/** Thumbnail / hero image URL (pre-resolved transforms). */
|
|
36
|
+
imageUrl?: string;
|
|
37
|
+
/** Product detail page slug for deep-linking from the cart UI. */
|
|
38
|
+
slug?: string;
|
|
39
|
+
/** Pre-formatted variant label, e.g. "Size: M, Color: Blue". */
|
|
40
|
+
variantLabel?: string;
|
|
41
|
+
/** Compare-at price for strikethrough display. */
|
|
42
|
+
compareAtPrice?: Money;
|
|
43
|
+
/**
|
|
44
|
+
* Timestamp when this snapshot was captured. The UI may show a "refresh"
|
|
45
|
+
* affordance if the snapshot is older than some threshold.
|
|
46
|
+
*/
|
|
47
|
+
capturedAt: Date;
|
|
48
|
+
}
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/domain/kinds/validity.d.ts
|
|
51
|
+
/**
|
|
52
|
+
* ValidityPolicy — how long a priced line's quote is good for and what to
|
|
53
|
+
* do when it expires. Every LineKind declares one.
|
|
54
|
+
*
|
|
55
|
+
* maxAgeMs — optional. undefined means "never stale" (e.g., hard-priced
|
|
56
|
+
* catalog SKUs).
|
|
57
|
+
* onStale — the kind's contract for what the saga's revalidation step
|
|
58
|
+
* does when a line is past its validity window.
|
|
59
|
+
* triggers — optional list of upstream events that should pre-emptively
|
|
60
|
+
* invalidate priced snapshots. Advisory only in P0; used by
|
|
61
|
+
* the cache invalidation plugin in later phases.
|
|
62
|
+
*
|
|
63
|
+
* See plan §5 — LineKind has an explicit validity/revalidation contract.
|
|
64
|
+
*/
|
|
65
|
+
interface ValidityPolicy {
|
|
66
|
+
maxAgeMs?: number;
|
|
67
|
+
onStale: StaleBehavior;
|
|
68
|
+
triggers?: readonly StaleTrigger[];
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* reprice — silently re-run price() and continue. Suitable for bundles,
|
|
72
|
+
* group-buy, and other cases where drift is acceptable.
|
|
73
|
+
* error — abort finalize with StaleQuoteError; the client must
|
|
74
|
+
* re-display and re-confirm. Required for bids, timeslots,
|
|
75
|
+
* rentals, and anything auction-like.
|
|
76
|
+
* extend — treat as indefinitely valid. Only for catalog SKUs where
|
|
77
|
+
* price changes are propagated by webhook, not time.
|
|
78
|
+
*/
|
|
79
|
+
type StaleBehavior = 'reprice' | 'error' | 'extend';
|
|
80
|
+
type StaleTrigger = 'pricelistChange' | 'stockChange' | 'surgeChange' | 'shippingRateChange' | 'promoChange';
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/domain/kinds/line-kind.d.ts
|
|
83
|
+
/**
|
|
84
|
+
* LineKind<TPayload> — the single polymorphism point that handles every
|
|
85
|
+
* business scenario the cart engine supports.
|
|
86
|
+
*
|
|
87
|
+
* One LineKind per line category. Hosts register only the kinds they need;
|
|
88
|
+
* the rest tree-shake out. Built-in kinds ship under `@classytic/cart/kinds`
|
|
89
|
+
* — `sku`, `variant`, `bundle`, `timeslot`, `rental`, `subscription-plan`,
|
|
90
|
+
* `bid`, `group-buy`. Custom kinds are a first-class extension point —
|
|
91
|
+
* hosts implement this interface and register the result via config.
|
|
92
|
+
*
|
|
93
|
+
* Method responsibilities:
|
|
94
|
+
*
|
|
95
|
+
* validate — enforce line-level business invariants (qty limits, slot
|
|
96
|
+
* availability, etc.). Runs on every draft mutation and
|
|
97
|
+
* again when `checkout.createFromDraft` runs revalidation.
|
|
98
|
+
* price — compute a PricedLine from the current line + context.
|
|
99
|
+
* Runs on every pricing pipeline invocation. Must be pure
|
|
100
|
+
* w.r.t. the input line; any catalog/pricing lookups go
|
|
101
|
+
* through the context's bridges.
|
|
102
|
+
* revalidate — called on stale lines past their ValidityPolicy.maxAgeMs
|
|
103
|
+
* window. Returns 'unchanged', 'reprice' (with a new
|
|
104
|
+
* PricedLine), or 'invalid' (with a reason the
|
|
105
|
+
* StaleQuoteError bubbles up).
|
|
106
|
+
* displayOf — optional. Capture a denormalized UI snapshot at
|
|
107
|
+
* add-time so the cart renders without a catalog join.
|
|
108
|
+
* reserve — optional. Inventory hold via an inventory bridge.
|
|
109
|
+
* Kinds must null-check `ctx.bridges.inventory` first.
|
|
110
|
+
* release — optional. Idempotent release used by the host or
|
|
111
|
+
* the cancel path.
|
|
112
|
+
* finalize — optional. Called after `checkout.commit()` if the kind
|
|
113
|
+
* needs to write to an external system on success (e.g.
|
|
114
|
+
* mark a bid "won", link a subscription plan).
|
|
115
|
+
* cacheKey — optional. Stable string for memoising price() results.
|
|
116
|
+
*/
|
|
117
|
+
interface LineKind<TPayload = unknown> {
|
|
118
|
+
/** Unique kind identifier. Must match `LineItem.kind` on persisted lines. */
|
|
119
|
+
readonly name: string;
|
|
120
|
+
/**
|
|
121
|
+
* Zod v4 schema for the kind's payload. The draft service uses this to
|
|
122
|
+
* validate input at the repository boundary, before anything persistent
|
|
123
|
+
* happens. Schemas should be strict — unknown fields rejected.
|
|
124
|
+
*/
|
|
125
|
+
readonly payloadSchema: z.ZodType<TPayload>;
|
|
126
|
+
/** How long a priced line of this kind stays good. */
|
|
127
|
+
readonly validity: ValidityPolicy;
|
|
128
|
+
validate(line: LineLike<TPayload>, ctx: KindContext): Promise<void>;
|
|
129
|
+
price(line: LineLike<TPayload>, ctx: KindContext): Promise<PricedLine>;
|
|
130
|
+
revalidate(line: LineLike<TPayload>, priced: PricedLine, ctx: KindContext): Promise<RevalidationResult>;
|
|
131
|
+
reserve?(line: LineLike<TPayload>, ctx: KindContext): Promise<ReservationRef | null>;
|
|
132
|
+
release?(ref: ReservationRef, ctx: KindContext): Promise<void>;
|
|
133
|
+
finalize?(line: LineLike<TPayload>, ctx: KindContext): Promise<void>;
|
|
134
|
+
/**
|
|
135
|
+
* Optional — build a denormalized display snapshot for the line. Called
|
|
136
|
+
* by the draft service at add-time; the returned snapshot is persisted
|
|
137
|
+
* on `LineItem.display` so the UI can render the cart without a second
|
|
138
|
+
* catalog lookup per line. Returning `null` means "no display data
|
|
139
|
+
* available"; the line still stores normally but renders as a bare
|
|
140
|
+
* reference.
|
|
141
|
+
*
|
|
142
|
+
* Kinds that wrap a catalog product (sku, variant, bundle) should
|
|
143
|
+
* implement this. Kinds that have no external display source (tip,
|
|
144
|
+
* custom fee) can omit it.
|
|
145
|
+
*/
|
|
146
|
+
displayOf?(line: LineLike<TPayload>, ctx: KindContext): Promise<LineDisplay | null>;
|
|
147
|
+
cacheKey?(line: LineLike<TPayload>): string;
|
|
148
|
+
/**
|
|
149
|
+
* Optional — derive the deduplication key for this line. The draft
|
|
150
|
+
* repository's `addItem` flow uses this to decide whether an incoming
|
|
151
|
+
* line should MERGE into an existing line (quantity += incoming.quantity)
|
|
152
|
+
* or APPEND as a new row.
|
|
153
|
+
*
|
|
154
|
+
* Return the same string for two lines that should collapse into one
|
|
155
|
+
* (e.g., same productRef+variantSku). Return `null` to opt this line
|
|
156
|
+
* out of merging — useful for kinds where every add must stay separate
|
|
157
|
+
* (e.g., a booking with a chosen timeslot, or a bid where each entry
|
|
158
|
+
* is unique).
|
|
159
|
+
*
|
|
160
|
+
* When a kind does NOT implement this method, the repository falls back
|
|
161
|
+
* to legacy detection (payload.skuRef) so older custom kinds keep the
|
|
162
|
+
* previous behavior.
|
|
163
|
+
*/
|
|
164
|
+
mergeKey?(line: LineLike<TPayload>): string | null;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The minimal shape the kind receives. Deliberately not the full LineItem
|
|
168
|
+
* entity — kinds should not depend on persistence concerns.
|
|
169
|
+
*/
|
|
170
|
+
interface LineLike<TPayload = unknown> {
|
|
171
|
+
lineId: string;
|
|
172
|
+
kind: string;
|
|
173
|
+
quantity: number;
|
|
174
|
+
payload: TPayload;
|
|
175
|
+
currency: string;
|
|
176
|
+
/** Unit price override, if the host is forcing a price. */
|
|
177
|
+
overrideUnitPrice?: Money;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Context passed to every kind method. A superset of OperationContext with
|
|
181
|
+
* the bridges the kind may need. Bridges are explicitly passed (not looked
|
|
182
|
+
* up on a global) so kinds are trivially testable in isolation with stub
|
|
183
|
+
* bridges.
|
|
184
|
+
*
|
|
185
|
+
* Using an opaque `bridges` index so each kind only depends on the bridges
|
|
186
|
+
* it actually uses. A kind that only needs CatalogBridge can import that
|
|
187
|
+
* one type; adding a new bridge to the engine does not break existing kinds.
|
|
188
|
+
*/
|
|
189
|
+
interface KindContext extends OperationContext {
|
|
190
|
+
/**
|
|
191
|
+
* Bridge registry. Keys match the bridge names in CartConfig. Values are
|
|
192
|
+
* typed via the interface augmentation in `engine-types.ts`.
|
|
193
|
+
*/
|
|
194
|
+
readonly bridges: KindBridges;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The bridges available to a kind method. This is a lookup table rather
|
|
198
|
+
* than a typed interface so custom kinds can access host-registered bridges
|
|
199
|
+
* via string keys without forcing every kind to know the full bridge surface.
|
|
200
|
+
*
|
|
201
|
+
* The engine populates this at construction time from CartConfig.bridges.
|
|
202
|
+
*/
|
|
203
|
+
interface KindBridges {
|
|
204
|
+
readonly catalog: CatalogBridge;
|
|
205
|
+
/**
|
|
206
|
+
* Inventory bridge is optional — kinds that don't reserve (sku, tip,
|
|
207
|
+
* plain variants) don't need it. Kinds with a `reserve()` method must
|
|
208
|
+
* null-check `ctx.bridges.inventory` before calling it.
|
|
209
|
+
*/
|
|
210
|
+
readonly inventory?: InventoryBridge;
|
|
211
|
+
readonly promotions?: PromotionsBridge;
|
|
212
|
+
readonly tax?: TaxBridge;
|
|
213
|
+
readonly shipping?: ShippingBridge;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Result of a revalidation call — one of three variants.
|
|
217
|
+
*/
|
|
218
|
+
type RevalidationResult = {
|
|
219
|
+
status: 'unchanged';
|
|
220
|
+
priced: PricedLine;
|
|
221
|
+
} | {
|
|
222
|
+
status: 'reprice';
|
|
223
|
+
priced: PricedLine;
|
|
224
|
+
delta: Money;
|
|
225
|
+
} | {
|
|
226
|
+
status: 'invalid';
|
|
227
|
+
reason: string;
|
|
228
|
+
details?: Record<string, unknown>;
|
|
229
|
+
};
|
|
230
|
+
//#endregion
|
|
231
|
+
export { RevalidationResult as a, ValidityPolicy as c, LineLike as i, LineDisplay as l, KindContext as n, StaleBehavior as o, LineKind as r, StaleTrigger as s, KindBridges as t };
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { r as CartError } from "./kind.error-CCjTB6kW.mjs";
|
|
2
|
+
//#region src/domain/errors/concurrency.error.ts
|
|
3
|
+
/**
|
|
4
|
+
* Optimistic-lock mismatch. Thrown when a mutation attempts to update a
|
|
5
|
+
* document with a stale `version` — another writer committed first.
|
|
6
|
+
*
|
|
7
|
+
* Host should re-read the draft/checkout and retry with the fresh state.
|
|
8
|
+
* Retryable, but the caller MUST mint a new idempotency key for the retry
|
|
9
|
+
* (the previous attempt's key is locked to the stale version number).
|
|
10
|
+
*/
|
|
11
|
+
var ConcurrencyError = class extends CartError {
|
|
12
|
+
code = "cart/concurrency_version_mismatch";
|
|
13
|
+
category = "concurrency";
|
|
14
|
+
retryable = true;
|
|
15
|
+
constructor(resource, expectedVersion, resourceId) {
|
|
16
|
+
super(`${resource}/${resourceId} was modified concurrently — expected version ${expectedVersion}`, {
|
|
17
|
+
resource,
|
|
18
|
+
resourceId,
|
|
19
|
+
expectedVersion
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/domain/errors/price-changed.error.ts
|
|
25
|
+
/**
|
|
26
|
+
* The re-run pricing snapshot's hash does not match the `expectedPricingHash`
|
|
27
|
+
* the client supplied when initiating finalize. Fired from saga step 3.
|
|
28
|
+
*
|
|
29
|
+
* This is a safety interlock: the client saw totals X, but by the time the
|
|
30
|
+
* saga ran, totals are now Y. Rather than silently charging a different
|
|
31
|
+
* amount, the saga aborts with this error so the client re-displays and
|
|
32
|
+
* re-confirms.
|
|
33
|
+
*
|
|
34
|
+
* Retryable with a new idempotency key AND a new expectedPricingHash matching
|
|
35
|
+
* the new snapshot.
|
|
36
|
+
*/
|
|
37
|
+
var PriceChangedError = class extends CartError {
|
|
38
|
+
code = "cart/price_changed";
|
|
39
|
+
category = "validation";
|
|
40
|
+
retryable = true;
|
|
41
|
+
constructor(expectedHash, actualHash, context) {
|
|
42
|
+
super(`Pricing changed since the client confirmed: expected ${expectedHash}, got ${actualHash}`, {
|
|
43
|
+
expectedHash,
|
|
44
|
+
actualHash,
|
|
45
|
+
...context
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/domain/errors/state-transition.error.ts
|
|
51
|
+
/**
|
|
52
|
+
* A write attempted to transition `checkout.state` along an edge that
|
|
53
|
+
* does not exist in the frozen state machine (see plan simplification —
|
|
54
|
+
* `open → finalized | canceled`).
|
|
55
|
+
*
|
|
56
|
+
* Thrown by service methods before the mutation reaches the database.
|
|
57
|
+
* Never retryable — the caller either has a bug or is racing another
|
|
58
|
+
* writer. A concurrency race manifests as `ConcurrencyError` first via
|
|
59
|
+
* the version check; if it reaches here, it is a logic bug.
|
|
60
|
+
*/
|
|
61
|
+
var StateTransitionError = class extends CartError {
|
|
62
|
+
code = "cart/illegal_state_transition";
|
|
63
|
+
category = "state";
|
|
64
|
+
retryable = false;
|
|
65
|
+
constructor(checkoutId, from, to) {
|
|
66
|
+
super(`Illegal checkout state transition on ${checkoutId}: ${from} -> ${to}`, {
|
|
67
|
+
checkoutId,
|
|
68
|
+
from,
|
|
69
|
+
to
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/domain/errors/not-found.error.ts
|
|
75
|
+
/**
|
|
76
|
+
* The requested draft, checkout, or reservation does not exist (or is not
|
|
77
|
+
* visible under the caller's organizationId scope).
|
|
78
|
+
*
|
|
79
|
+
* Retryable is false — the resource simply does not exist. If the host
|
|
80
|
+
* thinks it should, the bug is upstream.
|
|
81
|
+
*/
|
|
82
|
+
var NotFoundError = class extends CartError {
|
|
83
|
+
code = "cart/not_found";
|
|
84
|
+
category = "not_found";
|
|
85
|
+
retryable = false;
|
|
86
|
+
constructor(resource, ref, organizationId) {
|
|
87
|
+
super(`${resource} '${ref}' not found${organizationId ? ` in org ${organizationId}` : ""}`, {
|
|
88
|
+
resource,
|
|
89
|
+
ref,
|
|
90
|
+
organizationId
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
//#endregion
|
|
95
|
+
export { ConcurrencyError as i, StateTransitionError as n, PriceChangedError as r, NotFoundError as t };
|