@shirudo/ddd-kit 0.8.8 → 0.9.0

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