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