@shirudo/ddd-kit 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts DELETED
@@ -1,1309 +0,0 @@
1
- import { R as Result } from './result-CDTS-G0l.js';
2
-
3
- type Id<Tag extends string> = string & {
4
- readonly __brand: Tag;
5
- };
6
- interface IdGenerator {
7
- next: <T extends string>() => Id<T>;
8
- }
9
-
10
- type Version = number & {
11
- readonly __v: true;
12
- };
13
- /**
14
- * Metadata associated with a domain event for traceability and correlation.
15
- * Used in event-driven architectures to track event flow across services.
16
- */
17
- interface EventMetadata {
18
- /**
19
- * Correlation ID for tracing events across multiple services/components.
20
- * Typically used to group related events in a distributed system.
21
- */
22
- correlationId?: string;
23
- /**
24
- * Causation ID referencing the event or command that caused this event.
25
- * Used to build event chains and understand causality.
26
- */
27
- causationId?: string;
28
- /**
29
- * User ID of the person or system that triggered the event.
30
- */
31
- userId?: string;
32
- /**
33
- * Source service or component that produced the event.
34
- */
35
- source?: string;
36
- /**
37
- * Additional custom metadata fields.
38
- * Allows extensibility for domain-specific metadata.
39
- */
40
- [key: string]: unknown;
41
- }
42
- /**
43
- * Domain Event represents something meaningful that happened in the domain.
44
- * Events are immutable and carry information about what occurred.
45
- *
46
- * @template T - The event type name (e.g., "OrderCreated")
47
- * @template P - The event payload type
48
- */
49
- interface DomainEvent<T extends string, P> {
50
- /**
51
- * The type of the event, used for routing and handling.
52
- */
53
- type: T;
54
- /**
55
- * The event payload containing the domain data.
56
- */
57
- payload: P;
58
- /**
59
- * Timestamp when the event occurred.
60
- */
61
- occurredAt: Date;
62
- /**
63
- * Event schema version for handling schema evolution.
64
- * Defaults to 1 if not specified. Higher versions indicate schema changes.
65
- */
66
- version?: number;
67
- /**
68
- * Optional metadata for traceability, correlation, and auditing.
69
- * Includes correlationId, causationId, userId, source, and custom fields.
70
- */
71
- metadata?: EventMetadata;
72
- }
73
- /**
74
- * Marker interface for Aggregate Roots.
75
- *
76
- * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).
77
- * It represents the aggregate externally and is the only object that external code
78
- * is allowed to hold references to. All access to child entities within the aggregate
79
- * must go through the Aggregate Root.
80
- *
81
- * An Aggregate consists of:
82
- * - One Aggregate Root (Entity with id + version)
83
- * - Optional child entities (Entities with id, but no own version)
84
- * - Optional value objects
85
- *
86
- * The Aggregate Root has identity (id) and version for optimistic concurrency control.
87
- * Child entities exist only within the aggregate boundary and are versioned through
88
- * the Aggregate Root.
89
- *
90
- * @template TId - The type of the aggregate root identifier
91
- *
92
- * @example
93
- * ```typescript
94
- * class Order extends AggregateBase<OrderState, OrderId> implements AggregateRoot<OrderId> {
95
- * // Order is an Aggregate Root (an Entity)
96
- * // OrderState contains child entities (e.g., OrderItem) and value objects
97
- * }
98
- * ```
99
- */
100
- interface AggregateRoot<TId extends Id<string>> {
101
- /**
102
- * Unique identifier of the aggregate root entity.
103
- */
104
- readonly id: TId;
105
- /**
106
- * Version number for optimistic concurrency control.
107
- * Incremented on each state change to detect concurrent modifications.
108
- * This version applies to the entire aggregate, including all child entities.
109
- */
110
- readonly version: Version;
111
- }
112
- /**
113
- * Structural interface representing an aggregate with state and events.
114
- * Used for type constraints in repositories and other infrastructure code.
115
- *
116
- * @template State - The type of the aggregate state
117
- * @template Evt - The union type of all domain events
118
- */
119
- interface Aggregate<State, Evt extends DomainEvent<string, unknown>> {
120
- state: Readonly<State>;
121
- version: Version;
122
- pendingEvents: ReadonlyArray<Evt>;
123
- }
124
- declare function aggregate<State, Evt extends DomainEvent<string, unknown>>(state: State, version?: Version): Aggregate<State, Evt>;
125
- declare function withEvent<S, E extends DomainEvent<string, unknown>>(agg: Aggregate<S, E>, evt: E): Aggregate<S, E>;
126
- declare function bump<S, E extends DomainEvent<string, unknown>>(agg: Aggregate<S, E>): Aggregate<S, E>;
127
- /**
128
- * Creates a domain event with default values.
129
- * Sets occurredAt to current date and version to 1 if not provided.
130
- *
131
- * @param type - The event type
132
- * @param payload - The event payload
133
- * @param options - Optional event configuration
134
- * @returns A domain event
135
- *
136
- * @example
137
- * ```typescript
138
- * const event = createDomainEvent("OrderCreated", { orderId: "123" });
139
- * ```
140
- */
141
- declare function createDomainEvent<T extends string, P>(type: T, payload: P, options?: {
142
- occurredAt?: Date;
143
- version?: number;
144
- metadata?: EventMetadata;
145
- }): DomainEvent<T, P>;
146
- /**
147
- * Creates a domain event with metadata for traceability.
148
- * Convenience function for creating events with correlation and causation IDs.
149
- *
150
- * @param type - The event type
151
- * @param payload - The event payload
152
- * @param metadata - Event metadata for traceability
153
- * @param options - Optional event configuration
154
- * @returns A domain event with metadata
155
- *
156
- * @example
157
- * ```typescript
158
- * const event = createDomainEventWithMetadata(
159
- * "OrderCreated",
160
- * { orderId: "123" },
161
- * {
162
- * correlationId: "corr-123",
163
- * causationId: "cmd-456",
164
- * userId: "user-789"
165
- * }
166
- * );
167
- * ```
168
- */
169
- declare function createDomainEventWithMetadata<T extends string, P>(type: T, payload: P, metadata: EventMetadata, options?: {
170
- occurredAt?: Date;
171
- version?: number;
172
- }): DomainEvent<T, P>;
173
- /**
174
- * Copies metadata from a source event to a new event.
175
- * Useful for maintaining correlation chains in event-driven architectures.
176
- *
177
- * @param sourceEvent - The source event to copy metadata from
178
- * @param additionalMetadata - Additional metadata to merge in
179
- * @returns Event metadata with copied and merged values
180
- *
181
- * @example
182
- * ```typescript
183
- * const newEvent = createDomainEvent(
184
- * "OrderShipped",
185
- * { orderId: "123" },
186
- * {
187
- * metadata: copyMetadata(previousEvent, { causationId: previousEvent.type })
188
- * }
189
- * );
190
- * ```
191
- */
192
- declare function copyMetadata(sourceEvent: DomainEvent<string, unknown>, additionalMetadata?: Partial<EventMetadata>): EventMetadata;
193
- /**
194
- * Merges multiple metadata objects into one.
195
- * Later metadata objects override earlier ones for the same keys.
196
- *
197
- * @param metadataObjects - Array of metadata objects to merge
198
- * @returns Merged event metadata
199
- *
200
- * @example
201
- * ```typescript
202
- * const metadata = mergeMetadata(
203
- * { correlationId: "corr-123" },
204
- * { userId: "user-456" },
205
- * { source: "order-service" }
206
- * );
207
- * ```
208
- */
209
- declare function mergeMetadata(...metadataObjects: Array<EventMetadata | undefined>): EventMetadata;
210
- /**
211
- * Snapshot of an aggregate state at a specific point in time.
212
- * Used for optimizing event replay by starting from a snapshot
213
- * instead of replaying all events from the beginning.
214
- *
215
- * @template TState - The type of the aggregate state
216
- */
217
- interface AggregateSnapshot<TState> {
218
- /**
219
- * The state of the aggregate at the time of the snapshot.
220
- */
221
- state: TState;
222
- /**
223
- * The version of the aggregate when the snapshot was taken.
224
- */
225
- version: Version;
226
- /**
227
- * Timestamp when the snapshot was created.
228
- */
229
- snapshotAt: Date;
230
- }
231
- /**
232
- * Checks if two aggregates are the same (same ID and version).
233
- * Useful for optimistic concurrency control checks.
234
- *
235
- * @param a - First aggregate
236
- * @param b - Second aggregate
237
- * @returns true if both aggregates have the same ID and version
238
- *
239
- * @example
240
- * ```typescript
241
- * const aggregate1 = await repository.getById(id);
242
- * // ... some operations ...
243
- * const aggregate2 = await repository.getById(id);
244
- *
245
- * if (!sameAggregate(aggregate1, aggregate2)) {
246
- * throw new Error("Aggregate was modified by another process");
247
- * }
248
- * ```
249
- */
250
- declare function sameAggregate<TId extends Id<string>>(a: {
251
- id: TId;
252
- version: Version;
253
- }, b: {
254
- id: TId;
255
- version: Version;
256
- }): boolean;
257
-
258
- /**
259
- * Configuration options for AggregateBase behavior.
260
- */
261
- interface AggregateConfig {
262
- /**
263
- * Whether to automatically bump the version when state changes.
264
- * Defaults to false. Set to true for automatic versioning.
265
- */
266
- autoVersionBump?: boolean;
267
- }
268
- /**
269
- * Base class for creating Aggregate Roots (Entities) without Event Sourcing.
270
- *
271
- * This class creates an Entity that serves as the Aggregate Root. The Aggregate Root
272
- * is the parent Entity of the aggregate and represents it externally. It has identity
273
- * (id) and version for optimistic concurrency control.
274
- *
275
- * The aggregate state (`TState`) contains:
276
- * - Child entities (Entities with id, but no own version)
277
- * - Value objects (immutable objects)
278
- *
279
- * All changes to child entities are versioned through the Aggregate Root. The version
280
- * applies to the entire aggregate, including all child entities.
281
- *
282
- * Provides core functionality:
283
- * - ID and Version management (for Optimistic Concurrency Control)
284
- * - State management (containing child entities and value objects)
285
- * - Snapshot support for performance optimization
286
- *
287
- * Implements `AggregateRoot<TId>` to mark this as an Aggregate Root Entity.
288
- *
289
- * Use this class when you don't need Event Sourcing but still want
290
- * aggregate patterns with versioning and state management.
291
- *
292
- * @template TState - The type of the aggregate state (contains child entities and value objects)
293
- * @template TId - The type of the aggregate root identifier
294
- *
295
- * @example
296
- * ```typescript
297
- * // Order is an Aggregate Root (an Entity)
298
- * class Order extends AggregateBase<OrderState, OrderId> implements AggregateRoot<OrderId> {
299
- * constructor(id: OrderId, initialState: OrderState) {
300
- * super(id, initialState);
301
- * }
302
- *
303
- * confirm(): void {
304
- * this._state = { ...this._state, status: "confirmed" };
305
- * this.bumpVersion(); // Versions the entire aggregate
306
- * }
307
- * }
308
- * ```
309
- */
310
- declare abstract class AggregateBase<TState, TId extends Id<string>> implements AggregateRoot<TId> {
311
- readonly id: TId;
312
- version: Version;
313
- private readonly _config;
314
- private readonly _autoVersionBump;
315
- get state(): TState;
316
- /**
317
- * The state is 'protected' so that only the subclass can change it.
318
- * Subclasses can mutate this directly or use helper methods.
319
- */
320
- protected _state: TState;
321
- protected constructor(id: TId, initialState: TState, config?: AggregateConfig);
322
- /**
323
- * Manually bumps the aggregate version.
324
- * Call this after state changes for Optimistic Concurrency Control.
325
- *
326
- * If `autoVersionBump` is enabled, this is called automatically
327
- * when using `setState()`.
328
- */
329
- protected bumpVersion(): void;
330
- /**
331
- * Sets the state and optionally bumps the version automatically.
332
- * This is a convenience method for state mutations.
333
- *
334
- * @param newState - The new state
335
- * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)
336
- */
337
- protected setState(newState: TState, bumpVersion?: boolean): void;
338
- /**
339
- * Creates a snapshot of the current aggregate state.
340
- * Useful for performance optimization, backup/restore, and audit trails.
341
- *
342
- * @returns A snapshot containing the current state and version
343
- *
344
- * @example
345
- * ```typescript
346
- * const snapshot = aggregate.createSnapshot();
347
- * await snapshotRepository.save(aggregate.id, snapshot);
348
- * ```
349
- */
350
- createSnapshot(): AggregateSnapshot<TState>;
351
- /**
352
- * Restores the aggregate from a snapshot.
353
- * This is useful for loading aggregates from snapshots instead of
354
- * rebuilding them from scratch.
355
- *
356
- * @param snapshot - The snapshot to restore from
357
- *
358
- * @example
359
- * ```typescript
360
- * const snapshot = await snapshotRepository.getLatest(aggregateId);
361
- * aggregate.restoreFromSnapshot(snapshot);
362
- * ```
363
- */
364
- restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void;
365
- }
366
-
367
- type Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;
368
- /**
369
- * Extended configuration options for AggregateEventSourced behavior.
370
- */
371
- interface AggregateEventSourcedConfig extends AggregateConfig {
372
- /**
373
- * Whether to automatically bump the version when applying new events.
374
- * Defaults to true. Set to false to manually control versioning.
375
- */
376
- autoVersionBump?: boolean;
377
- }
378
- /**
379
- * Base class for Event-Sourced Aggregate Roots (Entities).
380
- *
381
- * Extends `AggregateBase` to create an Aggregate Root Entity with Event Sourcing capabilities.
382
- * The Aggregate Root is the parent Entity of the aggregate and represents it externally.
383
- *
384
- * The aggregate state (`TState`) contains:
385
- * - Child entities (Entities with id, but no own version)
386
- * - Value objects (immutable objects)
387
- *
388
- * All changes to child entities are versioned through the Aggregate Root. The version
389
- * applies to the entire aggregate, including all child entities.
390
- *
391
- * Extends `AggregateBase` with Event Sourcing capabilities:
392
- * - Event tracking (pendingEvents)
393
- * - Event handlers for state transitions
394
- * - Event validation
395
- * - History replay
396
- *
397
- * Use this class when you want Event Sourcing with full event tracking
398
- * and replay capabilities.
399
- *
400
- * @template TState - The type of the aggregate state (contains child entities and value objects)
401
- * @template TEvent - The union type of all domain events
402
- * @template TId - The type of the aggregate root identifier
403
- *
404
- * @example
405
- * ```typescript
406
- * // Order is an Aggregate Root (an Entity) with Event Sourcing
407
- * class Order extends AggregateEventSourced<OrderState, OrderEvent, OrderId> {
408
- * confirm(): void {
409
- * this.apply(createDomainEvent("OrderConfirmed", {}));
410
- * }
411
- *
412
- * protected readonly handlers = {
413
- * OrderConfirmed: (state: OrderState): OrderState => ({
414
- * ...state,
415
- * status: "confirmed",
416
- * }),
417
- * };
418
- * }
419
- * ```
420
- */
421
- declare abstract class AggregateEventSourced<TState, TEvent extends DomainEvent<string, unknown>, TId extends Id<string>> extends AggregateBase<TState, TId> {
422
- private readonly _eventConfig;
423
- private readonly _eventAutoVersionBump;
424
- private readonly _pendingEvents;
425
- protected constructor(id: TId, initialState: TState, config?: AggregateEventSourcedConfig);
426
- /**
427
- * Returns a read-only list of new, not-yet-persisted events.
428
- */
429
- get pendingEvents(): ReadonlyArray<TEvent>;
430
- /**
431
- * Clears the list of pending events.
432
- * Typically called after the events have been persisted.
433
- */
434
- clearPendingEvents(): void;
435
- /**
436
- * Validates an event before it is applied.
437
- * Override this method to add custom validation logic.
438
- * Return `ok(true)` if the event is valid, `err(message)` otherwise.
439
- *
440
- * @param event - The event to validate
441
- * @returns Result indicating if the event is valid
442
- *
443
- * @example
444
- * ```typescript
445
- * protected validateEvent(event: OrderEvent): Result<true, string> {
446
- * if (event.type === "OrderShipped" && this.state.status !== "confirmed") {
447
- * return err("Order must be confirmed before shipping");
448
- * }
449
- * return ok(true);
450
- * }
451
- * ```
452
- */
453
- protected validateEvent(_event: TEvent): Result<true, string>;
454
- /**
455
- * Applies an event to change the state and adds it
456
- * to the list of pending events.
457
- * Returns a Result type instead of throwing an error.
458
- *
459
- * @param event - The domain event to apply
460
- * @param isNew - Indicates whether the event is new (and needs to be persisted)
461
- * or if it is being loaded from history
462
- * @returns Result<void, string> - ok if successful, err with error message if validation fails or handler is missing
463
- */
464
- protected apply(event: TEvent, isNew?: boolean): Result<void, string>;
465
- /**
466
- * Applies an event to change the state and adds it
467
- * to the list of pending events.
468
- * Throws an error if validation fails or handler is missing.
469
- *
470
- * @param event - The domain event to apply
471
- * @param isNew - Indicates whether the event is new (and needs to be persisted)
472
- * or if it is being loaded from history
473
- * @throws Error if event validation fails or handler is missing
474
- */
475
- protected applyUnsafe(event: TEvent, isNew?: boolean): void;
476
- /**
477
- * Manually bumps the aggregate version.
478
- * Only needed if `autoVersionBump` is disabled.
479
- */
480
- protected bumpVersion(): void;
481
- /**
482
- * Reconstitutes the aggregate from an event history.
483
- * Sets the version to the number of events in the history.
484
- *
485
- * @param history - An ordered list of past events
486
- */
487
- loadFromHistory(history: TEvent[]): Result<void, string>;
488
- /**
489
- * Checks if the aggregate has any pending events.
490
- *
491
- * @returns true if there are pending events, false otherwise
492
- */
493
- hasPendingEvents(): boolean;
494
- /**
495
- * Returns the number of pending events.
496
- *
497
- * @returns The count of pending events
498
- */
499
- getEventCount(): number;
500
- /**
501
- * Returns the latest pending event, if any.
502
- *
503
- * @returns The most recent event or undefined if no events exist
504
- */
505
- getLatestEvent(): TEvent | undefined;
506
- /**
507
- * Restores the aggregate from a snapshot and applies events that occurred after the snapshot.
508
- * This is more efficient than replaying all events from the beginning.
509
- *
510
- * @param snapshot - The snapshot to restore from
511
- * @param eventsAfterSnapshot - Events that occurred after the snapshot was taken
512
- *
513
- * @example
514
- * ```typescript
515
- * const snapshot = await snapshotRepository.getLatest(aggregateId);
516
- * const eventsAfter = await eventStore.getEventsAfter(aggregateId, snapshot.version);
517
- * aggregate.restoreFromSnapshotWithEvents(snapshot, eventsAfter);
518
- * ```
519
- */
520
- restoreFromSnapshotWithEvents(snapshot: AggregateSnapshot<TState>, eventsAfterSnapshot: TEvent[]): Result<void, string>;
521
- /**
522
- * A map of event types to their corresponding handlers.
523
- * Subclasses MUST implement this property.
524
- */
525
- protected abstract readonly handlers: {
526
- [K in TEvent["type"]]: Handler<TState, Extract<TEvent, {
527
- type: K;
528
- }>>;
529
- };
530
- }
531
-
532
- /**
533
- * Marker interface for Commands.
534
- * Commands represent write operations that change system state.
535
- * They should be immutable and contain all data needed to perform the operation.
536
- *
537
- * This interface can be used as a type marker even when using external frameworks
538
- * (e.g., RabbitMQ, AWS SQS) to ensure type safety across different bus implementations.
539
- *
540
- * @example
541
- * ```typescript
542
- * type CreateOrderCommand = Command & {
543
- * type: "CreateOrder";
544
- * customerId: string;
545
- * items: OrderItem[];
546
- * };
547
- * ```
548
- *
549
- * @example Using with external frameworks (RabbitMQ, etc.)
550
- * ```typescript
551
- * // Define command using Command marker
552
- * type CreateOrderCommand = Command & {
553
- * type: "CreateOrder";
554
- * customerId: string;
555
- * };
556
- *
557
- * // Handler can be typed with CommandHandler even for external frameworks
558
- * const handler: CommandHandler<CreateOrderCommand, OrderId> = async (cmd) => {
559
- * // ... handler logic
560
- * return ok(orderId);
561
- * };
562
- *
563
- * // Register with RabbitMQ or other external bus
564
- * rabbitMQChannel.consume("order.commands", async (message) => {
565
- * const command = JSON.parse(message.content) as CreateOrderCommand;
566
- * const result = await handler(command);
567
- * // ... handle result
568
- * });
569
- * ```
570
- */
571
- interface Command {
572
- readonly type: string;
573
- }
574
- /**
575
- * Handler for executing commands.
576
- * Commands return Result for explicit error handling.
577
- * Commands may modify system state and should be idempotent when possible.
578
- *
579
- * This type can be used to mark handlers even when using external frameworks
580
- * (e.g., RabbitMQ, AWS SQS, Kafka) to ensure type safety and consistency.
581
- *
582
- * @template C - The command type (must extend Command)
583
- * @template R - The result type
584
- *
585
- * @example
586
- * ```typescript
587
- * const handler: CommandHandler<CreateOrderCommand, OrderId> = async (cmd) => {
588
- * const order = Order.create(cmd.customerId, cmd.items);
589
- * await repository.save(order);
590
- * return ok(order.id);
591
- * };
592
- * ```
593
- *
594
- * @example Using with external frameworks
595
- * ```typescript
596
- * // Handler typed with CommandHandler for type safety
597
- * const createOrderHandler: CommandHandler<CreateOrderCommand, OrderId> = async (cmd) => {
598
- * // ... handler logic
599
- * return ok(orderId);
600
- * };
601
- *
602
- * // Can be used with any external bus/framework
603
- * // RabbitMQ example:
604
- * rabbitMQChannel.consume("commands", async (msg) => {
605
- * const command = JSON.parse(msg.content) as CreateOrderCommand;
606
- * const result = await createOrderHandler(command);
607
- * // ... handle result
608
- * });
609
- *
610
- * // AWS SQS example:
611
- * sqs.receiveMessage({ QueueUrl: "..." }, async (err, data) => {
612
- * const command = JSON.parse(data.Messages[0].Body) as CreateOrderCommand;
613
- * const result = await createOrderHandler(command);
614
- * // ... handle result
615
- * });
616
- * ```
617
- */
618
- type CommandHandler<C extends Command, R> = (cmd: C) => Promise<Result<R, string>>;
619
-
620
- /**
621
- * Command Bus interface for dispatching commands to their handlers.
622
- * Provides a centralized way to execute commands with handler registration.
623
- *
624
- * @example
625
- * ```typescript
626
- * const bus = new CommandBus();
627
- * bus.register("CreateOrder", createOrderHandler);
628
- *
629
- * const result = await bus.execute({
630
- * type: "CreateOrder",
631
- * customerId: "123",
632
- * items: [...]
633
- * });
634
- * ```
635
- */
636
- interface ICommandBus {
637
- /**
638
- * Executes a command by dispatching it to the registered handler.
639
- *
640
- * @param command - The command to execute
641
- * @returns Result containing the success value or error message
642
- */
643
- execute<C extends Command, R>(command: C): Promise<Result<R, string>>;
644
- /**
645
- * Registers a handler for a specific command type.
646
- *
647
- * @param commandType - The command type to register the handler for
648
- * @param handler - The handler function for this command type
649
- */
650
- register<C extends Command, R>(commandType: C["type"], handler: CommandHandler<C, R>): void;
651
- }
652
- /**
653
- * Simple in-memory command bus implementation.
654
- * Handlers are stored in a Map and dispatched based on command type.
655
- *
656
- * **Note:** This is a basic implementation suitable for development and simple use cases.
657
- * For production environments, consider implementing or using a more feature-rich bus that includes:
658
- * - Middleware/Pipeline support (logging, validation, authorization)
659
- * - Error handling and retry logic
660
- * - Timeout handling
661
- * - Metrics and observability
662
- * - Transaction management
663
- * - Dead letter queue support
664
- *
665
- * The `CommandHandler` type can still be used with external production-grade buses
666
- * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.
667
- *
668
- * @example
669
- * ```typescript
670
- * const bus = new CommandBus();
671
- * bus.register("CreateOrder", async (cmd) => {
672
- * // ... handler logic
673
- * return ok(orderId);
674
- * });
675
- *
676
- * const result = await bus.execute({ type: "CreateOrder", ... });
677
- * ```
678
- */
679
- declare class CommandBus implements ICommandBus {
680
- private readonly handlers;
681
- register<C extends Command, R>(commandType: C["type"], handler: CommandHandler<C, R>): void;
682
- execute<C extends Command, R>(command: C): Promise<Result<R, string>>;
683
- }
684
-
685
- /**
686
- * Event handler function type for subscribing to domain events.
687
- *
688
- * @template Evt - The type of domain event
689
- */
690
- type EventHandler<Evt> = (event: Evt) => Promise<void> | void;
691
- /**
692
- * Event Bus interface for publishing and subscribing to domain events.
693
- * Supports multiple subscribers per event type (pub/sub pattern).
694
- *
695
- * @template Evt - The type of domain events
696
- *
697
- * @example
698
- * ```typescript
699
- * const bus = new EventBus<OrderEvent>();
700
- *
701
- * // Subscribe to specific event types
702
- * bus.subscribe("OrderCreated", async (event) => {
703
- * await sendEmail(event.payload.customerId);
704
- * });
705
- *
706
- * bus.subscribe("OrderShipped", async (event) => {
707
- * await updateInventory(event.payload.orderId);
708
- * });
709
- *
710
- * // Publish events
711
- * await bus.publish([orderCreatedEvent, orderShippedEvent]);
712
- * ```
713
- */
714
- interface EventBus<Evt> {
715
- /**
716
- * Publishes events to all subscribed handlers.
717
- * All handlers for each event type will be called.
718
- *
719
- * @param events - Array of events to publish
720
- */
721
- publish: (events: ReadonlyArray<Evt>) => Promise<void>;
722
- /**
723
- * Subscribes a handler to a specific event type.
724
- * Multiple handlers can subscribe to the same event type.
725
- *
726
- * @param eventType - The event type to subscribe to
727
- * @param handler - The handler function to call when events of this type are published
728
- * @returns A function to unsubscribe the handler
729
- *
730
- * @example
731
- * ```typescript
732
- * const unsubscribe = bus.subscribe("OrderCreated", async (event) => {
733
- * console.log("Order created:", event.payload.orderId);
734
- * });
735
- *
736
- * // Later: unsubscribe
737
- * unsubscribe();
738
- * ```
739
- */
740
- subscribe: <T extends Evt>(eventType: string, handler: EventHandler<T>) => () => void;
741
- }
742
- interface Outbox<Evt> {
743
- add: (events: ReadonlyArray<Evt>) => Promise<void>;
744
- }
745
- interface Clock {
746
- now: () => Date;
747
- }
748
-
749
- interface UnitOfWork {
750
- transactional<T>(fn: () => Promise<T>): Promise<T>;
751
- }
752
- type RepoProvider<R> = (uow: UnitOfWork) => R;
753
-
754
- /**
755
- * Helper function for executing commands within a transaction.
756
- * Handles event persistence via outbox and optional event bus publishing.
757
- *
758
- * @param deps - Dependencies including outbox, optional event bus, and unit of work
759
- * @param fn - Function that returns result and events
760
- * @returns The result wrapped in a transaction
761
- *
762
- * @example
763
- * ```typescript
764
- * const result = await withCommit(
765
- * { outbox, bus, uow },
766
- * async () => {
767
- * const order = Order.create(customerId, items);
768
- * await repository.save(order);
769
- * return {
770
- * result: order.id,
771
- * events: order.pendingEvents
772
- * };
773
- * }
774
- * );
775
- * ```
776
- */
777
- declare function withCommit<Evt, R>(deps: {
778
- outbox: Outbox<Evt>;
779
- bus?: EventBus<Evt>;
780
- uow: UnitOfWork;
781
- }, fn: () => Promise<{
782
- result: R;
783
- events: ReadonlyArray<Evt>;
784
- }>): Promise<R>;
785
-
786
- /**
787
- * Marker interface for Queries.
788
- * Queries represent read operations that don't change system state.
789
- * They should be immutable and contain all data needed to perform the read.
790
- *
791
- * This interface can be used as a type marker even when using external frameworks
792
- * (e.g., RabbitMQ, AWS SQS) to ensure type safety across different bus implementations.
793
- *
794
- * @example
795
- * ```typescript
796
- * type GetOrderQuery = Query & {
797
- * type: "GetOrder";
798
- * orderId: OrderId;
799
- * };
800
- * ```
801
- *
802
- * @example Using with external frameworks
803
- * ```typescript
804
- * type GetOrderQuery = Query & {
805
- * type: "GetOrder";
806
- * orderId: OrderId;
807
- * };
808
- *
809
- * // Handler typed with QueryHandler for type safety
810
- * const handler: QueryHandler<GetOrderQuery, Order | null> = async (query) => {
811
- * return await repository.getById(query.orderId);
812
- * };
813
- *
814
- * // Can be used with any external framework
815
- * rabbitMQChannel.consume("queries", async (message) => {
816
- * const query = JSON.parse(message.content) as GetOrderQuery;
817
- * const result = await handler(query);
818
- * // ... handle result
819
- * });
820
- * ```
821
- */
822
- interface Query {
823
- readonly type: string;
824
- }
825
- /**
826
- * Handler for executing queries.
827
- * Queries return data directly (no Result type) as read operations
828
- * are not expected to fail in normal circumstances.
829
- * Queries should not modify system state and can be cached.
830
- *
831
- * This type can be used to mark handlers even when using external frameworks
832
- * (e.g., RabbitMQ, AWS SQS, Kafka) to ensure type safety and consistency.
833
- *
834
- * @template Q - The query type (must extend Query)
835
- * @template R - The result type
836
- *
837
- * @example
838
- * ```typescript
839
- * const handler: QueryHandler<GetOrderQuery, Order | null> = async (query) => {
840
- * return await repository.getById(query.orderId);
841
- * };
842
- * ```
843
- *
844
- * @example Using with external frameworks
845
- * ```typescript
846
- * // Handler typed with QueryHandler for type safety
847
- * const getOrderHandler: QueryHandler<GetOrderQuery, Order | null> = async (query) => {
848
- * return await repository.getById(query.orderId);
849
- * };
850
- *
851
- * // Can be used with any external bus/framework
852
- * rabbitMQChannel.consume("queries", async (msg) => {
853
- * const query = JSON.parse(msg.content) as GetOrderQuery;
854
- * const result = await getOrderHandler(query);
855
- * // ... handle result
856
- * });
857
- * ```
858
- */
859
- type QueryHandler<Q extends Query, R> = (query: Q) => Promise<R>;
860
-
861
- /**
862
- * Query Bus interface for dispatching queries to their handlers.
863
- * Provides a centralized way to execute queries with handler registration.
864
- *
865
- * @example
866
- * ```typescript
867
- * const bus = new QueryBus();
868
- * bus.register("GetOrder", getOrderHandler);
869
- *
870
- * const order = await bus.execute({
871
- * type: "GetOrder",
872
- * orderId: "123"
873
- * });
874
- * ```
875
- */
876
- interface IQueryBus {
877
- /**
878
- * Executes a query by dispatching it to the registered handler.
879
- * Returns a Result type instead of throwing an error.
880
- *
881
- * @param query - The query to execute
882
- * @returns Result containing the query result if successful, or an error message if no handler is registered
883
- */
884
- execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;
885
- /**
886
- * Executes a query by dispatching it to the registered handler.
887
- * Throws an error if no handler is registered.
888
- *
889
- * @param query - The query to execute
890
- * @returns The query result
891
- * @throws Error if no handler is registered for the query type
892
- */
893
- executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;
894
- /**
895
- * Registers a handler for a specific query type.
896
- *
897
- * @param queryType - The query type to register the handler for
898
- * @param handler - The handler function for this query type
899
- */
900
- register<Q extends Query, R>(queryType: Q["type"], handler: QueryHandler<Q, R>): void;
901
- }
902
- /**
903
- * Type map for query types to their return types.
904
- * Used to improve type inference in QueryBus.
905
- */
906
- type QueryTypeMap = Record<string, unknown>;
907
- /**
908
- * Simple in-memory query bus implementation.
909
- * Handlers are stored in a Map and dispatched based on query type.
910
- *
911
- * **Note:** This is a basic implementation suitable for development and simple use cases.
912
- * For production environments, consider implementing or using a more feature-rich bus that includes:
913
- * - Middleware/Pipeline support (logging, caching, rate limiting)
914
- * - Error handling
915
- * - Timeout handling
916
- * - Metrics and observability
917
- * - Query result caching
918
- * - Rate limiting
919
- *
920
- * The `QueryHandler` type can still be used with external production-grade buses
921
- * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.
922
- *
923
- * @example
924
- * ```typescript
925
- * const bus = new QueryBus();
926
- * bus.register("GetOrder", async (query) => {
927
- * return await repository.getById(query.orderId);
928
- * });
929
- *
930
- * const order = await bus.execute({ type: "GetOrder", orderId: "123" });
931
- * ```
932
- */
933
- declare class QueryBus<TMap extends QueryTypeMap = QueryTypeMap> implements IQueryBus {
934
- private readonly handlers;
935
- register<Q extends Query, R>(queryType: Q["type"], handler: QueryHandler<Q, R>): void;
936
- execute<Q extends Query & {
937
- type: keyof TMap;
938
- }>(query: Q): Promise<Result<TMap[Q["type"]], string>>;
939
- execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;
940
- executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;
941
- }
942
-
943
- /**
944
- * Guard function that validates a condition and returns a Result.
945
- * Returns `ok(true)` if the condition is met, otherwise `err(error)`.
946
- *
947
- * @param cond - The condition to check
948
- * @param error - Error message if condition fails
949
- * @returns Result<true, string>
950
- *
951
- * @example
952
- * ```typescript
953
- * const result = guard(id.length > 0, "ID cannot be empty");
954
- * if (!result.ok) {
955
- * return err(result.error);
956
- * }
957
- * ```
958
- */
959
- declare function guard(cond: boolean, error: string): Result<true, string>;
960
-
961
- /**
962
- * Interface for entities with identity.
963
- *
964
- * In Domain-Driven Design, there are two types of entities:
965
- *
966
- * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.
967
- * - Has identity (id) and version
968
- * - Implemented by classes extending `AggregateBase` or `AggregateEventSourced`
969
- * - Represents the aggregate externally
970
- * - Loaded/saved through repositories
971
- *
972
- * 2. **Child Entities**: Entities within an aggregate.
973
- * - Have identity (id), but no own version
974
- * - Exist only within the aggregate boundary
975
- * - Versioned through the Aggregate Root
976
- * - Cannot be referenced directly from outside the aggregate
977
- *
978
- * This interface is used for child entities within aggregates. The Aggregate Root
979
- * also implements this interface (through `AggregateRoot<TId>`), but additionally
980
- * has version management.
981
- *
982
- * @template TId - The type of the entity identifier
983
- *
984
- * @example
985
- * ```typescript
986
- * // Child Entity within an aggregate
987
- * type OrderItem = Entity<ItemId> & {
988
- * productId: string;
989
- * quantity: number;
990
- * };
991
- *
992
- * // Aggregate Root (also an Entity, but with version)
993
- * class Order extends AggregateBase<OrderState, OrderId>
994
- * implements AggregateRoot<OrderId> {
995
- * // Order is an Entity (the Aggregate Root)
996
- * // OrderState contains OrderItem (child entities)
997
- * }
998
- * ```
999
- */
1000
- interface Entity<TId> {
1001
- readonly id: TId;
1002
- }
1003
- /**
1004
- * Checks if two entities have the same ID.
1005
- * Works with any object that has an 'id' property.
1006
- *
1007
- * @param a - First entity
1008
- * @param b - Second entity
1009
- * @returns true if both entities have the same ID, false otherwise
1010
- *
1011
- * @example
1012
- * ```typescript
1013
- * const item1: OrderItem = { id: itemId1, productId: "prod-1", quantity: 2 };
1014
- * const item2: OrderItem = { id: itemId2, productId: "prod-2", quantity: 1 };
1015
- *
1016
- * sameEntity(item1, item2); // false
1017
- * sameEntity(item1, item1); // true
1018
- * ```
1019
- */
1020
- declare function sameEntity<TId>(a: {
1021
- id: TId;
1022
- }, b: {
1023
- id: TId;
1024
- }): boolean;
1025
- /**
1026
- * Finds an entity by ID in a collection.
1027
- * Returns undefined if not found.
1028
- *
1029
- * @param entities - Array of entities to search
1030
- * @param id - The ID to search for
1031
- * @returns The entity if found, undefined otherwise
1032
- *
1033
- * @example
1034
- * ```typescript
1035
- * const items: OrderItem[] = [
1036
- * { id: itemId1, productId: "prod-1", quantity: 2 },
1037
- * { id: itemId2, productId: "prod-2", quantity: 1 }
1038
- * ];
1039
- *
1040
- * const item = findEntityById(items, itemId1);
1041
- * // item is { id: itemId1, productId: "prod-1", quantity: 2 }
1042
- * ```
1043
- */
1044
- declare function findEntityById<TId, T extends {
1045
- id: TId;
1046
- }>(entities: T[], id: TId): T | undefined;
1047
- /**
1048
- * Checks if an entity with the given ID exists in the collection.
1049
- *
1050
- * @param entities - Array of entities to search
1051
- * @param id - The ID to check for
1052
- * @returns true if an entity with the ID exists, false otherwise
1053
- *
1054
- * @example
1055
- * ```typescript
1056
- * const items: OrderItem[] = [
1057
- * { id: itemId1, productId: "prod-1", quantity: 2 }
1058
- * ];
1059
- *
1060
- * hasEntityId(items, itemId1); // true
1061
- * hasEntityId(items, itemId2); // false
1062
- * ```
1063
- */
1064
- declare function hasEntityId<TId, T extends {
1065
- id: TId;
1066
- }>(entities: T[], id: TId): boolean;
1067
- /**
1068
- * Removes an entity with the given ID from the collection.
1069
- * Returns a new array without the entity.
1070
- *
1071
- * @param entities - Array of entities
1072
- * @param id - The ID of the entity to remove
1073
- * @returns A new array without the entity with the given ID
1074
- *
1075
- * @example
1076
- * ```typescript
1077
- * const items: OrderItem[] = [
1078
- * { id: itemId1, productId: "prod-1", quantity: 2 },
1079
- * { id: itemId2, productId: "prod-2", quantity: 1 }
1080
- * ];
1081
- *
1082
- * const updated = removeEntityById(items, itemId1);
1083
- * // updated is [{ id: itemId2, productId: "prod-2", quantity: 1 }]
1084
- * ```
1085
- */
1086
- declare function removeEntityById<TId, T extends {
1087
- id: TId;
1088
- }>(entities: T[], id: TId): T[];
1089
- /**
1090
- * Updates an entity with the given ID in the collection.
1091
- * Returns a new array with the updated entity.
1092
- * If the entity is not found, returns the original array unchanged.
1093
- *
1094
- * @param entities - Array of entities
1095
- * @param id - The ID of the entity to update
1096
- * @param updater - Function that takes the entity and returns the updated entity
1097
- * @returns A new array with the updated entity
1098
- *
1099
- * @example
1100
- * ```typescript
1101
- * const items: OrderItem[] = [
1102
- * { id: itemId1, productId: "prod-1", quantity: 2 }
1103
- * ];
1104
- *
1105
- * const updated = updateEntityById(items, itemId1, (item) => ({
1106
- * ...item,
1107
- * quantity: item.quantity + 1
1108
- * }));
1109
- * // updated is [{ id: itemId1, productId: "prod-1", quantity: 3 }]
1110
- * ```
1111
- */
1112
- declare function updateEntityById<TId, T extends {
1113
- id: TId;
1114
- }>(entities: T[], id: TId, updater: (entity: T) => T): T[];
1115
- /**
1116
- * Replaces an entity with the given ID in the collection.
1117
- * Returns a new array with the replaced entity.
1118
- * If the entity is not found, returns the original array unchanged.
1119
- *
1120
- * @param entities - Array of entities
1121
- * @param id - The ID of the entity to replace
1122
- * @param replacement - The replacement entity
1123
- * @returns A new array with the replaced entity
1124
- *
1125
- * @example
1126
- * ```typescript
1127
- * const items: OrderItem[] = [
1128
- * { id: itemId1, productId: "prod-1", quantity: 2 }
1129
- * ];
1130
- *
1131
- * const updated = replaceEntityById(items, itemId1, {
1132
- * id: itemId1,
1133
- * productId: "prod-1",
1134
- * quantity: 5
1135
- * });
1136
- * ```
1137
- */
1138
- declare function replaceEntityById<TId, T extends {
1139
- id: TId;
1140
- }>(entities: T[], id: TId, replacement: T): T[];
1141
- /**
1142
- * Extracts all IDs from a collection of entities.
1143
- *
1144
- * @param entities - Array of entities
1145
- * @returns Array of entity IDs
1146
- *
1147
- * @example
1148
- * ```typescript
1149
- * const items: OrderItem[] = [
1150
- * { id: itemId1, productId: "prod-1", quantity: 2 },
1151
- * { id: itemId2, productId: "prod-2", quantity: 1 }
1152
- * ];
1153
- *
1154
- * const ids = entityIds(items);
1155
- * // ids is [itemId1, itemId2]
1156
- * ```
1157
- */
1158
- declare function entityIds<TId, T extends {
1159
- id: TId;
1160
- }>(entities: T[]): TId[];
1161
-
1162
- /**
1163
- * Simple in-memory event bus implementation.
1164
- * Supports multiple subscribers per event type (pub/sub pattern).
1165
- *
1166
- * @template Evt - The type of domain events (must extend DomainEvent)
1167
- *
1168
- * @example
1169
- * ```typescript
1170
- * const bus = new EventBusImpl<OrderEvent>();
1171
- *
1172
- * bus.subscribe("OrderCreated", async (event) => {
1173
- * await sendEmail(event.payload.customerId);
1174
- * });
1175
- *
1176
- * bus.subscribe("OrderCreated", async (event) => {
1177
- * await logEvent(event);
1178
- * });
1179
- *
1180
- * await bus.publish([orderCreatedEvent]);
1181
- * // Both handlers will be called
1182
- * ```
1183
- */
1184
- declare class EventBusImpl<Evt extends DomainEvent<string, unknown>> implements EventBus<Evt> {
1185
- private readonly handlers;
1186
- subscribe<T extends Evt>(eventType: string, handler: EventHandler<T>): () => void;
1187
- publish(events: ReadonlyArray<Evt>): Promise<void>;
1188
- }
1189
-
1190
- /**
1191
- * A Specification is a named, standalone object that represents a business rule for a query.
1192
- * It is "translatable" into a concrete database query.
1193
- */
1194
- interface ISpecification<T> {
1195
- readonly _type: T;
1196
- }
1197
-
1198
- /**
1199
- * Repository interface for Aggregate Roots (Entities).
1200
- *
1201
- * Repositories work exclusively with Aggregate Root Entities. The Aggregate Root
1202
- * is the Entity that represents the aggregate externally and is the only object
1203
- * that can be loaded/saved through repositories.
1204
- *
1205
- * When loading an Aggregate Root, all child entities and value objects within
1206
- * the aggregate state are loaded as well. When saving, the entire aggregate
1207
- * (including all child entities) is persisted as a unit.
1208
- *
1209
- * Child entities cannot be loaded or saved independently - they exist only
1210
- * within the aggregate boundary and are managed through the Aggregate Root.
1211
- *
1212
- * @template TState - The type of the aggregate state (contains child entities and value objects)
1213
- * @template TEvent - The union type of all domain events
1214
- * @template TAgg - The aggregate root type (must be an Aggregate Root Entity)
1215
- * @template TId - The type of the aggregate root identifier
1216
- */
1217
- interface IRepository<TState, TEvent extends DomainEvent<string, unknown>, TAgg extends AggregateRoot<TId> & Aggregate<TState, TEvent>, TId extends Id<string>> {
1218
- getById(id: TId): Promise<TAgg | null>;
1219
- findOne(spec: ISpecification<TAgg>): Promise<TAgg | null>;
1220
- find(spec: ISpecification<TAgg>): Promise<TAgg[]>;
1221
- save(aggregate: TAgg): Promise<void>;
1222
- delete(id: TId): Promise<void>;
1223
- }
1224
-
1225
- type ValueObject<T> = Readonly<T>;
1226
- /**
1227
- * Creates a deeply immutable value object from the given data.
1228
- * All nested objects and arrays are frozen recursively.
1229
- *
1230
- * @param t - The data to convert into a value object
1231
- * @returns A deeply frozen, immutable value object
1232
- *
1233
- * @example
1234
- * ```typescript
1235
- * const address = vo({
1236
- * street: "Main St",
1237
- * city: "Berlin",
1238
- * coordinates: { lat: 52.5, lng: 13.4 }
1239
- * });
1240
- * // address.coordinates.lat = 99; // ❌ Error: Cannot assign to read-only property
1241
- * ```
1242
- */
1243
- declare function vo<T>(t: T): ValueObject<T>;
1244
- /**
1245
- * Compares two value objects for equality based on their values.
1246
- * Uses deep equality comparison by serializing both objects to JSON.
1247
- *
1248
- * Note: This is a simple implementation. For production use with complex objects,
1249
- * consider using a more robust deep equality library or implementing custom equality logic.
1250
- *
1251
- * @param a - First value object
1252
- * @param b - Second value object
1253
- * @returns true if both objects have the same values, false otherwise
1254
- *
1255
- * @example
1256
- * ```typescript
1257
- * const money1 = vo({ amount: 100, currency: "USD" });
1258
- * const money2 = vo({ amount: 100, currency: "USD" });
1259
- * voEquals(money1, money2); // true
1260
- * ```
1261
- */
1262
- declare function voEquals<T>(a: ValueObject<T>, b: ValueObject<T>): boolean;
1263
- /**
1264
- * Creates a value object with optional validation.
1265
- * Returns a Result type instead of throwing an error.
1266
- *
1267
- * @param t - The data to convert into a value object
1268
- * @param validate - Validation function that returns true if valid
1269
- * @param errorMessage - Optional custom error message if validation fails
1270
- * @returns Result containing the value object if valid, or an error message if validation fails
1271
- *
1272
- * @example
1273
- * ```typescript
1274
- * const result = voWithValidation(
1275
- * { amount: 100, currency: "USD" },
1276
- * (m) => m.amount >= 0 && m.currency.length === 3,
1277
- * "Invalid money: amount must be non-negative and currency must be 3 characters"
1278
- * );
1279
- *
1280
- * if (result.ok) {
1281
- * console.log(result.value); // Use the value object
1282
- * } else {
1283
- * console.error(result.error); // Handle validation error
1284
- * }
1285
- * ```
1286
- */
1287
- declare function voWithValidation<T>(t: T, validate: (value: T) => boolean, errorMessage?: string): Result<ValueObject<T>, string>;
1288
- /**
1289
- * Creates a value object with optional validation.
1290
- * Throws an error if validation fails.
1291
- *
1292
- * @param t - The data to convert into a value object
1293
- * @param validate - Validation function that returns true if valid
1294
- * @param errorMessage - Optional custom error message if validation fails
1295
- * @returns A deeply frozen, immutable value object
1296
- * @throws Error if validation fails
1297
- *
1298
- * @example
1299
- * ```typescript
1300
- * const money = voWithValidationUnsafe(
1301
- * { amount: 100, currency: "USD" },
1302
- * (m) => m.amount >= 0 && m.currency.length === 3,
1303
- * "Invalid money: amount must be non-negative and currency must be 3 characters"
1304
- * );
1305
- * ```
1306
- */
1307
- declare function voWithValidationUnsafe<T>(t: T, validate: (value: T) => boolean, errorMessage?: string): ValueObject<T>;
1308
-
1309
- export { type Aggregate, AggregateBase, type AggregateConfig, AggregateEventSourced, type AggregateEventSourcedConfig, type AggregateRoot, type AggregateSnapshot, type Clock, type Command, CommandBus, type CommandHandler, type DomainEvent, type Entity, type EventBus, EventBusImpl, type EventHandler, type EventMetadata, type ICommandBus, type IQueryBus, type IRepository, type ISpecification, type Id, type IdGenerator, type Outbox, type Query, QueryBus, type QueryHandler, type RepoProvider, type UnitOfWork, type ValueObject, type Version, aggregate, bump, copyMetadata, createDomainEvent, createDomainEventWithMetadata, entityIds, findEntityById, guard, hasEntityId, mergeMetadata, removeEntityById, replaceEntityById, sameAggregate, sameEntity, updateEntityById, vo, voEquals, voWithValidation, voWithValidationUnsafe, withCommit, withEvent };