@shirudo/ddd-kit 2.2.0 → 3.0.0-rc.10

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.
@@ -0,0 +1,1165 @@
1
+ import { StructuredError } from "@shirudo/base-error";
2
+
3
+ //#region src/errors/kit-errors.ts
4
+ /** The keys `StructuredError` owns, which a declared field never replaces. */
5
+ const ENVELOPE_FIELDS = /* @__PURE__ */ new Set(["_tag", "details"]);
6
+ /**
7
+ * The fields a kit error declares of its own, for the raw log object.
8
+ *
9
+ * Every field of a kit error is an own enumerable property, so the log object
10
+ * carries them without each class repeating them.
11
+ */
12
+ function ownFields(error) {
13
+ const fields = {};
14
+ for (const key of Object.keys(error)) {
15
+ if (ENVELOPE_FIELDS.has(key)) continue;
16
+ try {
17
+ const safe = logSafeValue(error[key]);
18
+ if (safe !== void 0) fields[key] = safe;
19
+ } catch {}
20
+ }
21
+ return fields;
22
+ }
23
+ /**
24
+ * Projects one field value to something a log serializer survives.
25
+ *
26
+ * A field of type `unknown` can hold a driver value with a cycle, a bigint or
27
+ * a symbol, and `JSON.stringify` throws on the first two. A serializer that
28
+ * throws inside the failure path costs the whole report, so a value that does
29
+ * not survive the attempt is left out. An error keeps its name, message and
30
+ * code, which is what a reader needs and cannot cycle.
31
+ */
32
+ function logSafeValue(value) {
33
+ switch (typeof value) {
34
+ case "string":
35
+ case "number":
36
+ case "boolean": return value;
37
+ case "bigint":
38
+ case "symbol": return String(value);
39
+ case "undefined":
40
+ case "function": return;
41
+ }
42
+ if (value === null) return null;
43
+ if (value instanceof Error) {
44
+ const code = value.code;
45
+ return {
46
+ name: String(value.name),
47
+ message: String(value.message),
48
+ ...typeof code === "string" ? { code } : {}
49
+ };
50
+ }
51
+ try {
52
+ JSON.stringify(value);
53
+ return value;
54
+ } catch {
55
+ return;
56
+ }
57
+ }
58
+ /**
59
+ * Abstract base for **domain-invariant violations**. Domain methods
60
+ * (aggregates, entity validation hooks, value-object constructors)
61
+ * throw `DomainError`-derived exceptions when a business rule is
62
+ * violated. Consumers derive their own concrete errors (e.g.
63
+ * `class OrderAlreadyShippedError extends DomainError<"ORDER_ALREADY_SHIPPED">`)
64
+ * for `instanceof`-style catching at the App-Service boundary, where
65
+ * they typically map to HTTP 400 / business-rule responses.
66
+ *
67
+ * The library itself ships no business-rule `DomainError` subclass: the
68
+ * kit can't know your invariants. (The domain-state-machine module's
69
+ * transition errors are the structural exception.)
70
+ *
71
+ * The `category` is fixed to `"DOMAIN"` and `retryable` defaults to
72
+ * `false`, so a subclass supplies only its `code` and `message`:
73
+ *
74
+ * ```ts
75
+ * class OrderAlreadyShippedError extends DomainError<"ORDER_ALREADY_SHIPPED"> {
76
+ * constructor(orderId: string) {
77
+ * super({
78
+ * code: "ORDER_ALREADY_SHIPPED",
79
+ * message: `Order ${orderId} has already been shipped`,
80
+ * });
81
+ * }
82
+ * }
83
+ * ```
84
+ */
85
+ var DomainError = class extends StructuredError {
86
+ constructor(options) {
87
+ super({
88
+ code: options.code,
89
+ category: "DOMAIN",
90
+ retryable: options.retryable ?? false,
91
+ message: options.message,
92
+ cause: options.cause
93
+ });
94
+ }
95
+ /** Carries the fields the concrete error declares into the log object. */
96
+ buildLogObject() {
97
+ return {
98
+ ...ownFields(this),
99
+ ...super.buildLogObject()
100
+ };
101
+ }
102
+ };
103
+ /**
104
+ * Internal base for the kit's crash-loud **WIRING** family: deterministic
105
+ * programming/configuration bugs that must fail the operation loudly and
106
+ * never be absorbed by generic domain or infrastructure handlers. One
107
+ * implementation of the `{ category: "WIRING", retryable: false }` shape
108
+ * so the family cannot drift. Exported for the kit's own modules only;
109
+ * not part of the package entries.
110
+ */
111
+ var KitWiringError = class extends StructuredError {
112
+ constructor(code, message, cause) {
113
+ super({
114
+ code,
115
+ category: "WIRING",
116
+ retryable: false,
117
+ message,
118
+ cause
119
+ });
120
+ }
121
+ /** Carries the fields the concrete error declares into the log object. */
122
+ buildLogObject() {
123
+ return {
124
+ ...ownFields(this),
125
+ ...super.buildLogObject()
126
+ };
127
+ }
128
+ };
129
+ /**
130
+ * Abstract base for **infrastructure / persistence failures** that the
131
+ * App-Service can recover from: typically by retrying, by returning
132
+ * HTTP 404 / 409, or by surfacing a "please try again" UX. These are
133
+ * not domain-invariant violations (the business rules were not
134
+ * broken); they describe race conditions and missing rows at the
135
+ * storage boundary.
136
+ *
137
+ * The `category` is fixed to `"INFRASTRUCTURE"`; `retryable` defaults
138
+ * to `false` (opt in per subclass, see {@link ConcurrencyConflictError}).
139
+ *
140
+ * Library-internal concrete subclasses: {@link AggregateNotFoundError},
141
+ * {@link ConcurrencyConflictError}, {@link DuplicateAggregateError},
142
+ * plus the unit-of-work lifecycle wrappers `CommitError` and
143
+ * `RollbackError` (in `src/application/unit-of-work/errors.ts`).
144
+ */
145
+ var InfrastructureError = class extends StructuredError {
146
+ constructor(options) {
147
+ super({
148
+ code: options.code,
149
+ category: "INFRASTRUCTURE",
150
+ retryable: options.retryable ?? false,
151
+ message: options.message,
152
+ cause: options.cause
153
+ });
154
+ }
155
+ /** Carries the fields the concrete error declares into the log object. */
156
+ buildLogObject() {
157
+ return {
158
+ ...ownFields(this),
159
+ ...super.buildLogObject()
160
+ };
161
+ }
162
+ };
163
+ /**
164
+ * Copy-safe membership check for the kit's domain-error family.
165
+ *
166
+ * `instanceof` is false for an error constructed by another loaded copy of
167
+ * the kit (a separately installed adapter package, a CJS/ESM dual load), so
168
+ * kit boundaries that route by error family fall back to the structural
169
+ * `category` field, the stable cross-copy contract.
170
+ */
171
+ function isDomainErrorLike(value) {
172
+ return value instanceof DomainError || value instanceof Error && value.category === "DOMAIN";
173
+ }
174
+ /**
175
+ * Copy-safe membership check for the kit's infrastructure-error family.
176
+ * Same rationale as {@link isDomainErrorLike}.
177
+ */
178
+ function isInfrastructureErrorLike(value) {
179
+ return value instanceof InfrastructureError || value instanceof Error && value.category === "INFRASTRUCTURE";
180
+ }
181
+ /**
182
+ * Copy-safe membership check for the kit's wiring-error family.
183
+ * Same rationale as {@link isDomainErrorLike}.
184
+ *
185
+ * A wiring error states a deterministic programming or configuration defect.
186
+ * A kit boundary that translates failures uses this check to pass such an
187
+ * error through untouched, instead of relabelling it as a store failure.
188
+ *
189
+ * The check narrows to the structural shape, not to a class: the family's
190
+ * base stays kit-internal, and an error from another kit copy carries the
191
+ * shape without being an instance of this copy's class.
192
+ */
193
+ function isWiringErrorLike(value) {
194
+ return value instanceof KitWiringError || value instanceof Error && value.category === "WIRING";
195
+ }
196
+ /**
197
+ * A finite-capacity in-memory reference adapter rejected new state before
198
+ * mutation. Existing records remain usable; callers must release explicit
199
+ * lifecycle state, increase the configured limit, or switch to a durable
200
+ * adapter. The error is not retryable without one of those external changes.
201
+ */
202
+ var InMemoryCapacityExceededError = class extends InfrastructureError {
203
+ store;
204
+ resource;
205
+ limit;
206
+ current;
207
+ attempted;
208
+ constructor(options) {
209
+ super({
210
+ code: "IN_MEMORY_CAPACITY_EXCEEDED",
211
+ message: `${options.store} cannot retain ${options.attempted} new ${options.resource}: configured limit ${options.limit}, currently retained ${options.current}`
212
+ });
213
+ this.store = options.store;
214
+ this.resource = options.resource;
215
+ this.limit = options.limit;
216
+ this.current = options.current;
217
+ this.attempted = options.attempted;
218
+ }
219
+ };
220
+ /**
221
+ * Thrown when a projection built with `projectionFromHandlers` receives an
222
+ * event type with no own handler entry: the declared event union and the
223
+ * handler map disagree at runtime, which is a programming / configuration
224
+ * bug rather than a domain or infrastructure failure.
225
+ *
226
+ * Deliberately **not** on `DomainError` or `InfrastructureError`:
227
+ * a generic `catch (e instanceof DomainError)` handler at the App
228
+ * layer must not mask a forgotten handler; this should crash loud and
229
+ * fail the calling Use Case so the bug surfaces in development.
230
+ *
231
+ * Use `isBaseError(e)` from `@shirudo/base-error` to detect
232
+ * "any structured error from the kit or any other BaseError-using
233
+ * library" at the App boundary.
234
+ */
235
+ var MissingHandlerError = class extends KitWiringError {
236
+ eventType;
237
+ constructor(eventType, cause) {
238
+ super("MISSING_HANDLER", `Missing handler for event type: ${eventType}`, cause);
239
+ this.eventType = eventType;
240
+ }
241
+ };
242
+ /**
243
+ * Thrown by an event-sourced aggregate when `apply()` or replay reaches an
244
+ * event type with no own entry in the `folds` map: the declared event union
245
+ * and the map disagree at runtime. Same posture as
246
+ * {@link MissingHandlerError}: a deterministic bug, never a domain
247
+ * rejection, so it propagates through `replayHistory` instead of riding its
248
+ * `Result`.
249
+ */
250
+ var MissingFoldError = class extends KitWiringError {
251
+ eventType;
252
+ constructor(eventType, cause) {
253
+ super("MISSING_FOLD", `Missing fold for event type: ${eventType}`, cause);
254
+ this.eventType = eventType;
255
+ }
256
+ };
257
+ /**
258
+ * Thrown by an event-sourced aggregate when a fold returns `undefined`
259
+ * for an event, which is almost always a fold without a `return` statement.
260
+ * Storing that result would set the aggregate state to `undefined`, record
261
+ * the fact anyway on the apply path, and leave every later fold working on
262
+ * nothing. Same posture as {@link MissingFoldError}: a deterministic bug
263
+ * in the folds map, never a domain rejection, so it propagates through
264
+ * `replayHistory` instead of riding its `Result`.
265
+ */
266
+ var FoldReturnedNoStateError = class extends KitWiringError {
267
+ eventType;
268
+ constructor(eventType) {
269
+ super("FOLD_RETURNED_NO_STATE", `The fold for event type "${eventType}" returned no state. A fold must return the next state; check for a missing return statement.`);
270
+ this.eventType = eventType;
271
+ }
272
+ };
273
+ /**
274
+ * Thrown by `EventSourcedAggregate.setState`: on an event-sourced aggregate
275
+ * the state changes only through `apply()`, where the fact is recorded and
276
+ * the version advances with it. A direct state write would leave the
277
+ * instance ahead of its stream with nothing to replay. A wiring error: a
278
+ * deterministic bug in the aggregate's own code, the remedy is an event
279
+ * and a handler.
280
+ */
281
+ var DirectStateMutationError = class extends KitWiringError {
282
+ aggregateId;
283
+ constructor(aggregateId) {
284
+ super("DIRECT_STATE_MUTATION", `Aggregate ${aggregateId} is event-sourced: its state changes only through apply(). Record the fact as an event and fold it in a handler instead of calling setState.`);
285
+ this.aggregateId = aggregateId;
286
+ }
287
+ };
288
+ /**
289
+ * Thrown by `Projector.project` when an event cannot be projected
290
+ * safely because its cursor is missing or malformed, or its aggregate
291
+ * address is absent. Applying such an event would break idempotency, so
292
+ * the batch fails. Events written by `withCommit` carry the complete
293
+ * cursor automatically; other sources compose a gap-proof committed-event
294
+ * envelope. A well-formed cursor that does not continue the stored chain
295
+ * instead throws {@link ProjectionGapError}.
296
+ *
297
+ * A wiring error, not a `DomainError`: see {@link MissingHandlerError}
298
+ * for the rationale of crashing loud at the App layer.
299
+ */
300
+ var UnprojectableEventError = class extends KitWiringError {
301
+ projection;
302
+ eventId;
303
+ constructor(projection, eventId, reason, cause) {
304
+ super("UNPROJECTABLE_EVENT", `Projector(${projection}): event ${eventId} ${reason}`, cause);
305
+ this.projection = projection;
306
+ this.eventId = eventId;
307
+ }
308
+ };
309
+ /**
310
+ * Thrown when a valid projection cursor does not continue the stored
311
+ * per-aggregate chain. This is an infrastructure/delivery failure: an
312
+ * event or commit is missing, commonly because a partition reordered or
313
+ * dead-lettered it. The projector does not apply the later event and the
314
+ * checkpoint stays put until the missing history is replayed or the
315
+ * projection is rebuilt.
316
+ */
317
+ var ProjectionGapError = class extends InfrastructureError {
318
+ projection;
319
+ eventId;
320
+ previousPosition;
321
+ receivedPosition;
322
+ constructor(projection, eventId, previousPosition, receivedPosition) {
323
+ super({
324
+ code: "PROJECTION_GAP",
325
+ message: `Projector(${projection}): event ${eventId} creates a projection gap after ${previousPosition}; received ${receivedPosition}. Replay the missing commit before advancing the checkpoint.`
326
+ });
327
+ this.projection = projection;
328
+ this.eventId = eventId;
329
+ this.previousPosition = previousPosition;
330
+ this.receivedPosition = receivedPosition;
331
+ }
332
+ };
333
+ /**
334
+ * Thrown when one batch delivers previously unseen positions of the same
335
+ * aggregate in descending order. Unlike {@link ProjectionGapError}, this is
336
+ * direct proof that the feed violated its per-aggregate ordering contract;
337
+ * no missing-history inference is needed. Positions already covered by the
338
+ * checkpoint at batch start and exact receipts repeated inside the batch
339
+ * remain valid redeliveries and do not trip this diagnostic guard.
340
+ */
341
+ var ProjectionOrderViolationError = class extends InfrastructureError {
342
+ projection;
343
+ eventId;
344
+ previousReceivedPosition;
345
+ receivedPosition;
346
+ constructor(projection, eventId, previousReceivedPosition, receivedPosition) {
347
+ super({
348
+ code: "PROJECTION_ORDER_VIOLATION",
349
+ message: `Projector(${projection}): event ${eventId} at ${receivedPosition} arrived after the later unprocessed position ${previousReceivedPosition} in the same batch. Partition or serialize the feed by aggregate source.`
350
+ });
351
+ this.projection = projection;
352
+ this.eventId = eventId;
353
+ this.previousReceivedPosition = previousReceivedPosition;
354
+ this.receivedPosition = receivedPosition;
355
+ }
356
+ };
357
+ /**
358
+ * Thrown when a source maps different event identities to one position, either
359
+ * inside the current batch or at the position stored as the projection's
360
+ * watermark. The checkpoint retains the identity of that one last-applied
361
+ * event, so the durable collision is provable without keeping an unbounded
362
+ * processed-event ledger. Positions behind the watermark remain governed by
363
+ * the source's one-logical-event-per-position contract.
364
+ */
365
+ var ProjectionIdentityViolationError = class extends InfrastructureError {
366
+ projection;
367
+ eventId;
368
+ recordedEventId;
369
+ position;
370
+ constructor(projection, eventId, recordedEventId, position) {
371
+ super({
372
+ code: "PROJECTION_IDENTITY_VIOLATION",
373
+ message: `Projector(${projection}): position ${position} was already associated with event ${recordedEventId}, but the source supplied event ${eventId} at the same position. A source must map exactly one logical event to each position.`
374
+ });
375
+ this.projection = projection;
376
+ this.eventId = eventId;
377
+ this.recordedEventId = recordedEventId;
378
+ this.position = position;
379
+ }
380
+ };
381
+ /**
382
+ * Thrown when one logical projection position keeps its event identity but its
383
+ * commit-boundary receipt changes. `commitSize` and
384
+ * `previousEventfulAggregateVersion` are part of the continuity proof, so a
385
+ * source must keep them immutable just like the eventId. Accepting a
386
+ * contradictory redelivery could hide an incomplete commit or predecessor.
387
+ */
388
+ var ProjectionReceiptViolationError = class extends InfrastructureError {
389
+ projection;
390
+ eventId;
391
+ recordedReceipt;
392
+ receivedReceipt;
393
+ constructor(projection, eventId, recordedReceipt, receivedReceipt) {
394
+ super({
395
+ code: "PROJECTION_RECEIPT_VIOLATION",
396
+ message: `Projector(${projection}): event ${eventId} changed its commit receipt at one logical position from ${recordedReceipt} to ${receivedReceipt}. A source must keep commitSize and previousEventfulAggregateVersion immutable.`
397
+ });
398
+ this.projection = projection;
399
+ this.eventId = eventId;
400
+ this.recordedReceipt = recordedReceipt;
401
+ this.receivedReceipt = receivedReceipt;
402
+ }
403
+ };
404
+ /** A malformed or non-JSON-safe message at an integration boundary. */
405
+ var InvalidIntegrationMessageError = class extends InfrastructureError {
406
+ path;
407
+ reason;
408
+ constructor(path, reason, cause) {
409
+ super({
410
+ code: "INVALID_INTEGRATION_MESSAGE",
411
+ message: `Invalid integration message at ${path}: ${reason}`,
412
+ cause
413
+ });
414
+ this.path = path;
415
+ this.reason = reason;
416
+ }
417
+ };
418
+ /** A malformed or non-JSON-safe command selected for durable delivery. */
419
+ var InvalidCommandMessageError = class extends InfrastructureError {
420
+ path;
421
+ reason;
422
+ constructor(path, reason, cause) {
423
+ super({
424
+ code: "INVALID_COMMAND_MESSAGE",
425
+ message: `Invalid command message at ${path}: ${reason}`,
426
+ cause
427
+ });
428
+ this.path = path;
429
+ this.reason = reason;
430
+ }
431
+ };
432
+ /**
433
+ * Thrown by `Entity` (constructor and `setState`), by the event-sourced
434
+ * fold (`apply` and replay), by the event constructors for the payload,
435
+ * and by the event metadata helpers (`createDomainEvent`'s
436
+ * `options.metadata`, `mergeMetadata`, `copyMetadata`) when the value
437
+ * carries an own `"__proto__"` data key:
438
+ * the shape `JSON.parse` produces for hostile DB rows or request bodies
439
+ * handed to reconstitute factories. Such a key can never be legitimate
440
+ * domain state; accepting it would hand a prototype-pollution payload to
441
+ * every downstream consumer that copies the state through `[[Set]]`
442
+ * (`Object.assign`, for-in assignment loops), and dropping it would be
443
+ * silent data mutation. The check looks at the root object only; nested
444
+ * objects are not walked, and a class instance is an ownership transfer
445
+ * that passes.
446
+ *
447
+ * Deliberately **not** a `DomainError` or `InfrastructureError` (same
448
+ * posture as {@link MissingHandlerError}): untrusted input reaching the
449
+ * domain layer unvalidated is a boundary bug, and a generic
450
+ * business-rule handler must not absorb it. Validate and strip untrusted
451
+ * input at the application edge; model genuinely arbitrary keys with a
452
+ * `Map`, not a plain object.
453
+ */
454
+ var HostileStateKeyError = class extends KitWiringError {
455
+ key;
456
+ constructor(key, subject = "Entity state") {
457
+ super("HOSTILE_STATE_KEY", `${subject} carries a hostile own "${key}" key, which can never be legitimate domain data. Validate and strip untrusted input at the boundary, or model arbitrary keys with a Map.`);
458
+ this.key = key;
459
+ }
460
+ };
461
+ /**
462
+ * Thrown by the `Entity` constructor when the id is not a non-blank
463
+ * string. That covers `null`, `undefined`, a blank string, and a
464
+ * non-string value that reached the constructor through a cast. An
465
+ * entity without a usable identity cannot be tracked, compared, or
466
+ * persisted, so the construction fails before any state is stored. A
467
+ * wiring error: a deterministic bug at the call site, never a domain
468
+ * rejection.
469
+ */
470
+ var MissingEntityIdError = class extends KitWiringError {
471
+ constructor(received) {
472
+ super("MISSING_ENTITY_ID", `Entity ID must be a non-blank string; received ${describeRejectedId(received)}.`);
473
+ }
474
+ };
475
+ function describeRejectedId(value) {
476
+ if (typeof value === "string") return JSON.stringify(value);
477
+ if (value === null) return "null";
478
+ if (value === void 0) return "undefined";
479
+ if (typeof value === "object") return Array.isArray(value) ? "array" : "object";
480
+ if (typeof value === "function") return "function";
481
+ return `${typeof value} ${String(value)}`;
482
+ }
483
+ /**
484
+ * Thrown when a number that is not a valid aggregate version reaches the
485
+ * kit: `toVersion`, `markReconstituted`, `setVersion`, and the post-commit
486
+ * acknowledgement all reject it. A version is a safe integer of at least
487
+ * zero, and a restore never moves below the current version. A wiring
488
+ * error: an adapter passed a corrupt row value or a wrong number, and
489
+ * the optimistic-concurrency cursor must not carry it. Not retryable.
490
+ */
491
+ var InvalidVersionError = class extends KitWiringError {
492
+ value;
493
+ reason;
494
+ constructor(value, reason) {
495
+ super("INVALID_VERSION", `Version ${String(value)} ${reason}. A version is a safe integer of at least zero; create one with toVersion(n) from the stored row value.`);
496
+ this.value = value;
497
+ this.reason = reason;
498
+ }
499
+ };
500
+ /**
501
+ * Thrown by `EventSourcedAggregate.replayHistory` when the replay target
502
+ * carries unflushed `pendingEvents`. Replaying persisted facts onto that
503
+ * instance would advance the version underneath decisions made against an
504
+ * older state and could later claim history the stream does not carry.
505
+ *
506
+ * Deliberately **not** a `DomainError` or `InfrastructureError` (same
507
+ * posture as {@link MissingHandlerError}): a deterministic programming
508
+ * bug in how the aggregate was constructed before the restore. It
509
+ * propagates as a throw instead of riding the replay methods' `Result`
510
+ * channel, so a generic corrupted-stream handler cannot absorb it.
511
+ * Reconstitution belongs on a bare instance: construct the aggregate
512
+ * without factory-recorded events or prior mutations, then restore.
513
+ *
514
+ * Each throw site carries the safe remedy in its `reason`. Persistence
515
+ * lifecycle state is intentionally not mutable through the aggregate API:
516
+ * commit an actually saved instance through application orchestration, or
517
+ * discard a dirty instance and replay into a fresh one.
518
+ */
519
+ var UnreplayableAggregateError = class extends KitWiringError {
520
+ aggregateId;
521
+ constructor(aggregateId, reason) {
522
+ super("UNREPLAYABLE_AGGREGATE", `Cannot replay onto aggregate ${aggregateId}: ${reason}. Reconstitute on a fresh instance (no factory-recorded events, no unpersisted mutations).`);
523
+ this.aggregateId = aggregateId;
524
+ }
525
+ };
526
+ /** The address the event names; a missing field falls back to the receiving aggregate. */
527
+ function describeEventAddress(options) {
528
+ const { expected, actual } = options;
529
+ return `${actual.aggregateType ?? expected.aggregateType} ${actual.aggregateId ?? expected.aggregateId}`;
530
+ }
531
+ /**
532
+ * Thrown by `EventSourcedAggregate.apply()` when a NEW event carries an
533
+ * `aggregateId` or `aggregateType` naming a different aggregate: a
534
+ * deterministic programming bug at the call site (a hand-built or
535
+ * copied event addressed elsewhere), caught before the event can be
536
+ * recorded and poison the own stream. Events with MISSING address
537
+ * fields do not trip this: `apply()` stamps them from the aggregate,
538
+ * the same guarantee `createEvent` gives. A wiring error, distinct
539
+ * from {@link ForeignEventError} on purpose: a wrong new event is a
540
+ * bug in today's code, a wrong PERSISTED row is corrupted or miswired
541
+ * infrastructure, and handlers for one must not absorb the other.
542
+ */
543
+ var MisaddressedEventError = class extends KitWiringError {
544
+ /** Address of the aggregate that received the event. */
545
+ expected;
546
+ /** Address fields the event carries. */
547
+ actual;
548
+ eventType;
549
+ constructor(options) {
550
+ super("MISADDRESSED_EVENT", `New event "${options.eventType}" is addressed to ${describeEventAddress(options)} but was applied on ${options.expected.aggregateType} ${options.expected.aggregateId}: fix the call site (createEvent stamps the right address).`);
551
+ this.expected = options.expected;
552
+ this.actual = options.actual;
553
+ this.eventType = options.eventType;
554
+ }
555
+ };
556
+ /**
557
+ * Thrown by `reconstituteAggregateFromSnapshot` when the `reconstitute`
558
+ * factory returns an aggregate at a version other than the snapshot
559
+ * version. The factory ignored the version parameter, usually a forgotten
560
+ * `markReconstituted(version)`. A wiring error in the snapshot model,
561
+ * never snapshot corruption: routing it into the discard-and-refold
562
+ * channel would mask it as perpetual silent refolding.
563
+ */
564
+ var SnapshotVersionNotRestoredError = class extends KitWiringError {
565
+ aggregateType;
566
+ aggregateId;
567
+ snapshotVersion;
568
+ restoredVersion;
569
+ constructor(options) {
570
+ super("SNAPSHOT_VERSION_NOT_RESTORED", `SnapshotModel.reconstitute for ${options.aggregateType} ${options.aggregateId} returned an aggregate at version ${options.restoredVersion} for a snapshot at version ${options.snapshotVersion}. Reconstitution must restore the persisted version; call markReconstituted(version) inside the aggregate factory.`);
571
+ this.aggregateType = options.aggregateType;
572
+ this.aggregateId = options.aggregateId;
573
+ this.snapshotVersion = options.snapshotVersion;
574
+ this.restoredVersion = options.restoredVersion;
575
+ }
576
+ };
577
+ /**
578
+ * The structural-integrity rejection for a stored snapshot. A consumer's
579
+ * adapter-owned `SnapshotModel` may throw it from migration or reconstitution
580
+ * when the blob could not have been produced by any version of the model
581
+ * (missing fields, impossible types, truncated data). An
582
+ * `InfrastructureError`, because corrupted persistence is a storage
583
+ * problem, never a business rejection; it is nevertheless RECOVERABLE
584
+ * by design: the repository catches it, discards the derived snapshot, and
585
+ * refolds from the authoritative event stream.
586
+ */
587
+ var SnapshotCorruptedError = class extends InfrastructureError {
588
+ constructor(message, cause) {
589
+ super({
590
+ code: "SNAPSHOT_CORRUPTED",
591
+ message,
592
+ cause
593
+ });
594
+ }
595
+ };
596
+ /**
597
+ * Thrown when an event reaches the aggregate's recording paths
598
+ * (`apply`, `setState`, `addDomainEvent`) without having been minted by
599
+ * the kit's constructors: `createDomainEvent`,
600
+ * `createDomainEventFromFacts`, `createUncommittedDomainEvent`, or the
601
+ * aggregate `createEvent` helper. Those constructors deep-freeze the
602
+ * event, defensively copy payload and metadata, and mark the result as
603
+ * minted. The mark has two tiers: a
604
+ * module-private one for events of this loaded copy of the kit, and a
605
+ * cooperative `Symbol.for` brand that a second loaded copy stamps and
606
+ * recognizes. Anything else (a hand-rolled literal, a shallow-frozen
607
+ * copy with mutable nested data) is rejected: a mutable event recorded
608
+ * next to a state change can silently diverge from it afterwards. A
609
+ * wiring error: deterministic bug at the call site, the remedy is
610
+ * minting through the constructors. The gate catches accidents, not
611
+ * adversaries: code in the same process can fake the brand.
612
+ */
613
+ var UnmintedEventError = class extends KitWiringError {
614
+ constructor(eventType) {
615
+ super("UNMINTED_EVENT", `Event "${eventType}" was not minted by a domain-event constructor or aggregate createEvent(...) helper. Those constructors deep-freeze the event and defensively copy payload and metadata; a mutable event could diverge from the state change it records.`);
616
+ }
617
+ };
618
+ /**
619
+ * Thrown by `recordPendingEvents` when the aggregate's pending-event list
620
+ * changes while its events are being stamped: a stamp provider that
621
+ * directly or transitively triggers a new decision on the same aggregate
622
+ * would otherwise have that decision silently discarded when recording
623
+ * replaces the pending list. Recording is atomic: when this guard fires,
624
+ * every decision (including the re-entrant one) remains unrecorded. A
625
+ * wiring error: deterministic bug at the call site, the remedy is keeping
626
+ * stamp providers free of domain decisions.
627
+ */
628
+ var ReentrantEventRecordingError = class extends KitWiringError {
629
+ constructor(aggregateId) {
630
+ super("REENTRANT_EVENT_RECORDING", `Pending events of aggregate ${aggregateId} changed while recordPendingEvents was stamping them. A stamp provider must not trigger new decisions on the aggregate being recorded; make every domain decision first, then record.`);
631
+ }
632
+ };
633
+ /**
634
+ * Thrown when two facts of one aggregate would carry the same `eventId`.
635
+ * Two causes, two sites: the aggregate rejects a recorded event that is
636
+ * already pending at the append, before the state moves; and
637
+ * `recordPendingEvents` rejects a stamp provider that returns one reused
638
+ * stamp (or repeats an explicit id). Either would mint two distinct facts
639
+ * sharing one identity, and downstream idempotent consumers keyed on
640
+ * `eventId` silently drop one of them. A wiring error: deterministic bug at
641
+ * the append site or in the stamp provider, the remedy is one fresh
642
+ * identity per fact.
643
+ */
644
+ var DuplicateEventIdError = class extends KitWiringError {
645
+ eventId;
646
+ constructor(aggregateId, eventId) {
647
+ super("DUPLICATE_EVENT_ID", `Two pending events of aggregate ${aggregateId} carry the same eventId "${eventId}". Each fact needs its own identity: append a recorded event once, and return a fresh stamp per decision from the stamp provider.`);
648
+ this.eventId = eventId;
649
+ }
650
+ };
651
+ /**
652
+ * Thrown when a recording would grow the pending list of an aggregate past
653
+ * `AggregateConfig.maxPendingEvents`. The check runs before the state
654
+ * moves, so the rejected decision records nothing and moves nothing. The
655
+ * limit is a modelling signal, not a runtime budget: a decision that emits
656
+ * hundreds of facts points at a missing aggregate boundary, and a retry
657
+ * repeats it. A wiring error: split the aggregate, or emit fewer facts
658
+ * per decision.
659
+ */
660
+ var PendingEventLimitExceededError = class extends KitWiringError {
661
+ aggregateType;
662
+ aggregateId;
663
+ limit;
664
+ pending;
665
+ added;
666
+ constructor(options) {
667
+ super("PENDING_EVENT_LIMIT_EXCEEDED", `Aggregate ${options.aggregateType}(${options.aggregateId}) holds ${options.pending} pending event(s) and cannot record ${options.added} more: maxPendingEvents is ${options.limit}. A decision that emits this many facts points at a missing aggregate boundary.`);
668
+ this.aggregateType = options.aggregateType;
669
+ this.aggregateId = options.aggregateId;
670
+ this.limit = options.limit;
671
+ this.pending = options.pending;
672
+ this.added = options.added;
673
+ }
674
+ };
675
+ /**
676
+ * Thrown by the post-commit acknowledgement of an aggregate when the
677
+ * committed batch is not the prefix of its pending events any more. The
678
+ * batch is longer than the pending list, or an event in it is not the
679
+ * pending event at the same position. Acknowledging such a batch would
680
+ * drop decisions the commit never persisted or keep events it did. The
681
+ * pending list stays untouched. A wiring error in application commit
682
+ * orchestration: acknowledge exactly the batch that was enrolled, once.
683
+ */
684
+ var PendingEventBatchMismatchError = class extends KitWiringError {
685
+ aggregateId;
686
+ batchLength;
687
+ pendingLength;
688
+ constructor(aggregateId, batchLength, pendingLength) {
689
+ super("PENDING_EVENT_BATCH_MISMATCH", `The committed batch of ${batchLength} event(s) is no longer the pending prefix of aggregate ${aggregateId} (${pendingLength} pending). Acknowledge exactly the batch that was enrolled, once.`);
690
+ this.aggregateId = aggregateId;
691
+ this.batchLength = batchLength;
692
+ this.pendingLength = pendingLength;
693
+ }
694
+ };
695
+ /**
696
+ * Thrown by persisted-event consumers (including `replayHistory` and
697
+ * `Projector`) when an event carries an
698
+ * `aggregateId` or `aggregateType` that names a different aggregate:
699
+ * the persisted row belongs to someone else (a miswired stream read,
700
+ * ids colliding across aggregate types, a corrupted store). An
701
+ * `InfrastructureError`, NOT a `DomainError` (same posture as
702
+ * {@link SnapshotSchemaMismatchError}): a wrong address is data
703
+ * corruption or wiring, never an expected business rejection, so it
704
+ * must not be absorbed by generic domain error handling or presented
705
+ * as a 4xx. It therefore PROPAGATES as a throw through the replay
706
+ * methods' `Result` contract (which reserves `Err` for `DomainError`),
707
+ * after the usual all-or-nothing rollback. History events without the
708
+ * optional address fields pass unchecked (the fields are optional on
709
+ * the event shape); new events are covered by
710
+ * {@link MisaddressedEventError}.
711
+ */
712
+ var ForeignEventError = class extends InfrastructureError {
713
+ /** Address of the aggregate that received the event. */
714
+ expected;
715
+ /** Address fields the event carries. */
716
+ actual;
717
+ eventType;
718
+ constructor(options) {
719
+ super({
720
+ code: "FOREIGN_EVENT",
721
+ message: `Persisted event "${options.eventType}" belongs to ${describeEventAddress(options)}, not to ${options.expected.aggregateType} ${options.expected.aggregateId}: the stream row addresses a different aggregate.`
722
+ });
723
+ this.expected = options.expected;
724
+ this.actual = options.actual;
725
+ this.eventType = options.eventType;
726
+ }
727
+ };
728
+ /**
729
+ * Thrown by a paged EventStore consumer when `readStream` returns no events
730
+ * even though its continuation cursor has not reached the pinned target.
731
+ * Such a page cannot advance and violates the EventStore port contract; a
732
+ * replay loop that merely continued would spin forever.
733
+ *
734
+ * This is a non-retryable infrastructure error: the persistence adapter
735
+ * deterministically contradicted its port contract, so retrying the same read
736
+ * is not a recovery policy. Run `createEventStoreContractTests` against the
737
+ * adapter and fix its windowing/continuation implementation.
738
+ */
739
+ var NonProgressingEventStreamPageError = class extends InfrastructureError {
740
+ aggregateType;
741
+ aggregateId;
742
+ fromVersion;
743
+ targetVersion;
744
+ constructor(options) {
745
+ super({
746
+ code: "NON_PROGRESSING_EVENT_STREAM_PAGE",
747
+ message: `EventStore returned no events for ${options.aggregateType}(${options.aggregateId}) after version ${options.fromVersion}, before pinned target version ${options.targetVersion}. The page cannot advance; run the EventStore contract suite and fix the adapter's continuation window.`
748
+ });
749
+ this.aggregateType = options.aggregateType;
750
+ this.aggregateId = options.aggregateId;
751
+ this.fromVersion = options.fromVersion;
752
+ this.targetVersion = options.targetVersion;
753
+ }
754
+ };
755
+ /**
756
+ * Thrown by a load recipe when the replayed aggregate does not end at the
757
+ * pinned stream head. Events carry no stream position, so the aggregate
758
+ * cannot detect a tail that overlaps the restored version or a page that
759
+ * lies outside the requested window; only the caller, which pinned the
760
+ * head, can compare. A snapshot catch-up passes only the events after the
761
+ * restored version, and the final version must equal the head.
762
+ *
763
+ * This is a non-retryable infrastructure error: the persistence adapter
764
+ * contradicted its port contract. Run `createEventStoreContractTests` and
765
+ * `createEsRepositoryContractTests` against the adapter and fix its
766
+ * windowing.
767
+ */
768
+ var ReplayHeadMismatchError = class extends InfrastructureError {
769
+ aggregateType;
770
+ aggregateId;
771
+ targetVersion;
772
+ actualVersion;
773
+ constructor(options) {
774
+ super({
775
+ code: "REPLAY_HEAD_MISMATCH",
776
+ message: `Replay of ${options.aggregateType}(${options.aggregateId}) ended at version ${options.actualVersion}, not at the pinned stream head ${options.targetVersion}. The tail overlapped the restored version or a page lay outside the requested window; pass only the events after the restored version.`
777
+ });
778
+ this.aggregateType = options.aggregateType;
779
+ this.aggregateId = options.aggregateId;
780
+ this.targetVersion = options.targetVersion;
781
+ this.actualVersion = options.actualVersion;
782
+ }
783
+ };
784
+ /**
785
+ * Thrown when an event harvested from an aggregate cannot be safely composed
786
+ * into a commit envelope, or when an outbox can prove that accepting a
787
+ * candidate would violate its event identity/source chain. Harvest failures
788
+ * include missing `aggregateId` / `aggregateType` (downstream routing would
789
+ * break), or an
790
+ * eventful persisted aggregate did not advance its version (two commits
791
+ * would receive the same source position). These programming bugs are
792
+ * deterministic and fail identically on every retry.
793
+ *
794
+ * Deliberately **not** an {@link InfrastructureError} (same reasoning as
795
+ * {@link MissingHandlerError}): this is a deterministic programming error,
796
+ * not a transient storage failure. A `catch (e instanceof InfrastructureError)`
797
+ * retry handler, or a retrying `TransactionScope`, must NOT mask it or loop on
798
+ * it forever; it should crash loud so the caller misuse surfaces in
799
+ * development. This is why `withCommit` throws it directly and
800
+ * `UnitOfWork.run` passes it through unchanged instead of wrapping it in
801
+ * `CommitError`.
802
+ */
803
+ var EventHarvestError = class extends KitWiringError {
804
+ eventType;
805
+ constructor(message, eventType) {
806
+ super("EVENT_HARVEST_FAILED", message);
807
+ this.eventType = eventType;
808
+ }
809
+ };
810
+ /**
811
+ * Thrown at bootstrap when the global key of a kit capability registry
812
+ * already holds a value that is not a registry: another module claimed
813
+ * the key. The kit neither shares that value nor overwrites it, because a
814
+ * silent replacement would break whichever module owned the key first. A
815
+ * wiring error in the host process; the remedy is one owner per key.
816
+ */
817
+ var CapabilityRegistryConflictError = class extends KitWiringError {
818
+ key;
819
+ constructor(key) {
820
+ super("CAPABILITY_REGISTRY_CONFLICT", `The global key ${String(key)} holds a value that is not a capability registry of this package. Another module claimed the key; the kit refuses to share or overwrite it.`);
821
+ this.key = key;
822
+ }
823
+ };
824
+ /**
825
+ * Thrown when a kit operation receives an instance that this package did
826
+ * not construct: a structural lookalike, a repository DTO, or an instance
827
+ * from an incompatible copy of the package. Such an instance carries none
828
+ * of the kit-managed capabilities the operation needs. A wiring error:
829
+ * extend the kit's base classes and run one compatible package copy.
830
+ */
831
+ var UnmanagedInstanceError = class extends KitWiringError {
832
+ operation;
833
+ subject;
834
+ instanceId;
835
+ constructor(operation, subject, instanceId, detail) {
836
+ super("UNMANAGED_INSTANCE", `${operation} requires an instance constructed by this package; ${instanceId === void 0 ? subject : `${subject} ${String(instanceId)}`} carries no kit-managed capability. Construct it through this package and run one compatible package copy; a structural lookalike or an instance from another copy cannot be managed.` + (detail === void 0 ? "" : ` ${detail}`));
837
+ this.operation = operation;
838
+ this.subject = subject;
839
+ this.instanceId = instanceId;
840
+ }
841
+ };
842
+ /**
843
+ * Shared guard for the loud-rejection contract on own `__proto__` data
844
+ * keys (the shape `JSON.parse` produces for hostile rows, bodies, or
845
+ * envelopes): used by `Entity` state copies and the event metadata
846
+ * helpers. One implementation so the contract cannot drift.
847
+ * Module-internal export; not part of the package entries.
848
+ */
849
+ function assertNoHostileOwnProtoKey(value, subject) {
850
+ if (Object.hasOwn(value, "__proto__")) throw new HostileStateKeyError("__proto__", subject);
851
+ }
852
+ /**
853
+ * Produced by the in-memory `CommandBus` / `QueryBus` when a message is
854
+ * dispatched for a type no handler was registered under: a wiring bug
855
+ * (typo in the type string, missing `register` call at bootstrap), not
856
+ * a domain or infrastructure failure.
857
+ *
858
+ * Carries the `WIRING` category (same crash-loud family as
859
+ * {@link MissingHandlerError}), and since v3 it is THROWN by `execute`
860
+ * and `executeUnsafe` alike, never delivered through the error channel:
861
+ * the channel carries expected failures a registered handler produced,
862
+ * and a generic err-branch must not absorb a mis-wired bus. Catch it
863
+ * only at a boundary that turns bugs into 500s.
864
+ */
865
+ var UnregisteredHandlerError = class extends KitWiringError {
866
+ busKind;
867
+ messageType;
868
+ constructor(options) {
869
+ super("UNREGISTERED_HANDLER", `No handler registered for ${options.busKind} type: ${options.messageType}`);
870
+ this.busKind = options.busKind;
871
+ this.messageType = options.messageType;
872
+ }
873
+ };
874
+ /**
875
+ * Produced by `CommandBus.register` / `QueryBus.register` when a handler
876
+ * is registered for a type that already has one: silent replacement would
877
+ * turn the first handler into dead code with no signal, so the wiring bug
878
+ * surfaces at registration time. Same crash-loud family as
879
+ * {@link UnregisteredHandlerError}; catch it only at a boundary that
880
+ * turns bugs into 500s.
881
+ */
882
+ var DuplicateHandlerRegistrationError = class extends KitWiringError {
883
+ busKind;
884
+ messageType;
885
+ constructor(options) {
886
+ super("DUPLICATE_HANDLER_REGISTRATION", `A handler for ${options.busKind} type "${options.messageType}" is already registered; the duplicate would silently shadow the first. Register each type exactly once at bootstrap.`);
887
+ this.busKind = options.busKind;
888
+ this.messageType = options.messageType;
889
+ }
890
+ };
891
+ /**
892
+ * Produced by the in-memory `CommandBus` / `QueryBus` when the configured
893
+ * `mapExpectedError` policy fails while classifying a registered handler's
894
+ * failure, either by throwing or by returning an invalid decision. A broken
895
+ * mapper is a wiring bug: letting its failure propagate bare would
896
+ * replace the handler's original failure entirely, and the rest of the
897
+ * kit is fastidious about never letting a secondary failure mask the
898
+ * primary one (`RollbackError.rollbackCause`, the neutralized observers).
899
+ *
900
+ * The handler's original failure is preserved as `cause` (so cause-chain
901
+ * walks, retryability checks, and error-type mapping keep working) and
902
+ * the mapper's own failure rides along as {@link mapperCause}.
903
+ *
904
+ * Carries the `WIRING` category (same crash-loud family as
905
+ * {@link MissingHandlerError} and {@link UnregisteredHandlerError}): it is
906
+ * thrown, never delivered through the error channel.
907
+ */
908
+ var ErrorMapperFailedError = class extends KitWiringError {
909
+ busKind;
910
+ /** The mapper failure or invalid-decision diagnostic. */
911
+ mapperCause;
912
+ constructor(options) {
913
+ super("ERROR_MAPPER_FAILED", `The ${options.busKind} bus mapExpectedError policy failed while classifying a handler failure. The original handler error is preserved as cause; the mapper's own failure as mapperCause.`, options.handlerError);
914
+ this.busKind = options.busKind;
915
+ this.mapperCause = options.mapperError;
916
+ }
917
+ };
918
+ /**
919
+ * Thrown at the end of a `UnitOfWork.run` when an aggregate that was
920
+ * loaded into the identity map changed but no `update` intent was registered.
921
+ * Without this guard the changed state or pending events would be silently
922
+ * dropped.
923
+ *
924
+ * Deliberately **not** an `InfrastructureError` (same posture as
925
+ * {@link MissingHandlerError}): a programming bug that must crash loud,
926
+ * not be absorbed by a generic infrastructure-error handler. The throw
927
+ * happens inside the transaction, so the unit of work rolls back and
928
+ * leaves no partial state.
929
+ *
930
+ * **Scope of the guard.** A best-effort runtime safety net, not a proof.
931
+ * It sees aggregates that repository adapters register through
932
+ * `tracking.trackLoaded` and detects ordinary state changes through the version
933
+ * captured at load. The pending-event count remains a second guard for an
934
+ * invalid event-only mutation that did not advance the version. A freshly
935
+ * created aggregate that is never passed to `add` is invisible to the kit.
936
+ *
937
+ * An append-only repository installs no `update`, so for its aggregate the
938
+ * message names the rule instead: a loaded append-only aggregate must not
939
+ * change.
940
+ */
941
+ var UnenrolledChangesError = class extends KitWiringError {
942
+ aggregateId;
943
+ constructor(aggregateId, options = {}) {
944
+ super("UNENROLLED_CHANGES", `Aggregate ${aggregateId} was loaded and changed in this unit of work, ` + (options.appendOnly ? "but its repository is append-only and installs no update. An append-only aggregate must not change after add." : "but no update intent was registered. Call repository.update(aggregate) after the final domain decision so state and events flush together."));
945
+ this.aggregateId = aggregateId;
946
+ }
947
+ };
948
+ /**
949
+ * Thrown when an aggregate removed within the current unit of work is added,
950
+ * updated, or tracked again in the same operation. Removal is final within an
951
+ * operation; writing afterwards would resurrect the row, which is always a
952
+ * use-case bug.
953
+ *
954
+ * Carries the `WIRING` category (same reasoning as
955
+ * {@link MissingHandlerError}): a programming bug that should crash
956
+ * loud, not be absorbed by a generic infrastructure-error handler.
957
+ */
958
+ var AggregateDeletedError = class extends KitWiringError {
959
+ aggregateId;
960
+ constructor(aggregateId) {
961
+ super("AGGREGATE_DELETED", `Aggregate ${aggregateId} was removed in this unit of work and cannot be added, updated, tracked, or removed through another instance again. Removal is final within an operation. A repeated remove of the SAME instance is an accepted no-op; if the aggregate must remain, do not remove it.`);
962
+ this.aggregateId = aggregateId;
963
+ }
964
+ };
965
+ var AggregateNotFoundError = class extends InfrastructureError {
966
+ aggregateType;
967
+ id;
968
+ constructor(options) {
969
+ super({
970
+ code: "AGGREGATE_NOT_FOUND",
971
+ message: `Aggregate not found: ${options.aggregateType}(${options.id})`,
972
+ cause: options.cause
973
+ });
974
+ this.aggregateType = options.aggregateType;
975
+ this.id = options.id;
976
+ }
977
+ };
978
+ var DuplicateAggregateError = class extends InfrastructureError {
979
+ aggregateType;
980
+ aggregateId;
981
+ constructor(options) {
982
+ super({
983
+ code: "DUPLICATE_AGGREGATE",
984
+ message: `Duplicate aggregate: ${options.aggregateType}(${options.aggregateId}) already exists`,
985
+ cause: options.cause
986
+ });
987
+ this.aggregateType = options.aggregateType;
988
+ this.aggregateId = options.aggregateId;
989
+ }
990
+ };
991
+ var SnapshotSchemaMismatchError = class extends InfrastructureError {
992
+ aggregateType;
993
+ aggregateId;
994
+ expectedSchemaVersion;
995
+ actualSchemaVersion;
996
+ constructor(options) {
997
+ super({
998
+ code: "SNAPSHOT_SCHEMA_MISMATCH",
999
+ message: `Snapshot schema mismatch on ${options.aggregateType}(${options.aggregateId}): the snapshot model expects schema ${options.expectedSchemaVersion}, the stored snapshot carries ${options.actualSchemaVersion}. Override the model's migrate function to upgrade old snapshots, or discard the snapshot and refold from the full event stream.`
1000
+ });
1001
+ this.aggregateType = options.aggregateType;
1002
+ this.aggregateId = options.aggregateId;
1003
+ this.expectedSchemaVersion = options.expectedSchemaVersion;
1004
+ this.actualSchemaVersion = options.actualSchemaVersion;
1005
+ }
1006
+ };
1007
+ /**
1008
+ * Surfaced by a Unit-of-Work flush when the aggregate's expected version does
1009
+ * not match the version currently persisted: i.e. another writer
1010
+ * updated the aggregate concurrently. The canonical optimistic-
1011
+ * concurrency signal; the App-Service typically reloads, re-applies
1012
+ * the use case, and retries, or surfaces HTTP 409 to the caller.
1013
+ *
1014
+ * **Retry means a FRESH unit of work** (a new `UnitOfWork.run()` /
1015
+ * `withCommit` invocation): reload, re-apply, and register `update` again. Do NOT catch this
1016
+ * inside the same `run()` callback and continue: the failed aggregate
1017
+ * is already enrolled (its events would be committed for a write that
1018
+ * never happened) and the identity map still serves the same stale
1019
+ * instance to any in-place "reload".
1020
+ *
1021
+ * `InfrastructureError` because the persistence layer (not a domain
1022
+ * rule) detects the race. Its `retryable` follows the reason, so the
1023
+ * `isRetryable` predicate from `@shirudo/base-error` picks up every reason
1024
+ * but `version_unchanged`, which names a defect of the adapter.
1025
+ */
1026
+ var ConcurrencyConflictError = class extends InfrastructureError {
1027
+ aggregateType;
1028
+ aggregateId;
1029
+ expectedVersion;
1030
+ /** The stored version, or `null` when none exists to name. */
1031
+ actualVersion;
1032
+ reason;
1033
+ constructor(options) {
1034
+ super({
1035
+ code: "CONCURRENCY_CONFLICT",
1036
+ message: concurrencyConflictMessage(options),
1037
+ cause: options.cause,
1038
+ retryable: options.reason !== "version_unchanged"
1039
+ });
1040
+ this.aggregateType = options.aggregateType;
1041
+ this.aggregateId = options.aggregateId;
1042
+ this.expectedVersion = options.expectedVersion;
1043
+ this.actualVersion = options.actualVersion ?? null;
1044
+ this.reason = options.reason;
1045
+ }
1046
+ };
1047
+ function concurrencyConflictMessage(options) {
1048
+ const site = `${options.aggregateType}(${options.aggregateId})`;
1049
+ switch (options.reason) {
1050
+ case "stale_version": return `Concurrency conflict on ${site}: expected version ${options.expectedVersion}, stored version ${options.actualVersion}.`;
1051
+ case "version_unchanged": return `Concurrency conflict on ${site}: the write matched nothing, although the stored version is ${options.actualVersion}. Its statement carries a condition beyond the version, or its version read answered from a transaction snapshot. Drop the extra condition, or read the version with a locking read, for example SELECT ... FOR SHARE.`;
1052
+ case "aggregate_absent": return `Concurrency conflict on ${site}: expected version ${options.expectedVersion}, but the aggregate no longer exists.`;
1053
+ case "version_unknown": return `Concurrency conflict on ${site}: expected version ${options.expectedVersion}. The stored version could not be read; the read failure is the cause.`;
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Thrown by `IdempotencyStore.claim()` when the same idempotency key
1058
+ * arrives with a DIFFERENT command fingerprint than the one it was
1059
+ * first claimed with: the caller is reusing a key for a different
1060
+ * command. Replaying the stored outcome would answer a question that
1061
+ * was never asked; rejecting is the only safe reaction.
1062
+ *
1063
+ * `InfrastructureError` because the store detects the collision, same
1064
+ * delegation model as {@link DuplicateAggregateError}. NOT retryable:
1065
+ * re-sending the same mismatched pair cannot succeed. Map it to an
1066
+ * unprocessable/conflict application outcome.
1067
+ */
1068
+ var IdempotencyKeyReuseError = class extends InfrastructureError {
1069
+ key;
1070
+ storedFingerprint;
1071
+ receivedFingerprint;
1072
+ constructor(options) {
1073
+ super({
1074
+ code: "IDEMPOTENCY_KEY_REUSE",
1075
+ message: `Idempotency key reuse on "${options.key}": stored fingerprint ${options.storedFingerprint}, received ${options.receivedFingerprint}`,
1076
+ cause: options.cause
1077
+ });
1078
+ this.key = options.key;
1079
+ this.storedFingerprint = options.storedFingerprint;
1080
+ this.receivedFingerprint = options.receivedFingerprint;
1081
+ }
1082
+ };
1083
+ /**
1084
+ * Thrown when a leased idempotency owner tries to renew, complete, or
1085
+ * reconcile through a claim token that no longer owns the key. The usual
1086
+ * cause is lease expiry followed by a successful takeover. The stale
1087
+ * execution must abort before its transaction commits; retrying starts from
1088
+ * a fresh claim or replays the winner.
1089
+ */
1090
+ var IdempotencyClaimLostError = class extends InfrastructureError {
1091
+ key;
1092
+ token;
1093
+ constructor(options) {
1094
+ super({
1095
+ code: "IDEMPOTENCY_CLAIM_LOST",
1096
+ message: `Idempotency claim for key "${options.key}" no longer belongs to token "${options.token}"`,
1097
+ cause: options.cause,
1098
+ retryable: true
1099
+ });
1100
+ this.key = options.key;
1101
+ this.token = options.token;
1102
+ }
1103
+ };
1104
+ /**
1105
+ * Thrown by `IdempotencyStore.claim()` when the key is already claimed
1106
+ * by an execution that has not completed yet: the first delivery of the
1107
+ * command is still running (or crashed mid-flight on a
1108
+ * non-transactional store). Retryable by design: a later retry either
1109
+ * finds the completed outcome and replays it, or finds the claim
1110
+ * released (rolled back) and executes fresh. `RetryingTransactionScope`
1111
+ * picks this up through the `retryable` flag without extra wiring.
1112
+ */
1113
+ var IdempotencyInFlightError = class extends InfrastructureError {
1114
+ key;
1115
+ constructor(options) {
1116
+ super({
1117
+ code: "IDEMPOTENCY_IN_FLIGHT",
1118
+ message: `Idempotency key "${options.key}" is claimed by an execution that has not completed yet`,
1119
+ cause: options.cause,
1120
+ retryable: true
1121
+ });
1122
+ this.key = options.key;
1123
+ }
1124
+ };
1125
+ /**
1126
+ * An expired staged outcome cannot be replayed or discarded until the
1127
+ * application checks the authoritative write model. Immediate retry without
1128
+ * that evidence cannot make progress, so this error is deliberately not
1129
+ * marked retryable.
1130
+ */
1131
+ var IdempotencyReconciliationRequiredError = class extends InfrastructureError {
1132
+ key;
1133
+ fingerprint;
1134
+ token;
1135
+ expiredAt;
1136
+ constructor(options) {
1137
+ super({
1138
+ code: "IDEMPOTENCY_RECONCILIATION_REQUIRED",
1139
+ message: `Idempotency key "${options.key}" has an expired staged outcome; consult the authoritative write model before confirming or releasing it`
1140
+ });
1141
+ this.key = options.key;
1142
+ this.fingerprint = options.fingerprint;
1143
+ this.token = options.token;
1144
+ this.expiredAt = options.expiredAt;
1145
+ }
1146
+ };
1147
+ /**
1148
+ * Thrown by `IdempotencyStore.complete()` when no pending claim exists
1149
+ * for the key: `complete` ran without a preceding successful `claim`
1150
+ * in the same execution, or against a key whose claim was already
1151
+ * completed or abandoned. Always a wiring bug in hand-rolled
1152
+ * orchestration (`withIdempotentCommit` cannot produce it), hence the
1153
+ * crash-loud category.
1154
+ */
1155
+ var IdempotencyCompletionWithoutClaimError = class extends KitWiringError {
1156
+ key;
1157
+ constructor(key) {
1158
+ super("IDEMPOTENCY_COMPLETED_WITHOUT_CLAIM", `IdempotencyStore.complete() called for key "${key}" without a pending claim; call claim() first (or use withIdempotentCommit)`);
1159
+ this.key = key;
1160
+ }
1161
+ };
1162
+
1163
+ //#endregion
1164
+ export { NonProgressingEventStreamPageError as A, SnapshotSchemaMismatchError as B, InvalidIntegrationMessageError as C, MissingEntityIdError as D, MisaddressedEventError as E, ProjectionOrderViolationError as F, UnprojectableEventError as G, UnenrolledChangesError as H, ProjectionReceiptViolationError as I, assertNoHostileOwnProtoKey as J, UnregisteredHandlerError as K, ReentrantEventRecordingError as L, PendingEventLimitExceededError as M, ProjectionGapError as N, MissingFoldError as O, ProjectionIdentityViolationError as P, ReplayHeadMismatchError as R, InvalidCommandMessageError as S, KitWiringError as T, UnmanagedInstanceError as U, SnapshotVersionNotRestoredError as V, UnmintedEventError as W, isInfrastructureErrorLike as X, isDomainErrorLike as Y, isWiringErrorLike as Z, IdempotencyInFlightError as _, DirectStateMutationError as a, InMemoryCapacityExceededError as b, DuplicateEventIdError as c, EventHarvestError as d, FoldReturnedNoStateError as f, IdempotencyCompletionWithoutClaimError as g, IdempotencyClaimLostError as h, ConcurrencyConflictError as i, PendingEventBatchMismatchError as j, MissingHandlerError as k, DuplicateHandlerRegistrationError as l, HostileStateKeyError as m, AggregateNotFoundError as n, DomainError as o, ForeignEventError as p, UnreplayableAggregateError as q, CapabilityRegistryConflictError as r, DuplicateAggregateError as s, AggregateDeletedError as t, ErrorMapperFailedError as u, IdempotencyKeyReuseError as v, InvalidVersionError as w, InfrastructureError as x, IdempotencyReconciliationRequiredError as y, SnapshotCorruptedError as z };
1165
+ //# sourceMappingURL=kit-errors.js.map