@shirudo/ddd-kit 0.16.0 → 1.0.0-rc.2
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/README.md +157 -218
- package/dist/index.d.ts +1141 -513
- package/dist/index.js +1144 -1
- package/dist/index.js.map +1 -1
- package/dist/utils.d.ts +92 -1
- package/dist/utils.js +282 -0
- package/dist/utils.js.map +1 -1
- package/package.json +69 -65
- package/dist/deep-equal-except-C8yoSk4L.d.ts +0 -57
- package/dist/result-jCwPSjFa.d.ts +0 -352
- package/dist/result.d.ts +0 -204
- package/dist/result.js +0 -2
- package/dist/result.js.map +0 -1
- package/dist/utils-array.d.ts +0 -47
- package/dist/utils-array.js +0 -2
- package/dist/utils-array.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/aggregate/aggregate.ts","../src/utils/array/is-built-in.ts","../src/utils/array/deep-equal.ts","../src/entity/entity.ts","../src/aggregate/aggregate-root.ts","../src/core/result/result.ts","../src/aggregate/aggregate-event-sourced.ts","../src/app/command-bus.ts","../src/app/handler.ts","../src/app/query-bus.ts","../src/core/guard.ts","../src/events/event-bus.ts","../src/utils/array/deep-omit.ts","../src/utils/array/deep-equal-except.ts","../src/value-object/value-object.ts"],"names":["aggregate","state","version","__name","withEvent","agg","evt","bump","createDomainEvent","type","payload","options","createDomainEventWithMetadata","metadata","copyMetadata","sourceEvent","additionalMetadata","mergeMetadata","metadataObjects","sameAggregate","a","b","isBuiltInObject","obj","tag","objConstructor","constructorName","proto","objProto","objToString","objHasOwn","deepEqual","deepEqualInner","visited","typeA","typeB","objA","objB","cached","tagA","tagB","viewA","viewB","len","i","arrA","arrB","mapA","mapB","key","valA","valB","setA","setB","value","timeA","timeB","regA","regB","stringKeysA","stringKeysB","symbolKeysA","symbolKeysB","Entity","id","initialState","_state","newState","sameEntity","findEntityById","entities","entity","hasEntityId","removeEntityById","updateEntityById","updater","replaceEntityById","replacement","entityIds","AggregateRoot","config","event","bumpVersion","snapshot","ok","err","error","AggregateEventSourced","_event","isNew","validation","handler","history","result","events","eventsAfterSnapshot","CommandBus","commandType","command","withCommit","deps","fn","QueryBus","queryType","query","guard","cond","EventBusImpl","eventType","handlersForType","resolve","unsubscribe","errors","results","deepOmit","omitInternal","path","arr","clone","stringKeys","symbolKeys","keys","shouldIgnoreKey","deepEqualExcept","prunedA","prunedB","deepFreeze","propNames","name","vo","voEquals","voEqualsExcept","voWithValidation","validate","errorMessage","voWithValidationUnsafe","ValueObject","props","other","Constructor"],"mappings":"AA4FO,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,KAAA,CAAA,CAAA,CAAA,YAAA,CAAA,IAAA,CAAA,CAAA,CAAA,SAASA,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CAAmB,CAAA,CACK,CACxB,OAAO,CAAE,KAAA,CAAAD,CAAAA,CAAO,OAAA,CAAAC,CAAAA,CAAS,aAAA,CAAe,EAAG,CAC5C,CALgBC,CAAAA,CAAAH,CAAAA,CAAA,WAAA,CAAA,CAOT,SAASI,EAAAA,CACfC,CAAAA,CACAC,CAAAA,CACkB,CAClB,OAAO,CAAE,GAAGD,CAAAA,CAAK,aAAA,CAAe,CAAC,GAAGA,CAAAA,CAAI,aAAA,CAAeC,CAAG,CAAE,CAC7D,CALgBH,CAAAA,CAAAC,EAAAA,CAAA,WAAA,CAAA,CAOT,SAASG,EAAAA,CACfF,CAAAA,CACkB,CAClB,OAAO,CAAE,GAAGA,CAAAA,CAAK,OAAA,CAAUA,CAAAA,CAAI,OAAA,CAAU,CAAc,CACxD,CAJgBF,CAAAA,CAAAI,GAAA,MAAA,CAAA,CAsCT,SAASC,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAKoB,CACpB,OAAO,CACN,I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AU,CAClB,IAAA,CAAK,QAAA,CAASA,CAAK,CAAA,CACnB,IAAA,CAAK,KAAA,CAAQX,CAAAA,CAAW,CAAE,GAAGW,CAAM,CAAC,EACxC,CASU,QAAA,CAASA,CAAAA,CAAgB,CAEnC,CASO,MAAA,CAAOC,CAAAA,CAAgC,CAK1C,OAJIA,CAAAA,EAAU,IAAA,EAIV,IAAA,CAAK,WAAA,GAAgBA,EAAM,WAAA,CACpB,KAAA,CAGJ3G,CAAAA,CAAU,IAAA,CAAK,KAAA,CAAO2G,CAAAA,CAAM,KAAK,CAC5C,CAQO,KAAA,CAAMD,CAAAA,CAA0B,CACnC,IAAME,CAAAA,CAAc,IAAA,CAAK,WAAA,CACzB,OAAO,IAAIA,CAAAA,CAAY,CAAE,GAAG,IAAA,CAAK,KAAA,CAAO,GAAIF,CAAAA,EAAS,EAAI,CAAC,CAC9D,CAOO,MAAA,EAAsB,CACzB,OAAO,IAAA,CAAK,KAChB,CAGJ","file":"index.js","sourcesContent":["import type { Id } from \"../core/id\";\n\nexport type Version = number & { readonly __v: true };\n\n/**\n * Metadata associated with a domain event for traceability and correlation.\n * Used in event-driven architectures to track event flow across services.\n */\nexport interface EventMetadata {\n\t/**\n\t * Correlation ID for tracing events across multiple services/components.\n\t * Typically used to group related events in a distributed system.\n\t */\n\tcorrelationId?: string;\n\n\t/**\n\t * Causation ID referencing the event or command that caused this event.\n\t * Used to build event chains and understand causality.\n\t */\n\tcausationId?: string;\n\n\t/**\n\t * User ID of the person or system that triggered the event.\n\t */\n\tuserId?: string;\n\n\t/**\n\t * Source service or component that produced the event.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Additional custom metadata fields.\n\t * Allows extensibility for domain-specific metadata.\n\t */\n\t[key: string]: unknown;\n}\n\n/**\n * Domain Event represents something meaningful that happened in the domain.\n * Events are immutable and carry information about what occurred.\n *\n * @template T - The event type name (e.g., \"OrderCreated\")\n * @template P - The event payload type\n */\nexport interface DomainEvent<T extends string, P = void> {\n\t/**\n\t * The type of the event, used for routing and handling.\n\t */\n\ttype: T;\n\n\t/**\n\t * The event payload containing the domain data.\n\t * Omitted when P is void (events without payload).\n\t */\n\tpayload: P;\n\n\t/**\n\t * Timestamp when the event occurred.\n\t */\n\toccurredAt: Date;\n\n\t/**\n\t * Event schema version for handling schema evolution.\n\t * Defaults to 1 if not specified. Higher versions indicate schema changes.\n\t */\n\tversion?: number;\n\n\t/**\n\t * Optional metadata for traceability, correlation, and auditing.\n\t * Includes correlationId, causationId, userId, source, and custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n// Re-export interfaces from their respective files for convenience\nexport type { IAggregateRoot } from \"./aggregate-root\";\nexport type { IAggregateEventSourced } from \"./aggregate-event-sourced\";\n\n/**\n * Structural interface representing an aggregate with state and events.\n * Used for type constraints in repositories and other infrastructure code.\n *\n * @template State - The type of the aggregate state\n * @template Evt - The union type of all domain events\n */\nexport interface Aggregate<State, Evt extends DomainEvent<string, unknown>> {\n\tstate: Readonly<State>;\n\tversion: Version;\n\tpendingEvents: ReadonlyArray<Evt>;\n}\n\nexport function aggregate<State, Evt extends DomainEvent<string, unknown>>(\n\tstate: State,\n\tversion: Version = 0 as Version,\n): Aggregate<State, Evt> {\n\treturn { state, version, pendingEvents: [] };\n}\n\nexport function withEvent<S, E extends DomainEvent<string, unknown>>(\n\tagg: Aggregate<S, E>,\n\tevt: E,\n): Aggregate<S, E> {\n\treturn { ...agg, pendingEvents: [...agg.pendingEvents, evt] };\n}\n\nexport function bump<S, E extends DomainEvent<string, unknown>>(\n\tagg: Aggregate<S, E>,\n): Aggregate<S, E> {\n\treturn { ...agg, version: (agg.version + 1) as Version };\n}\n\n/**\n * Creates a domain event with default values.\n * Sets occurredAt to current date and version to 1 if not provided.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param options - Optional event configuration\n * @returns A domain event\n *\n * @example\n * ```typescript\n * const event = createDomainEvent(\"OrderCreated\", { orderId: \"123\" });\n * ```\n */\nexport function createDomainEvent<T extends string>(\n\ttype: T,\n\tpayload?: undefined,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, void>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, P>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload?: P,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, P> {\n\treturn {\n\t\ttype,\n\t\tpayload: payload as P,\n\t\toccurredAt: options?.occurredAt ?? new Date(),\n\t\tversion: options?.version ?? 1,\n\t\tmetadata: options?.metadata,\n\t};\n}\n\n/**\n * Creates a domain event with metadata for traceability.\n * Convenience function for creating events with correlation and causation IDs.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param metadata - Event metadata for traceability\n * @param options - Optional event configuration\n * @returns A domain event with metadata\n *\n * @example\n * ```typescript\n * const event = createDomainEventWithMetadata(\n * \"OrderCreated\",\n * { orderId: \"123\" },\n * {\n * correlationId: \"corr-123\",\n * causationId: \"cmd-456\",\n * userId: \"user-789\"\n * }\n * );\n * ```\n */\nexport function createDomainEventWithMetadata<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\tmetadata: EventMetadata,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t},\n): DomainEvent<T, P> {\n\treturn createDomainEvent(type, payload, {\n\t\t...options,\n\t\tmetadata,\n\t});\n}\n\n/**\n * Copies metadata from a source event to a new event.\n * Useful for maintaining correlation chains in event-driven architectures.\n *\n * @param sourceEvent - The source event to copy metadata from\n * @param additionalMetadata - Additional metadata to merge in\n * @returns Event metadata with copied and merged values\n *\n * @example\n * ```typescript\n * const newEvent = createDomainEvent(\n * \"OrderShipped\",\n * { orderId: \"123\" },\n * {\n * metadata: copyMetadata(previousEvent, { causationId: previousEvent.type })\n * }\n * );\n * ```\n */\nexport function copyMetadata(\n\tsourceEvent: DomainEvent<string, unknown>,\n\tadditionalMetadata?: Partial<EventMetadata>,\n): EventMetadata {\n\treturn {\n\t\t...(sourceEvent.metadata ?? {}),\n\t\t...(additionalMetadata ?? {}),\n\t};\n}\n\n/**\n * Merges multiple metadata objects into one.\n * Later metadata objects override earlier ones for the same keys.\n *\n * @param metadataObjects - Array of metadata objects to merge\n * @returns Merged event metadata\n *\n * @example\n * ```typescript\n * const metadata = mergeMetadata(\n * { correlationId: \"corr-123\" },\n * { userId: \"user-456\" },\n * { source: \"order-service\" }\n * );\n * ```\n */\nexport function mergeMetadata(\n\t...metadataObjects: Array<EventMetadata | undefined>\n): EventMetadata {\n\treturn Object.assign({}, ...metadataObjects.filter(Boolean));\n}\n\n/**\n * Snapshot of an aggregate state at a specific point in time.\n * Used for optimizing event replay by starting from a snapshot\n * instead of replaying all events from the beginning.\n *\n * @template TState - The type of the aggregate state\n */\nexport interface AggregateSnapshot<TState> {\n\t/**\n\t * The state of the aggregate at the time of the snapshot.\n\t */\n\tstate: TState;\n\n\t/**\n\t * The version of the aggregate when the snapshot was taken.\n\t */\n\tversion: Version;\n\n\t/**\n\t * Timestamp when the snapshot was created.\n\t */\n\tsnapshotAt: Date;\n}\n\n/**\n * Checks if two aggregates are the same (same ID and version).\n * Useful for optimistic concurrency control checks.\n *\n * @param a - First aggregate\n * @param b - Second aggregate\n * @returns true if both aggregates have the same ID and version\n *\n * @example\n * ```typescript\n * const aggregate1 = await repository.getById(id);\n * // ... some operations ...\n * const aggregate2 = await repository.getById(id);\n *\n * if (!sameAggregate(aggregate1, aggregate2)) {\n * throw new Error(\"Aggregate was modified by another process\");\n * }\n * ```\n */\nexport function sameAggregate<TId extends Id<string>>(\n\ta: { id: TId; version: Version },\n\tb: { id: TId; version: Version },\n): boolean {\n\treturn a.id === b.id && a.version === b.version;\n}\n","/**\n * Checks if an object is a built-in JavaScript type that should be treated atomically.\n * This function automatically detects built-ins without requiring manual maintenance.\n *\n * Detection strategy:\n * 1. TypedArrays: Check if tag ends with \"Array]\" (covers all current and future TypedArrays)\n * 2. ArrayBuffer views: Use ArrayBuffer.isView() (covers DataView and all TypedArrays)\n * 3. Built-in constructors: Check if constructor exists in global scope and matches known patterns\n * 4. Tag-based: Fallback to tag matching for known built-ins\n *\n * @param obj - The object to check\n * @param tag - The result of `Object.prototype.toString.call(obj)`\n * @returns `true` if the object is a built-in type, `false` otherwise\n */\nexport function isBuiltInObject(obj: object, tag: string): boolean {\n\t// 1. TypedArrays: all end with \"Array]\" - future-proof for new TypedArrays\n\tif (tag.endsWith(\"Array]\")) {\n\t\treturn true;\n\t}\n\n\t// 2. ArrayBuffer views: covers DataView and all TypedArrays (future-proof)\n\tif (ArrayBuffer.isView(obj)) {\n\t\treturn true;\n\t}\n\n\t// 3. ArrayBuffer and SharedArrayBuffer\n\tif (tag === \"[object ArrayBuffer]\" || tag === \"[object SharedArrayBuffer]\") {\n\t\treturn true;\n\t}\n\n\t// 4. Check if constructor exists in global scope (future-proof for new globals)\n\tconst objConstructor = (obj as { constructor?: unknown }).constructor;\n\tif (objConstructor && typeof objConstructor === \"function\") {\n\t\tconst constructorName = objConstructor.name;\n\t\t// Check if it's a known global constructor\n\t\t// This covers: Date, RegExp, Map, Set, WeakMap, WeakSet, Promise, Error, etc.\n\t\tif (\n\t\t\tconstructorName &&\n\t\t\ttypeof globalThis !== \"undefined\" &&\n\t\t\tconstructorName in globalThis &&\n\t\t\t(globalThis as Record<string, unknown>)[constructorName] === objConstructor\n\t\t) {\n\t\t\t// Additional check: ensure it's not a user-defined class with same name\n\t\t\t// Built-ins typically have non-enumerable properties and specific prototypes\n\t\t\tconst proto = Object.getPrototypeOf(obj);\n\t\t\tif (proto !== Object.prototype && proto !== null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// 5. Tag-based fallback for known built-ins (covers edge cases)\n\tconst knownBuiltInTags = new Set([\n\t\t\"[object Date]\",\n\t\t\"[object RegExp]\",\n\t\t\"[object Map]\",\n\t\t\"[object Set]\",\n\t\t\"[object WeakMap]\",\n\t\t\"[object WeakSet]\",\n\t\t\"[object Promise]\",\n\t\t\"[object Error]\",\n\t\t\"[object Boolean]\",\n\t\t\"[object Number]\",\n\t\t\"[object String]\",\n\t]);\n\n\treturn knownBuiltInTags.has(tag);\n}\n\n","import { isBuiltInObject } from \"./is-built-in\";\n\nconst objProto = Object.prototype;\nconst objToString = objProto.toString;\nconst objHasOwn = objProto.hasOwnProperty;\n\n/**\n * Performs a deep equality check between two values.\n *\n * This function compares values recursively, handling:\n * - Primitives (with special handling for NaN)\n * - Arrays (nested arrays supported)\n * - Objects (plain objects and class instances)\n * - TypedArrays (Uint8Array, Int32Array, etc.)\n * - DataView\n * - Maps and Sets\n * - Dates and RegExp\n * - Wrapper objects (Boolean, Number, String)\n * - Circular references (detected and handled)\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @returns `true` if the values are deeply equal, `false` otherwise\n *\n * @example\n * ```ts\n * deepEqual([1, 2, 3], [1, 2, 3]); // true\n * deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); // true\n * deepEqual(NaN, NaN); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n\treturn deepEqualInner(a, b, new WeakMap<object, object>());\n}\n\n/**\n * Internal recursive function for deep equality comparison.\n * Tracks visited objects to detect and handle circular references.\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param visited - WeakMap to track visited object pairs and detect cycles\n * @returns `true` if the values are deeply equal, `false` otherwise\n * @internal\n */\nfunction deepEqualInner(\n\ta: unknown,\n\tb: unknown,\n\tvisited: WeakMap<object, object>\n): boolean {\n\t// 1. Fast path: reference equality\n\tif (a === b) return true;\n\n\tconst typeA = typeof a;\n\tconst typeB = typeof b;\n\n\t// 2. If one is not an object → primitive / function\n\tif (typeA !== \"object\" || a === null || typeB !== \"object\" || b === null) {\n\t\t// Special case: NaN should be equal\n\t\tif (typeA === \"number\" && typeB === \"number\") {\n\t\t\treturn Number.isNaN(a as number) && Number.isNaN(b as number);\n\t\t}\n\t\t// Everything else is directly unequal with !== (including functions)\n\t\treturn false;\n\t}\n\n\t// From here on: both are non-null objects\n\n\tconst objA = a as object;\n\tconst objB = b as object;\n\n\t// 3. Cycles: already seen pair?\n\tconst cached = visited.get(objA);\n\tif (cached !== undefined) {\n\t\t// If we already paired this A with a different B → unequal\n\t\treturn cached === objB;\n\t}\n\tvisited.set(objA, objB);\n\n\t// 4. Handle Typed Arrays / DataView first\n\tif (ArrayBuffer.isView(objA) || ArrayBuffer.isView(objB)) {\n\t\tif (!ArrayBuffer.isView(objA) || !ArrayBuffer.isView(objB)) return false;\n\n\t\tconst tagA = objToString.call(objA);\n\t\tconst tagB = objToString.call(objB);\n\t\tif (tagA !== tagB) return false;\n\n\t\t// DataView: compare byte by byte\n\t\tif (tagA === \"[object DataView]\") {\n\t\t\tconst viewA = objA as DataView;\n\t\t\tconst viewB = objB as DataView;\n\t\t\tif (viewA.byteLength !== viewB.byteLength) return false;\n\n\t\t\tconst len = viewA.byteLength;\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (viewA.getUint8(i) !== viewB.getUint8(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// Typed Arrays: element by element\n\t\tconst arrA = objA as unknown as ArrayLike<unknown>;\n\t\tconst arrB = objB as unknown as ArrayLike<unknown>;\n\n\t\tconst len = arrA.length;\n\t\tif (len !== arrB.length) return false;\n\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tif ((arrA as any)[i] !== (arrB as any)[i]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// 5. Tag-based type detection (robust across realms)\n\tconst tagA = objToString.call(objA);\n\tconst tagB = objToString.call(objB);\n\tif (tagA !== tagB) return false;\n\n\tswitch (tagA) {\n\t\tcase \"[object Array]\": {\n\t\t\tconst arrA = objA as unknown[];\n\t\t\tconst arrB = objB as unknown[];\n\t\t\tconst len = arrA.length;\n\t\t\tif (len !== arrB.length) return false;\n\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (!deepEqualInner(arrA[i], arrB[i], visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Map]\": {\n\t\t\tconst mapA = objA as Map<unknown, unknown>;\n\t\t\tconst mapB = objB as Map<unknown, unknown>;\n\n\t\t\tif (mapA.size !== mapB.size) return false;\n\n\t\t\tfor (const [key, valA] of mapA) {\n\t\t\t\t// Map keys according to JS semantics: reference / SameValueZero\n\t\t\t\tif (!mapB.has(key)) return false;\n\t\t\t\tconst valB = mapB.get(key);\n\t\t\t\tif (!deepEqualInner(valA, valB, visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Set]\": {\n\t\t\tconst setA = objA as Set<unknown>;\n\t\t\tconst setB = objB as Set<unknown>;\n\n\t\t\tif (setA.size !== setB.size) return false;\n\n\t\t\t// Set elements: same reference (JS semantics)\n\t\t\tfor (const value of setA) {\n\t\t\t\tif (!setB.has(value)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Date]\": {\n\t\t\tconst timeA = (objA as Date).getTime();\n\t\t\tconst timeB = (objB as Date).getTime();\n\t\t\treturn timeA === timeB;\n\t\t}\n\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst regA = objA as RegExp;\n\t\t\tconst regB = objB as RegExp;\n\t\t\treturn regA.source === regB.source && regA.flags === regB.flags;\n\t\t}\n\n\t\tcase \"[object Boolean]\":\n\t\tcase \"[object Number]\":\n\t\tcase \"[object String]\": {\n\t\t\t// Wrapper objects (new Boolean/Number/String)\n\t\t\treturn (objA as any).valueOf() === (objB as any).valueOf();\n\t\t}\n\n\t\tdefault: {\n\t\t\t// 6. Check if this is an unhandled built-in type (future-proof)\n\t\t\t// If both are built-ins but not handled above, they should be compared by reference\n\t\t\t// (since we don't know their internal structure)\n\t\t\tif (isBuiltInObject(objA, tagA) && isBuiltInObject(objB, tagB)) {\n\t\t\t\t// Unhandled built-in types: compare by reference as fallback\n\t\t\t\t// This ensures new built-ins don't fall through to plain object comparison\n\t\t\t\treturn objA === objB;\n\t\t\t}\n\n\t\t\t// 7. Fallback: plain / custom objects → compare own enumerable keys + values\n\t\t\tconst stringKeysA = Object.keys(objA as any);\n\t\t\tconst stringKeysB = Object.keys(objB as any);\n\t\t\tconst symbolKeysA = Object.getOwnPropertySymbols(objA as any);\n\t\t\tconst symbolKeysB = Object.getOwnPropertySymbols(objB as any);\n\n\t\t\t// Compare string keys count\n\t\t\tif (stringKeysA.length !== stringKeysB.length) return false;\n\t\t\t// Compare symbol keys count\n\t\t\tif (symbolKeysA.length !== symbolKeysB.length) return false;\n\n\t\t\t// Check all string keys exist in both objects\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!objHasOwn.call(objB, key)) return false;\n\t\t\t}\n\n\t\t\t// Check all symbol keys exist in both objects\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!Object.getOwnPropertySymbols(objB as any).includes(key)) return false;\n\t\t\t}\n\n\t\t\t// Compare string key values\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!deepEqualInner((objA as any)[key], (objB as any)[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compare symbol key values\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!deepEqualInner((objA as any)[key], (objB as any)[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n}\n","/**\n * Entity utilities and interfaces for Domain-Driven Design.\n *\n * In Domain-Driven Design, there are two types of entities:\n *\n * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.\n * - Has identity (id), state, and version\n * - Implemented by classes extending `AggregateRoot` or `AggregateEventSourced`\n * - Represents the aggregate externally\n * - Loaded/saved through repositories\n *\n * 2. **Child Entities**: Entities within an aggregate.\n * - Have identity (id) and state, but no own version\n * - Can extend `EntityBase<TState, TId>` for class-based entities\n * - Or use functional style with `Identifiable<TId> & TProps`\n * - Exist only within the aggregate boundary\n * - Versioned through the Aggregate Root\n * - Cannot be referenced directly from outside the aggregate\n *\n * This module provides:\n * - `EntityBase<TState, TId>` - Base class for entities with state\n * - `Entity<TId>` - Simple class for entities without state management\n * - `Identifiable<TId>` - Minimal interface for objects with id\n * - Helper functions for working with collections of entities\n *\n * @example\n * ```typescript\n * // Class-based child entity with logic\n * class OrderItem extends EntityBase<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n *\n * calculateSubtotal(): number {\n * return this._state.price * this._state.quantity;\n * }\n * }\n *\n * // Functional-style child entity (simpler, no logic)\n * type OrderItem = Identifiable<ItemId> & {\n * productId: string;\n * quantity: number;\n * price: number;\n * };\n *\n * // Aggregate Root (Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * // Order is an Aggregate Root Entity\n * // OrderState contains OrderItem child entities\n * }\n * ```\n */\nimport { deepEqual } from \"../utils/array/deep-equal\";\n\nimport type { Id } from \"../core/id\";\n\n/**\n * Functional definition of an Entity via its capability.\n * An object is identifiable if it has an id.\n */\nexport type Identifiable<TId> = {\n\treadonly id: TId;\n};\n\n/**\n * Interface for Entities with state.\n *\n * In Domain-Driven Design, Entities have:\n * - Identity (id): Distinguishes one entity from another\n * - State: The attributes/properties of the entity\n *\n * Unlike Value Objects (which are immutable and compared by value),\n * Entities are compared by identity and can have mutable state.\n *\n * @template TId - The type of the entity identifier\n * @template TState - The type of the entity state\n */\nexport interface IEntity<TId extends Id<string>, TState> extends Identifiable<TId> {\n\t/**\n\t * Unique identifier of the entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * The current state of the entity.\n\t */\n\treadonly state: TState;\n}\n\n/**\n * Abstract base class for Entities with state.\n *\n * Provides:\n * - Identity management (id)\n * - State management\n * - State validation hook\n * - Immutable state access through getter\n *\n * This is the foundation for all Entities in DDD:\n * - Child Entities within aggregates can extend this\n * - Aggregate Roots extend this and add version + events\n *\n * @template TState - The type of the entity state\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * // Child Entity within an aggregate\n * class OrderItem extends Entity<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n * }\n * ```\n */\nexport abstract class Entity<TState, TId extends Id<string>>\n\timplements IEntity<TId, TState> {\n\tpublic readonly id: TId;\n\n\t/**\n\t * Returns the current state of the entity.\n\t * State is readonly from outside to enforce encapsulation.\n\t */\n\tpublic get state(): TState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * The state is 'protected' so that only the subclass can modify it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(id: TId, initialState: TState) {\n\t\tif (id === null || id === undefined) {\n\t\t\tthrow new Error(\"Entity ID cannot be null or undefined\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis._state = initialState;\n\t\tthis.validateState(this._state);\n\t}\n\n\t/**\n\t * Optional validation hook to ensure state invariants.\n\t * Called during construction and whenever helpful.\n\t * Override this method to implement validation logic.\n\t *\n\t * @param state - The state to validate\n\t * @throws Error if validation fails\n\t */\n\tprotected validateState(_state: TState): void {\n\t\t// Default implementation does nothing\n\t}\n\n\t/**\n\t * Sets the state of the entity.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t *\n\t * @param newState - The new state\n\t */\n\tprotected setState(newState: TState): void {\n\t\tthis.validateState(newState);\n\t\tthis._state = newState;\n\t}\n}\n\n\n/**\n * Checks if two entities have the same ID.\n * Works with any object that has an 'id' property.\n *\n * @param a - First entity\n * @param b - Second entity\n * @returns true if both entities have the same ID, false otherwise\n *\n * @example\n * ```typescript\n * const item1: OrderItem = { id: itemId1, productId: \"prod-1\", quantity: 2 };\n * const item2: OrderItem = { id: itemId2, productId: \"prod-2\", quantity: 1 };\n *\n * sameEntity(item1, item2); // false\n * sameEntity(item1, item1); // true\n * ```\n */\nexport function sameEntity<TId>(a: Identifiable<TId>, b: Identifiable<TId>): boolean {\n\treturn deepEqual(a.id, b.id);\n}\n\n/**\n * Finds an entity by ID in a collection.\n * Returns undefined if not found.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to search for\n * @returns The entity if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const item = findEntityById(items, itemId1);\n * // item is { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ```\n */\nexport function findEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T | undefined {\n\treturn entities.find((entity) => deepEqual(entity.id, id));\n}\n\n/**\n * Checks if an entity with the given ID exists in the collection.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to check for\n * @returns true if an entity with the ID exists, false otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * hasEntityId(items, itemId1); // true\n * hasEntityId(items, itemId2); // false\n * ```\n */\nexport function hasEntityId<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): boolean {\n\treturn entities.some((entity) => deepEqual(entity.id, id));\n}\n\n/**\n * Removes an entity with the given ID from the collection.\n * Returns a new array without the entity.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to remove\n * @returns A new array without the entity with the given ID\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const updated = removeEntityById(items, itemId1);\n * // updated is [{ id: itemId2, productId: \"prod-2\", quantity: 1 }]\n * ```\n */\nexport function removeEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T[] {\n\treturn entities.filter((entity) => !deepEqual(entity.id, id));\n}\n\n/**\n * Updates an entity with the given ID in the collection.\n * Returns a new array with the updated entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to update\n * @param updater - Function that takes the entity and returns the updated entity\n * @returns A new array with the updated entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = updateEntityById(items, itemId1, (item) => ({\n * ...item,\n * quantity: item.quantity + 1\n * }));\n * // updated is [{ id: itemId1, productId: \"prod-1\", quantity: 3 }]\n * ```\n */\nexport function updateEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\tupdater: (entity: T) => T,\n): T[] {\n\treturn entities.map((entity) => (deepEqual(entity.id, id) ? updater(entity) : entity));\n}\n\n/**\n * Replaces an entity with the given ID in the collection.\n * Returns a new array with the replaced entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to replace\n * @param replacement - The replacement entity\n * @returns A new array with the replaced entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = replaceEntityById(items, itemId1, {\n * id: itemId1,\n * productId: \"prod-1\",\n * quantity: 5\n * });\n * ```\n */\nexport function replaceEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\treplacement: T,\n): T[] {\n\treturn entities.map((entity) => (deepEqual(entity.id, id) ? replacement : entity));\n}\n\n/**\n * Extracts all IDs from a collection of entities.\n *\n * @param entities - Array of entities\n * @returns Array of entity IDs\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const ids = entityIds(items);\n * // ids is [itemId1, itemId2]\n * ```\n */\nexport function entityIds<TId, T extends Identifiable<TId>>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\n\n","import type { Id } from \"../core/id\";\nimport { Entity } from \"../entity/entity\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Marker interface for Aggregate Roots.\n *\n * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).\n * It represents the aggregate externally and is the only object that external code\n * is allowed to hold references to. All access to child entities within the aggregate\n * must go through the Aggregate Root.\n *\n * An Aggregate consists of:\n * - One Aggregate Root (Entity with id + version)\n * - Optional child entities (Entities with id + state, but no own version)\n * - Optional value objects\n *\n * The Aggregate Root has identity (id), state, and version for optimistic concurrency control.\n * Child entities exist only within the aggregate boundary and are versioned through\n * the Aggregate Root.\n *\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {\n * // Order is an Aggregate Root (an Entity with version)\n * // OrderState contains child entities (e.g., OrderItem) and value objects\n * }\n * ```\n */\nexport interface IAggregateRoot<TId extends Id<string>> {\n\t/**\n\t * Unique identifier of the aggregate root entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * Version number for optimistic concurrency control.\n\t * Incremented on each state change to detect concurrent modifications.\n\t * This version applies to the entire aggregate, including all child entities.\n\t */\n\treadonly version: Version;\n}\n\n/**\n * Configuration options for AggregateRoot behavior.\n */\nexport interface AggregateConfig {\n\t/**\n\t * Whether to automatically bump the version when state changes.\n\t * Defaults to false. Set to true for automatic versioning.\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for creating Aggregate Roots (Entities) without Event Sourcing.\n *\n * This class creates an Entity that serves as the Aggregate Root. The Aggregate Root\n * is the parent Entity of the aggregate and represents it externally. It has identity\n * (id), state, and version for optimistic concurrency control.\n *\n * Extends `Entity<TState, TId>` to inherit:\n * - Identity (id)\n * - State management\n * - State validation\n *\n * Adds Aggregate Root specific functionality:\n * - Version management (for Optimistic Concurrency Control)\n * - Domain events tracking\n * - Snapshot support for performance optimization\n *\n * The aggregate state (`TState`) contains:\n * - Child entities (Entities with id + state, but no own version)\n * - Value objects (immutable objects)\n *\n * All changes to child entities are versioned through the Aggregate Root. The version\n * applies to the entire aggregate, including all child entities.\n *\n * Implements `IAggregateRoot<TId>` to mark this as an Aggregate Root Entity.\n *\n * Use this class when you don't need Event Sourcing but still want\n * aggregate patterns with versioning and state management.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The type of domain events recorded by this aggregate (defaults to unknown)\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * constructor(id: OrderId, initialState: OrderState) {\n * super(id, initialState);\n * }\n *\n * confirm(): void {\n * this._state = { ...this._state, status: \"confirmed\" };\n * this.bumpVersion(); // Versions the entire aggregate\n * }\n * }\n * ```\n */\nexport abstract class AggregateRoot<TState, TId extends Id<string>, TEvent = unknown>\n\textends Entity<TState, TId>\n\timplements IAggregateRoot<TId> {\n\tpublic version: Version = 0 as Version;\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\tprivate _domainEvents: TEvent[] = [];\n\n\t/**\n\t * Returns a read-only list of domain events recorded by this aggregate.\n\t * These events are side-effects of state changes.\n\t */\n\tpublic get domainEvents(): ReadonlyArray<TEvent> {\n\t\treturn this._domainEvents;\n\t}\n\n\t/**\n\t * Clears the list of recorded domain events.\n\t * Call this after dispatching the events.\n\t */\n\tpublic clearDomainEvents(): void {\n\t\tthis._domainEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\n\t}\n\n\t/**\n\t * Adds a domain event to the aggregate's list of changes.\n\t * Use this to record side-effects that should be published.\n\t *\n\t * @param event - The domain event to add\n\t */\n\tprotected addDomainEvent(event: TEvent): void {\n\t\tthis._domainEvents.push(event);\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Call this after state changes for Optimistic Concurrency Control.\n\t *\n\t * If `autoVersionBump` is enabled, this is called automatically\n\t * when using `setState()`.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.version = (this.version + 1) as Version;\n\t}\n\n\t/**\n\t * Sets the state and optionally bumps the version automatically.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t * Overrides Entity.setState to add version bumping.\n\t *\n\t * @param newState - The new state\n\t * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)\n\t */\n\tprotected setState(\n\t\tnewState: TState,\n\t\tbumpVersion?: boolean,\n\t): void {\n\t\tsuper.setState(newState);\n\t\tconst shouldBump = bumpVersion ?? this._autoVersionBump;\n\t\tif (shouldBump) {\n\t\t\tthis.bumpVersion();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t * Useful for performance optimization, backup/restore, and audit trails.\n\t *\n\t * @returns A snapshot containing the current state and version\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = aggregate.createSnapshot();\n\t * await snapshotRepository.save(aggregate.id, snapshot);\n\t * ```\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: { ...this._state } as TState,\n\t\t\tversion: this.version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot.\n\t * This is useful for loading aggregates from snapshots instead of\n\t * rebuilding them from scratch.\n\t * Validates the restored state.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * aggregate.restoreFromSnapshot(snapshot);\n\t * ```\n\t */\n\tpublic restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void {\n\t\tthis.validateState(snapshot.state);\n\t\tthis._state = snapshot.state;\n\t\tthis.version = snapshot.version;\n\t}\n}\n","export type Ok<T> = { ok: true; value: T };\nexport type Err<E> = { ok: false; error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Creates an Ok result with a value.\n *\n * @param value - The success value\n * @returns An Ok result containing the value\n *\n * @example\n * ```typescript\n * const result = ok(42);\n * // result is Ok<number>\n * ```\n */\nexport function ok<T>(value: T): Ok<T>;\n\n/**\n * Creates an Ok result with void (no value).\n *\n * @returns An Ok<void> result\n *\n * @example\n * ```typescript\n * const result = ok();\n * // result is Ok<void>\n * ```\n */\nexport function ok(): Ok<void>;\n\nexport function ok<T>(value?: T): Ok<T> {\n\treturn { ok: true, value: value as T };\n}\n\n/**\n * Creates an Err result with an error.\n *\n * @param error - The error value\n * @returns An Err result containing the error\n *\n * @example\n * ```typescript\n * const result = err(\"Something went wrong\");\n * // result is Err<string>\n * ```\n */\nexport function err<E>(error: E): Err<E>;\n\n/**\n * Creates an Err result with void (no error value).\n *\n * @returns An Err<void> result\n *\n * @example\n * ```typescript\n * const result = err();\n * // result is Err<void>\n * ```\n */\nexport function err(): Err<void>;\n\nexport function err<E>(error?: E): Err<E> {\n\treturn { ok: false, error: error as E };\n}\n\n/**\n * Type guard to check if a Result is Ok.\n * Narrows the type to Ok<T> when returning true.\n *\n * @param result - The result to check\n * @returns true if the result is Ok, false otherwise\n *\n * @example\n * ```typescript\n * const result = voWithValidation(data, validator);\n * if (isOk(result)) {\n * // TypeScript knows result is Ok<VO<T>>\n * console.log(result.value);\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.ok === true;\n}\n\n/**\n * Type guard to check if a Result is Err.\n * Narrows the type to Err<E> when returning true.\n *\n * @param result - The result to check\n * @returns true if the result is Err, false otherwise\n *\n * @example\n * ```typescript\n * const result = voWithValidation(data, validator);\n * if (isErr(result)) {\n * // TypeScript knows result is Err<string>\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.ok === false;\n}\n\n/**\n * Chains Result operations (flatMap/bind).\n * If the result is Ok, applies the function to the value.\n * If Err, returns the error unchanged.\n *\n * @param result - The result to chain\n * @param fn - Function that takes the Ok value and returns a new Result\n * @returns A new Result\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"123\")\n * .andThen(userId => validateEmail(\"test@example.com\")\n * .map(email => ({ id: userId, email }))\n * );\n * ```\n */\nexport function andThen<T, E, U>(\n\tresult: Result<T, E>,\n\tfn: (value: T) => Result<U, E>,\n): Result<U, E> {\n\tif (result.ok) {\n\t\treturn fn(result.value);\n\t}\n\treturn result;\n}\n\n/**\n * Transforms the Ok value using a function.\n * If the result is Err, returns the error unchanged.\n *\n * @param result - The result to transform\n * @param fn - Function to transform the Ok value\n * @returns A new Result with transformed value\n *\n * @example\n * ```typescript\n * const result = ok(5);\n * const doubled = map(result, x => x * 2); // Ok<10>\n * ```\n */\nexport function map<T, E, U>(\n\tresult: Result<T, E>,\n\tfn: (value: T) => U,\n): Result<U, E> {\n\tif (result.ok) {\n\t\treturn ok(fn(result.value));\n\t}\n\treturn result;\n}\n\n/**\n * Transforms the Err value using a function.\n * If the result is Ok, returns the value unchanged.\n *\n * @param result - The result to transform\n * @param fn - Function to transform the Err value\n * @returns A new Result with transformed error\n *\n * @example\n * ```typescript\n * const result = err(\"not found\");\n * const mapped = mapErr(result, e => `Error: ${e}`); // Err<\"Error: not found\">\n * ```\n */\nexport function mapErr<T, E, F>(\n\tresult: Result<T, E>,\n\tfn: (error: E) => F,\n): Result<T, F> {\n\tif (result.ok) {\n\t\treturn result;\n\t}\n\treturn err(fn(result.error));\n}\n\n/**\n * Returns the value if Ok, otherwise returns the default value.\n *\n * @param result - The result to unwrap\n * @param defaultValue - Default value to return if Err\n * @returns The Ok value or the default value\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"123\");\n * const userId = unwrapOr(result, \"default-id\");\n * ```\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n\treturn result.ok ? result.value : defaultValue;\n}\n\n/**\n * Returns the value if Ok, otherwise computes default from error.\n *\n * @param result - The result to unwrap\n * @param fn - Function to compute default from error\n * @returns The Ok value or computed default\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"\");\n * const userId = unwrapOrElse(result, err => `fallback-${Date.now()}`);\n * ```\n */\nexport function unwrapOrElse<T, E>(\n\tresult: Result<T, E>,\n\tfn: (error: E) => T,\n): T {\n\treturn result.ok ? result.value : fn(result.error);\n}\n\n/**\n * Pattern matching for Result.\n * Applies one function if Ok, another if Err.\n *\n * @param result - The result to match\n * @param onOk - Function to apply if Ok\n * @param onErr - Function to apply if Err\n * @returns The result of applying the appropriate function\n *\n * @example\n * ```typescript\n * const message = match(result,\n * value => `Success: ${value}`,\n * error => `Error: ${error}`\n * );\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const message = match(result, {\n * ok: value => `Success: ${value}`,\n * err: error => `Error: ${error}`\n * });\n * ```\n */\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => R,\n\tonErr: (error: E) => R,\n): R;\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\thandlers: { ok: (value: T) => R; err: (error: E) => R },\n): R;\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers: ((value: T) => R) | { ok: (value: T) => R; err: (error: E) => R },\n\tonErr?: (error: E) => R,\n): R {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\t// Function syntax: match(result, onOk, onErr)\n\t\treturn result.ok ? onOkOrHandlers(result.value) : onErr!(result.error);\n\t}\n\t// Object syntax: match(result, { ok: ..., err: ... })\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Async pattern matching for Result.\n * Applies one async function if Ok, another if Err.\n * Both handlers must return Promises.\n *\n * @param result - The result to match\n * @param onOk - Async function to apply if Ok\n * @param onErr - Async function to apply if Err\n * @returns Promise resolving to the result of applying the appropriate function\n *\n * @example\n * ```typescript\n * const message = await matchAsync(result,\n * async (value) => `Success: ${value}`,\n * async (error) => `Error: ${error}`\n * );\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const message = await matchAsync(result, {\n * ok: async (value) => `Success: ${value}`,\n * err: async (error) => `Error: ${error}`\n * });\n * ```\n */\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => Promise<R>,\n\tonErr: (error: E) => Promise<R>,\n): Promise<R>;\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\thandlers: { ok: (value: T) => Promise<R>; err: (error: E) => Promise<R> },\n): Promise<R>;\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers:\n\t\t| ((value: T) => Promise<R>)\n\t\t| { ok: (value: T) => Promise<R>; err: (error: E) => Promise<R> },\n\tonErr?: (error: E) => Promise<R>,\n): Promise<R> {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\t// Function syntax: matchAsync(result, onOk, onErr)\n\t\treturn result.ok\n\t\t\t? onOkOrHandlers(result.value)\n\t\t\t: onErr!(result.error);\n\t}\n\t// Object syntax: matchAsync(result, { ok: ..., err: ... })\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Pattern matching for Result that returns a Result.\n * Both handlers must return a Result, allowing you to transform\n * both the success and error cases while staying in Result context.\n *\n * @param result - The result to match\n * @param handlers - Object with ok and err handlers, both returning Result\n * @returns A new Result from the appropriate handler\n *\n * @example\n * ```typescript\n * const result = await fetchUser(id);\n * return matchResult(result, {\n * ok: (user) => ok(transformUser(user)),\n * err: (error) => err(mapToAppError(error))\n * });\n * ```\n */\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\thandlers: {\n\t\tok: (value: T) => Result<U, F>;\n\t\terr: (error: E) => Result<U, F>;\n\t},\n): Result<U, F>;\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => Result<U, F>,\n\tonErr: (error: E) => Result<U, F>,\n): Result<U, F>;\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers:\n\t\t| ((value: T) => Result<U, F>)\n\t\t| { ok: (value: T) => Result<U, F>; err: (error: E) => Result<U, F> },\n\tonErr?: (error: E) => Result<U, F>,\n): Result<U, F> {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\treturn result.ok ? onOkOrHandlers(result.value) : onErr!(result.error);\n\t}\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Pipes a Result through multiple operations.\n * Each function receives the previous Result and returns a new Result.\n * Stops on first error.\n *\n * @param initial - The initial Result value\n * @param fns - Array of functions that take the previous Result and return a new Result\n * @returns The final Result after all operations\n *\n * @example\n * ```typescript\n * // Instead of nested andThen calls:\n * andThen(\n * updateCountryCode(code),\n * () => andThen(updateCurrencyCode(currency), () => updateLanguageCode(lang))\n * )\n *\n * // Use pipe (cleaner and more readable):\n * pipe(\n * updateCountryCode(code),\n * () => updateCurrencyCode(currency),\n * () => updateLanguageCode(lang)\n * )\n * ```\n *\n * @example With void results\n * ```typescript\n * setInitialData(initialData: JobConfigProps[\"initialData\"]): Result<void, JobDomainError> {\n * return pipe(\n * this.updateCountryCode(initialData.countryCode),\n * () => this.updateCurrencyCode(initialData.currencyCode),\n * () => this.updateLanguageCode(initialData.languageCode)\n * );\n * }\n * ```\n */\nexport function pipe<T, E>(\n\tinitial: Result<T, E>,\n\t...fns: Array<(prev: Result<T, E>) => Result<T, E>>\n): Result<T, E> {\n\tlet current = initial;\n\tfor (const fn of fns) {\n\t\tcurrent = fn(current);\n\t\tif (!current.ok) {\n\t\t\treturn current;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * Wraps a function that may throw exceptions into a Result type.\n * Catches any thrown exceptions and converts them to Err results.\n *\n * @param fn - Function that may throw exceptions\n * @param errorMapper - Optional function to transform the caught error\n * @returns A Result containing the function's return value or error\n *\n * @example\n * ```typescript\n * function riskyOperation(): string {\n * if (Math.random() > 0.5) {\n * throw new Error(\"Something went wrong\");\n * }\n * return \"success\";\n * }\n *\n * const result = tryCatch(() => riskyOperation());\n * if (result.ok) {\n * console.log(result.value); // \"success\"\n * } else {\n * console.error(result.error.message); // \"Something went wrong\"\n * }\n * ```\n *\n * @example With custom error mapper\n * ```typescript\n * const result = tryCatch(\n * () => riskyOperation(),\n * (error) => `Custom: ${error instanceof Error ? error.message : String(error)}`\n * );\n * ```\n */\nexport function tryCatch<T, E = Error>(\n\tfn: () => T,\n\terrorMapper?: (error: unknown) => E,\n): Result<T, E> {\n\ttry {\n\t\treturn ok(fn());\n\t} catch (error) {\n\t\tif (errorMapper) {\n\t\t\treturn err(errorMapper(error));\n\t\t}\n\t\treturn err((error instanceof Error ? error : new Error(String(error))) as E);\n\t}\n}\n\n/**\n * Wraps an async function that may throw exceptions into a Promise<Result>.\n * Catches any thrown exceptions and converts them to Err results.\n *\n * @param fn - Async function that may throw exceptions\n * @param errorMapper - Optional function to transform the caught error\n * @returns A Promise resolving to a Result containing the function's return value or error\n *\n * @example\n * ```typescript\n * async function riskyAsyncOperation(): Promise<string> {\n * if (Math.random() > 0.5) {\n * throw new Error(\"Something went wrong\");\n * }\n * return \"success\";\n * }\n *\n * const result = await tryCatchAsync(() => riskyAsyncOperation());\n * if (result.ok) {\n * console.log(result.value); // \"success\"\n * } else {\n * console.error(result.error.message); // \"Something went wrong\"\n * }\n * ```\n */\nexport async function tryCatchAsync<T, E = Error>(\n\tfn: () => Promise<T>,\n\terrorMapper?: (error: unknown) => E,\n): Promise<Result<T, E>> {\n\ttry {\n\t\tconst value = await fn();\n\t\treturn ok(value);\n\t} catch (error) {\n\t\tif (errorMapper) {\n\t\t\treturn err(errorMapper(error));\n\t\t}\n\t\treturn err((error instanceof Error ? error : new Error(String(error))) as E);\n\t}\n}\n\n","import { err, ok, type Result } from \"../core/result\";\nimport type { Id } from \"../core/id\";\nimport { AggregateRoot, type AggregateConfig, type IAggregateRoot } from \"./aggregate-root\";\nimport type {\n\tAggregateSnapshot,\n\tDomainEvent,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Interface for Event-Sourced Aggregate Roots.\n * Defines the contract for aggregates that manage state changes via event sourcing.\n *\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The union type of all domain events\n */\nexport interface IAggregateEventSourced<\n\tTId extends Id<string>,\n\tTEvent extends DomainEvent<string, unknown>,\n> extends IAggregateRoot<TId> {\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\treadonly pendingEvents: ReadonlyArray<TEvent>;\n\n\t/**\n\t * Reconstitutes the aggregate from an event history.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tloadFromHistory(history: TEvent[]): Result<void, string>;\n\n\t/**\n\t * Clears the list of pending events.\n\t */\n\tclearPendingEvents(): void;\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t */\n\thasPendingEvents(): boolean;\n\n\t/**\n\t * Returns the number of pending events.\n\t */\n\tgetEventCount(): number;\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t */\n\tgetLatestEvent(): TEvent | undefined;\n}\n\ntype Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;\n\n/**\n * Extended configuration options for AggregateEventSourced behavior.\n */\nexport interface AggregateEventSourcedConfig extends AggregateConfig {\n\t/**\n\t * Whether to automatically bump the version when applying new events.\n\t * Defaults to true. Set to false to manually control versioning.\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Event-Sourced Aggregate Roots (Entities).\n * \n * Extends `AggregateRoot` to create an Aggregate Root Entity with Event Sourcing capabilities.\n * The Aggregate Root is the parent Entity of the aggregate and represents it externally.\n * \n * The aggregate state (`TState`) contains:\n * - Child entities (Entities with id, but no own version)\n * - Value objects (immutable objects)\n * \n * All changes to child entities are versioned through the Aggregate Root. The version\n * applies to the entire aggregate, including all child entities.\n * \n * Extends `AggregateRoot` with Event Sourcing capabilities:\n * - Event tracking (pendingEvents)\n * - Event handlers for state transitions\n * - Event validation\n * - History replay\n *\n * Use this class when you want Event Sourcing with full event tracking\n * and replay capabilities.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity) with Event Sourcing\n * class Order extends AggregateEventSourced<OrderState, OrderEvent, OrderId> {\n * confirm(): void {\n * this.apply(createDomainEvent(\"OrderConfirmed\", {}));\n * }\n *\n * protected readonly handlers = {\n * OrderConfirmed: (state: OrderState): OrderState => ({\n * ...state,\n * status: \"confirmed\",\n * }),\n * };\n * }\n * ```\n */\nexport abstract class AggregateEventSourced<\n\tTState,\n\tTEvent extends DomainEvent<string, unknown>,\n\tTId extends Id<string>,\n> extends AggregateRoot<TState, TId, TEvent>\n\timplements IAggregateEventSourced<TId, TEvent> {\n\tprivate readonly _eventConfig: AggregateEventSourcedConfig;\n\tprivate readonly _eventAutoVersionBump: boolean;\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateEventSourcedConfig,\n\t) {\n\t\tsuper(id, initialState, config);\n\t\tthis._eventConfig = config ?? {};\n\t\tthis._eventAutoVersionBump = this._eventConfig.autoVersionBump ?? true;\n\t}\n\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\tpublic get pendingEvents(): ReadonlyArray<TEvent> {\n\t\treturn this.domainEvents;\n\t}\n\n\t/**\n\t * Clears the list of pending events.\n\t * Typically called after the events have been persisted.\n\t */\n\tpublic clearPendingEvents(): void {\n\t\tthis.clearDomainEvents();\n\t}\n\n\t/**\n\t * Validates an event before it is applied.\n\t * Override this method to add custom validation logic.\n\t * Return `ok(true)` if the event is valid, `err(message)` otherwise.\n\t *\n\t * @param event - The event to validate\n\t * @returns Result indicating if the event is valid\n\t *\n\t * @example\n\t * ```typescript\n\t * protected validateEvent(event: OrderEvent): Result<true, string> {\n\t * if (event.type === \"OrderShipped\" && this.state.status !== \"confirmed\") {\n\t * return err(\"Order must be confirmed before shipping\");\n\t * }\n\t * return ok(true);\n\t * }\n\t * ```\n\t */\n\tprotected validateEvent(_event: TEvent): Result<true, string> {\n\t\treturn ok(true);\n\t}\n\n\t/**\n\t * Applies an event to change the state and adds it\n\t * to the list of pending events.\n\t * Returns a Result type instead of throwing an error.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Indicates whether the event is new (and needs to be persisted)\n\t * or if it is being loaded from history\n\t * @returns Result<void, string> - ok if successful, err with error message if validation fails or handler is missing\n\t */\n\tprotected apply(event: TEvent, isNew = true): Result<void, string> {\n\t\t// Validate event before applying\n\t\tconst validation = this.validateEvent(event);\n\t\tif (!validation.ok) {\n\t\t\treturn err(\n\t\t\t\t`Event validation failed for ${event.type}: ${validation.error}`,\n\t\t\t);\n\t\t}\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers];\n\t\tif (!handler) {\n\t\t\treturn err(`Missing handler for event type: ${event.type}`);\n\t\t}\n\n\t\t// First, change the state\n\t\tthis._state = handler(\n\t\t\tthis._state,\n\t\t\tevent as Extract<TEvent, { type: TEvent[\"type\"] }>,\n\t\t);\n\n\t\t// Then (if new) add the event to the list and bump version\n\t\tif (isNew) {\n\t\t\tthis.addDomainEvent(event);\n\t\t\tif (this._eventAutoVersionBump) {\n\t\t\t\tthis.version = (this.version + 1) as Version;\n\t\t\t}\n\t\t}\n\n\t\treturn ok();\n\t}\n\n\t/**\n\t * Applies an event to change the state and adds it\n\t * to the list of pending events.\n\t * Throws an error if validation fails or handler is missing.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Indicates whether the event is new (and needs to be persisted)\n\t * or if it is being loaded from history\n\t * @throws Error if event validation fails or handler is missing\n\t */\n\tprotected applyUnsafe(event: TEvent, isNew = true): void {\n\t\t// Validate event before applying\n\t\tconst validation = this.validateEvent(event);\n\t\tif (!validation.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Event validation failed for ${event.type}: ${validation.error}`,\n\t\t\t);\n\t\t}\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers];\n\t\tif (!handler) {\n\t\t\tthrow new Error(`Missing handler for event type: ${event.type}`);\n\t\t}\n\n\t\t// First, change the state\n\t\tthis._state = handler(\n\t\t\tthis._state,\n\t\t\tevent as Extract<TEvent, { type: TEvent[\"type\"] }>,\n\t\t);\n\n\t\t// Then (if new) add the event to the list and bump version\n\t\tif (isNew) {\n\t\t\tthis.addDomainEvent(event);\n\t\t\tif (this._eventAutoVersionBump) {\n\t\t\t\tthis.version = (this.version + 1) as Version;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Only needed if `autoVersionBump` is disabled.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.version = (this.version + 1) as Version;\n\t}\n\n\t/**\n\t * Reconstitutes the aggregate from an event history.\n\t * Sets the version to the number of events in the history.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tpublic loadFromHistory(history: TEvent[]): Result<void, string> {\n\t\tfor (const event of history) {\n\t\t\tconst result = this.apply(event, false); // 'false' as it's not a new event\n\t\t\tif (!result.ok) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\t// Set version to the number of events in history\n\t\tthis.version = history.length as Version;\n\t\treturn ok();\n\t}\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t *\n\t * @returns true if there are pending events, false otherwise\n\t */\n\tpublic hasPendingEvents(): boolean {\n\t\treturn this.domainEvents.length > 0;\n\t}\n\n\t/**\n\t * Returns the number of pending events.\n\t *\n\t * @returns The count of pending events\n\t */\n\tpublic getEventCount(): number {\n\t\treturn this.domainEvents.length;\n\t}\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t *\n\t * @returns The most recent event or undefined if no events exist\n\t */\n\tpublic getLatestEvent(): TEvent | undefined {\n\t\tconst events = this.domainEvents;\n\t\treturn events[events.length - 1];\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot and applies events that occurred after the snapshot.\n\t * This is more efficient than replaying all events from the beginning.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t * @param eventsAfterSnapshot - Events that occurred after the snapshot was taken\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * const eventsAfter = await eventStore.getEventsAfter(aggregateId, snapshot.version);\n\t * aggregate.restoreFromSnapshotWithEvents(snapshot, eventsAfter);\n\t * ```\n\t */\n\tpublic restoreFromSnapshotWithEvents(\n\t\tsnapshot: AggregateSnapshot<TState>,\n\t\teventsAfterSnapshot: TEvent[],\n\t): Result<void, string> {\n\t\tthis._state = snapshot.state;\n\t\tthis.version = snapshot.version;\n\n\t\t// Apply events that occurred after the snapshot\n\t\tfor (const event of eventsAfterSnapshot) {\n\t\t\tconst result = this.apply(event, false);\n\t\t\tif (!result.ok) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\t// Set version to snapshot version + events after snapshot\n\t\tthis.version = (snapshot.version + eventsAfterSnapshot.length) as Version;\n\t\treturn ok();\n\t}\n\n\t/**\n\t * A map of event types to their corresponding handlers.\n\t * Subclasses MUST implement this property.\n\t */\n\tprotected abstract readonly handlers: {\n\t\t[K in TEvent[\"type\"]]: Handler<TState, Extract<TEvent, { type: K }>>;\n\t};\n}\n\n","import type { Result } from \"../core/result\";\nimport { err, ok } from \"../core/result\";\nimport type { Command, CommandHandler } from \"./command\";\n\n/**\n * Command Bus interface for dispatching commands to their handlers.\n * Provides a centralized way to execute commands with handler registration.\n *\n * @example\n * ```typescript\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", createOrderHandler);\n *\n * const result = await bus.execute({\n * type: \"CreateOrder\",\n * customerId: \"123\",\n * items: [...]\n * });\n * ```\n */\nexport interface ICommandBus {\n\t/**\n\t * Executes a command by dispatching it to the registered handler.\n\t *\n\t * @param command - The command to execute\n\t * @returns Result containing the success value or error message\n\t */\n\texecute<C extends Command, R>(command: C): Promise<Result<R, string>>;\n\n\t/**\n\t * Registers a handler for a specific command type.\n\t *\n\t * @param commandType - The command type to register the handler for\n\t * @param handler - The handler function for this command type\n\t */\n\tregister<C extends Command, R>(\n\t\tcommandType: C[\"type\"],\n\t\thandler: CommandHandler<C, R>,\n\t): void;\n}\n\n/**\n * Simple in-memory command bus implementation.\n * Handlers are stored in a Map and dispatched based on command type.\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, validation, authorization)\n * - Error handling and retry logic\n * - Timeout handling\n * - Metrics and observability\n * - Transaction management\n * - Dead letter queue support\n *\n * The `CommandHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @example\n * ```typescript\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", async (cmd) => {\n * // ... handler logic\n * return ok(orderId);\n * });\n *\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * ```\n */\nexport class CommandBus implements ICommandBus {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, CommandHandler<any, any>>();\n\n\tregister<C extends Command, R>(\n\t\tcommandType: C[\"type\"],\n\t\thandler: CommandHandler<C, R>,\n\t): void {\n\t\tthis.handlers.set(commandType, handler);\n\t}\n\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(command.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for command type: ${command.type}`);\n\t\t}\n\t\ttry {\n\t\t\treturn await handler(command);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n}\n\n","import type { EventBus, Outbox } from \"../events/ports\";\nimport type { UnitOfWork } from \"../repo/uow\";\n\n/**\n * Helper function for executing commands within a transaction.\n * Handles event persistence via outbox and optional event bus publishing.\n *\n * @param deps - Dependencies including outbox, optional event bus, and unit of work\n * @param fn - Function that returns result and events\n * @returns The result wrapped in a transaction\n *\n * @example\n * ```typescript\n * const result = await withCommit(\n * { outbox, bus, uow },\n * async () => {\n * const order = Order.create(customerId, items);\n * await repository.save(order);\n * return {\n * result: order.id,\n * events: order.pendingEvents\n * };\n * }\n * );\n * ```\n */\nexport function withCommit<Evt, R>(\n\tdeps: {\n\t\toutbox: Outbox<Evt>;\n\t\tbus?: EventBus<Evt>;\n\t\tuow: UnitOfWork;\n\t},\n\tfn: () => Promise<{ result: R; events: ReadonlyArray<Evt> }>,\n) {\n\treturn deps.uow.transactional(async () => {\n\t\tconst { result, events } = await fn();\n\t\tawait deps.outbox.add(events);\n\t\tif (deps.bus) await deps.bus.publish(events);\n\t\treturn result;\n\t});\n}\n","import { err, ok, type Result } from \"../core/result\";\nimport type { Query, QueryHandler } from \"./query\";\n\n/**\n * Query Bus interface for dispatching queries to their handlers.\n * Provides a centralized way to execute queries with handler registration.\n *\n * @example\n * ```typescript\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", getOrderHandler);\n *\n * const order = await bus.execute({\n * type: \"GetOrder\",\n * orderId: \"123\"\n * });\n * ```\n */\nexport interface IQueryBus {\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Returns a Result type instead of throwing an error.\n\t *\n\t * @param query - The query to execute\n\t * @returns Result containing the query result if successful, or an error message if no handler is registered\n\t */\n\texecute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Throws an error if no handler is registered.\n\t *\n\t * @param query - The query to execute\n\t * @returns The query result\n\t * @throws Error if no handler is registered for the query type\n\t */\n\texecuteUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\n\t/**\n\t * Registers a handler for a specific query type.\n\t *\n\t * @param queryType - The query type to register the handler for\n\t * @param handler - The handler function for this query type\n\t */\n\tregister<Q extends Query, R>(\n\t\tqueryType: Q[\"type\"],\n\t\thandler: QueryHandler<Q, R>,\n\t): void;\n}\n\n/**\n * Type map for query types to their return types.\n * Used to improve type inference in QueryBus.\n */\ntype QueryTypeMap = Record<string, unknown>;\n\n/**\n * Simple in-memory query bus implementation.\n * Handlers are stored in a Map and dispatched based on query type.\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, caching, rate limiting)\n * - Error handling\n * - Timeout handling\n * - Metrics and observability\n * - Query result caching\n * - Rate limiting\n *\n * The `QueryHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @example\n * ```typescript\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", async (query) => {\n * return await repository.getById(query.orderId);\n * });\n *\n * const order = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * ```\n */\nexport class QueryBus<TMap extends QueryTypeMap = QueryTypeMap>\n\timplements IQueryBus\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, QueryHandler<any, any>>();\n\n\tregister<Q extends Query, R>(\n\t\tqueryType: Q[\"type\"],\n\t\thandler: QueryHandler<Q, R>,\n\t): void {\n\t\tthis.handlers.set(queryType, handler);\n\t}\n\n\tasync execute<Q extends Query & { type: keyof TMap }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await handler(query);\n\t\t\treturn ok(result);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\treturn handler(query);\n\t}\n}\n\n","import { err, ok, type Result } from \"./result\";\n\n/**\n * Guard function that validates a condition and returns a Result.\n * Returns `ok(true)` if the condition is met, otherwise `err(error)`.\n *\n * @param cond - The condition to check\n * @param error - Error message if condition fails\n * @returns Result<true, string>\n *\n * @example\n * ```typescript\n * const result = guard(id.length > 0, \"ID cannot be empty\");\n * if (!result.ok) {\n * return err(result.error);\n * }\n * ```\n */\nexport function guard(cond: boolean, error: string): Result<true, string> {\n\treturn cond ? ok(true) : err(error);\n}\n","import type { DomainEvent } from \"../aggregate/aggregate\";\nimport type { EventBus, EventHandler } from \"./ports\";\n\n/**\n * Simple in-memory event bus implementation.\n * Supports multiple subscribers per event type (pub/sub pattern).\n *\n * @template Evt - The type of domain events (must extend DomainEvent)\n *\n * @example\n * ```typescript\n * const bus = new EventBusImpl<OrderEvent>();\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await sendEmail(event.payload.customerId);\n * });\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await logEvent(event);\n * });\n *\n * await bus.publish([orderCreatedEvent]);\n * // Both handlers will be called\n * ```\n */\nexport class EventBusImpl<Evt extends DomainEvent<string, unknown>>\n\timplements EventBus<Evt>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, Set<EventHandler<any>>>();\n\n\tsubscribe<T extends Evt>(\n\t\teventType: string,\n\t\thandler: EventHandler<T>,\n\t): () => void {\n\t\tconst type = eventType;\n\t\tif (!this.handlers.has(type)) {\n\t\t\tthis.handlers.set(type, new Set());\n\t\t}\n\t\tconst handlersForType = this.handlers.get(type)!;\n\t\thandlersForType.add(handler);\n\n\t\t// Return unsubscribe function\n\t\treturn () => {\n\t\t\thandlersForType.delete(handler);\n\t\t\tif (handlersForType.size === 0) {\n\t\t\t\tthis.handlers.delete(type);\n\t\t\t}\n\t\t};\n\t}\n\n\tonce<T extends Evt>(eventType: string): Promise<T> {\n\t\treturn new Promise<T>((resolve) => {\n\t\t\tconst unsubscribe = this.subscribe<T>(eventType, ((event: T) => {\n\t\t\t\tunsubscribe();\n\t\t\t\tresolve(event);\n\t\t\t}) as EventHandler<T>);\n\t\t});\n\t}\n\n\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\n\t\tconst errors: Error[] = [];\n\n\t\tfor (const event of events) {\n\t\t\tconst handlersForType = this.handlers.get(event.type);\n\t\t\tif (handlersForType) {\n\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\tArray.from(handlersForType).map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason\n\t\t\t\t\t\t\t\t: new Error(String(result.reason)),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (errors.length === 1) {\n\t\t\tthrow errors[0];\n\t\t}\n\t\tif (errors.length > 1) {\n\t\t\tthrow new AggregateError(errors, \"Multiple event handlers failed\");\n\t\t}\n\t}\n}\n\n","import { isBuiltInObject } from \"./is-built-in\";\n\nexport type Key = string | symbol;\nexport type PathSegment = string | number | symbol;\n\nexport interface DeepOmitOptions {\n\t/**\n\t * Keys to ignore everywhere in the object tree.\n\t * Only applies to object properties, not Map/Set/TypedArray contents.\n\t */\n\treadonly ignoreKeys?: readonly Key[];\n\n\t/**\n\t * Fine-grained control: Key + path (without current key).\n\t * Example path: [\"user\", \"meta\", 0, \"data\"]\n\t */\n\treadonly ignoreKeyPredicate?: (\n\t\tkey: Key,\n\t\tpath: readonly PathSegment[],\n\t) => boolean;\n}\n\n/**\n * Creates a deep copy of `value` with certain keys removed according to the provided rules.\n *\n * This function recursively traverses the object tree and removes keys that match\n * the criteria specified in `options`. Built-in types (Date, Map, Set, TypedArrays, etc.)\n * are treated atomically and not modified.\n *\n * @param value - The value to create a deep copy from\n * @param options - Options specifying which keys to ignore\n * @returns A deep copy of `value` with specified keys removed\n *\n * @example\n * ```ts\n * const obj = { a: 1, b: { c: 2, d: 3 } };\n * const result = deepOmit(obj, { ignoreKeys: ['d'] });\n * // result: { a: 1, b: { c: 2 } }\n * ```\n */\nexport function deepOmit<T>(value: T, options: DeepOmitOptions): T {\n\tconst visited = new WeakMap<object, unknown>();\n\treturn omitInternal(value, options, [], visited) as T;\n}\n\nfunction omitInternal(\n\tvalue: unknown,\n\toptions: DeepOmitOptions,\n\tpath: PathSegment[],\n\tvisited: WeakMap<object, unknown>,\n): unknown {\n\tif (value === null) return value;\n\tconst type = typeof value;\n\n\t// Primitives and functions are passed through unchanged\n\tif (type !== \"object\") return value;\n\n\tconst obj = value as object;\n\n\t// Cycles: return cached value if already visited\n\tconst cached = visited.get(obj);\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\tconst tag = Object.prototype.toString.call(obj);\n\n\t// Arrays: recursively process elements\n\tif (tag === \"[object Array]\") {\n\t\tconst arr = obj as unknown[];\n\t\tconst clone: unknown[] = new Array(arr.length);\n\t\tvisited.set(obj, clone);\n\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tpath.push(i);\n\t\t\tclone[i] = omitInternal(arr[i], options, path, visited);\n\t\t\tpath.pop();\n\t\t}\n\t\treturn clone;\n\t}\n\n\t// Built-ins: treat atomically, no key filtering inside\n\t// Future-proof detection: check if object is a built-in type\n\tif (isBuiltInObject(obj, tag)) {\n\t\treturn value;\n\t}\n\n\t// Plain / Custom Objects: filter keys, recursively process values\n\tconst clone = Object.create(Object.getPrototypeOf(obj));\n\tvisited.set(obj, clone);\n\n\tconst stringKeys = Object.keys(obj);\n\tconst symbolKeys = Object.getOwnPropertySymbols(obj);\n\tconst keys: Key[] = [...stringKeys, ...symbolKeys];\n\n\tfor (const key of keys) {\n\t\tif (shouldIgnoreKey(key, path, options)) continue;\n\n\t\tpath.push(key);\n\t\t(clone as Record<PropertyKey, unknown>)[key] = omitInternal(\n\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\toptions,\n\t\t\tpath,\n\t\t\tvisited,\n\t\t);\n\t\tpath.pop();\n\t}\n\n\treturn clone;\n}\n\nfunction shouldIgnoreKey(\n\tkey: Key,\n\tpath: readonly PathSegment[],\n\toptions: DeepOmitOptions,\n): boolean {\n\tif (options.ignoreKeys?.includes(key)) {\n\t\treturn true;\n\t}\n\tif (options.ignoreKeyPredicate?.(key, path)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n","import { deepEqual } from \"./deep-equal\";\nimport { type DeepOmitOptions, deepOmit } from \"./deep-omit\";\n\nexport type DeepEqualExceptOptions = DeepOmitOptions;\n\n/**\n * Performs a deep equality comparison between two values after omitting specified keys.\n * \n * This function first removes the specified keys from both values using `deepOmit`,\n * then performs a deep equality check using `deepEqual`.\n * \n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param options - Options specifying which keys to omit before comparison\n * @returns `true` if the values are deeply equal after omitting specified keys, `false` otherwise\n * \n * @example\n * ```ts\n * const obj1 = { id: 1, name: \"Alice\", updatedAt: \"2024-01-01\" };\n * const obj2 = { id: 2, name: \"Alice\", updatedAt: \"2024-01-02\" };\n * \n * deepEqualExcept(obj1, obj2, { ignoreKeys: [\"id\", \"updatedAt\"] }); // true\n * ```\n */\nexport function deepEqualExcept(\n\ta: unknown,\n\tb: unknown,\n\toptions: DeepEqualExceptOptions,\n): boolean {\n\tconst prunedA = deepOmit(a, options);\n\tconst prunedB = deepOmit(b, options);\n\treturn deepEqual(prunedA, prunedB);\n}\n","import { deepEqual } from \"../utils/array/deep-equal\";\nimport {\n deepEqualExcept,\n type DeepEqualExceptOptions,\n} from \"../utils/array/deep-equal-except\";\nimport { err, ok, type Result } from \"../core/result\";\n\n// ============================================================================\n// Functional Value Object API\n// ============================================================================\n\nexport type VO<T> = Readonly<T>;\n\n/**\n * Deep freezes an object and all its nested properties recursively.\n * This ensures true immutability for value objects with nested structures.\n * Handles circular references by tracking visited objects.\n */\nexport function deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n // Handle null and non-objects\n if (obj === null || typeof obj !== \"object\") {\n return obj as Readonly<T>;\n }\n\n // Handle circular references\n if (visited.has(obj as object)) {\n return obj as Readonly<T>;\n }\n\n // Mark as visited\n visited.add(obj as object);\n\n // Retrieve the property names defined on obj\n const propNames = Object.getOwnPropertyNames(obj);\n\n // Freeze properties before freezing self\n for (const name of propNames) {\n const value = (obj as Record<string, unknown>)[name];\n\n // Freeze value if it is an object or array\n if (value && (typeof value === \"object\" || Array.isArray(value))) {\n deepFreeze(value, visited);\n }\n }\n\n return Object.freeze(obj) as Readonly<T>;\n}\n\n/**\n * Creates a deeply immutable value object from the given data.\n * All nested objects and arrays are frozen recursively.\n *\n * @param t - The data to convert into a value object\n * @returns A deeply frozen, immutable value object\n *\n * @example\n * ```typescript\n * const address = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * // address.coordinates.lat = 99; // ❌ Error: Cannot assign to read-only property\n * ```\n */\nexport function vo<T>(t: T): VO<T> {\n return deepFreeze({ ...t });\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison that handles:\n * - Nested objects and arrays\n * - Primitives (including NaN)\n * - Dates, Maps, Sets, RegExp\n * - TypedArrays and DataView\n * - Symbol keys\n * - Circular references\n *\n * @param a - First value object\n * @param b - Second value object\n * @returns true if both objects have the same values, false otherwise\n *\n * @example\n * ```typescript\n * const money1 = vo({ amount: 100, currency: \"USD\" });\n * const money2 = vo({ amount: 100, currency: \"USD\" });\n * voEquals(money1, money2); // true\n *\n * const address1 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * const address2 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * voEquals(address1, address2); // true\n * ```\n */\nexport function voEquals<T>(a: VO<T>, b: VO<T>): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * Compares two value objects for equality while ignoring specified keys.\n * Useful for comparing value objects that contain metadata or optional fields\n * that should not affect equality comparison.\n *\n * @param a - First value object\n * @param b - Second value object\n * @param options - Options specifying which keys to ignore during comparison\n * @returns true if both objects have the same values (after ignoring specified keys), false otherwise\n *\n * @example\n * ```typescript\n * // Value object with metadata\n * const address1 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-02\" }\n * });\n *\n * const address2 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-03\" }\n * });\n *\n * // Compare ignoring metadata timestamps\n * voEqualsExcept(address1, address2, {\n * ignoreKeys: [\"updatedAt\"],\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n *\n * // Compare ignoring all metadata\n * voEqualsExcept(address1, address2, {\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n * ```\n */\nexport function voEqualsExcept<T>(\n a: VO<T>,\n b: VO<T>,\n options: DeepEqualExceptOptions,\n): boolean {\n return deepEqualExcept(a, b, options);\n}\n\n/**\n * Creates a value object with optional validation.\n * Returns a Result type instead of throwing an error.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns Result containing the value object if valid, or an error message if validation fails\n *\n * @example\n * ```typescript\n * const result = voWithValidation(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n *\n * if (result.ok) {\n * console.log(result.value); // Use the value object\n * } else {\n * console.error(result.error); // Handle validation error\n * }\n * ```\n */\nexport function voWithValidation<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): Result<VO<T>, string> {\n if (!validate(t)) {\n return err(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return ok(vo(t));\n}\n\n/**\n * Creates a value object with optional validation.\n * Throws an error if validation fails.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns A deeply frozen, immutable value object\n * @throws Error if validation fails\n *\n * @example\n * ```typescript\n * const money = voWithValidationUnsafe(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n * ```\n */\nexport function voWithValidationUnsafe<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): VO<T> {\n if (!validate(t)) {\n throw new Error(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return vo(t);\n}\n\n// ============================================================================\n// Class-based Value Object API\n// ============================================================================\n\n/**\n * Interface for Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport interface IValueObject<T extends object> {\n /**\n * The immutable properties of the value object.\n */\n readonly props: Readonly<T>;\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal\n */\n equals(other: IValueObject<T>): boolean;\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n clone(props?: Partial<T>): IValueObject<T>;\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n toJSON(): Readonly<T>;\n}\n\n/**\n * Abstract base class for creating Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport abstract class ValueObject<T extends object> implements IValueObject<T> {\n public readonly props: Readonly<T>;\n\n /**\n * Creates a new ValueObject.\n * The properties are deeply frozen to ensure immutability.\n *\n * @param props - The properties of the value object\n * @example\n * ```ts\n * class Money extends ValueObject<{ amount: number; currency: string }> {\n * constructor(props: { amount: number; currency: string }) {\n * super(props);\n * }\n *\n * protected validate(props: { amount: number; currency: string }): void {\n * if (props.amount < 0) throw new Error(\"Amount cannot be negative\");\n * }\n * }\n * ```\n */\n constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze({ ...props });\n }\n\n /**\n * Optional validation hook that can be overridden by subclasses.\n * Should throw an error if validation fails.\n *\n * @param props - The properties to validate\n * @throws Error if validation fails\n */\n protected validate(props: T): void {\n // Default implementation does nothing\n }\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties and checks for constructor equality.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal and constructors match\n */\n public equals(other: ValueObject<T>): boolean {\n if (other === null || other === undefined) {\n return false;\n }\n\n if (this.constructor !== other.constructor) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n public clone(props?: Partial<T>): this {\n const Constructor = this.constructor as new (props: T) => this;\n return new Constructor({ ...this.props, ...(props || {}) });\n }\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n public toJSON(): Readonly<T> {\n return this.props;\n }\n\n\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/array/is-built-in.ts","../src/utils/array/deep-equal.ts","../src/utils/array/deep-omit.ts","../src/utils/array/deep-equal-except.ts","../src/value-object/value-object.ts","../src/aggregate/domain-event.ts","../src/aggregate/aggregate.ts","../src/entity/entity.ts","../src/aggregate/aggregate-root.ts","../src/core/errors.ts","../src/aggregate/event-sourced-aggregate.ts","../src/app/command-bus.ts","../src/app/handler.ts","../src/app/query-bus.ts","../src/events/event-bus.ts"],"names":["tagA","tagB","len","clone","err","ok"],"mappings":";;;;;;AAaA,IAAM,aAAA,uBAAyC,GAAA,CAAI;AAAA,EAClD,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,cAAA;AAAA,EACA,cAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,gBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,sBAAA;AAAA,EACA,4BAAA;AAAA,EACA;AACD,CAAC,CAAA;AAWM,SAAS,eAAA,CAAgB,KAAa,GAAA,EAAsB;AAElE,EAAA,IAAI,GAAA,CAAI,QAAA,CAAS,QAAQ,CAAA,EAAG,OAAO,IAAA;AAEnC,EAAA,IAAI,WAAA,CAAY,MAAA,CAAO,GAAG,CAAA,EAAG,OAAO,IAAA;AACpC,EAAA,OAAO,aAAA,CAAc,IAAI,GAAG,CAAA;AAC7B;AANgB,MAAA,CAAA,eAAA,EAAA,iBAAA,CAAA;;;ACrChB,IAAM,WAAW,MAAA,CAAO,SAAA;AACxB,IAAM,cAAc,QAAA,CAAS,QAAA;AAC7B,IAAM,YAAY,QAAA,CAAS,cAAA;AA4BpB,SAAS,SAAA,CAAU,GAAY,CAAA,EAAqB;AAC1D,EAAA,OAAO,cAAA,CAAe,CAAA,EAAG,CAAA,kBAAG,I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A,CAAS,GAAA,CAAI,MAAM,IAAI,CAAA;AACpD,MAAA,IAAI,eAAA,EAAiB;AAGpB,QAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,UAAA;AAAA,UAC7B,eAAA,CAAgB,OAAM,CAAE,GAAA,CAAI,CAAC,OAAA,KAAY,OAAA,CAAQ,KAAK,CAAC;AAAA,SACxD;AACA,QAAA,KAAA,MAAW,UAAU,OAAA,EAAS;AAC7B,UAAA,IAAI,MAAA,CAAO,WAAW,UAAA,EAAY;AACjC,YAAA,MAAA,CAAO,IAAA;AAAA,cACN,MAAA,CAAO,MAAA,YAAkB,KAAA,GACtB,MAAA,CAAO,MAAA,GACP,IAAI,KAAA,CAAM,MAAA,CAAO,MAAA,CAAO,MAAM,CAAC;AAAA,aACnC;AAAA,UACD;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAEA,IAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACxB,MAAA,MAAM,OAAO,CAAC,CAAA;AAAA,IACf;AACA,IAAA,IAAI,MAAA,CAAO,SAAS,CAAA,EAAG;AACtB,MAAA,MAAM,IAAI,cAAA,CAAe,MAAA,EAAQ,gCAAgC,CAAA;AAAA,IAClE;AAAA,EACD;AACD","file":"index.js","sourcesContent":["/**\n * Set of `Object.prototype.toString.call(x)` tags that the library treats\n * as built-in atomic types. Members of this set are compared/cloned by\n * reference (or with type-specific logic) rather than walked structurally.\n *\n * The detection is purely tag-based — `Object.prototype.toString` reads\n * `Symbol.toStringTag`, which gives the same answer across realms (an\n * iframe's `Date` has the same tag as the main window's `Date`). The\n * previous strategy also checked `globalThis[name] === constructor` and a\n * `proto !== Object.prototype` heuristic; both broke for cross-realm\n * objects and the latter additionally misclassified ordinary user classes\n * as built-ins. Tag-only is the simplest robust choice.\n */\nconst BUILT_IN_TAGS: ReadonlySet<string> = new Set([\n\t\"[object Date]\",\n\t\"[object RegExp]\",\n\t\"[object Map]\",\n\t\"[object Set]\",\n\t\"[object WeakMap]\",\n\t\"[object WeakSet]\",\n\t\"[object Promise]\",\n\t\"[object Error]\",\n\t\"[object Boolean]\",\n\t\"[object Number]\",\n\t\"[object String]\",\n\t\"[object ArrayBuffer]\",\n\t\"[object SharedArrayBuffer]\",\n\t\"[object DataView]\",\n]);\n\n/**\n * Returns `true` when `obj` is a built-in JavaScript type that should be\n * treated atomically (compared/cloned as a unit, not walked structurally).\n * Cross-realm safe.\n *\n * @param obj - The object to classify\n * @param tag - The result of `Object.prototype.toString.call(obj)` — passed\n * in so callers that already computed it don't pay twice\n */\nexport function isBuiltInObject(obj: object, tag: string): boolean {\n\t// All TypedArrays produce tags ending in \"Array]\" — future-proof match.\n\tif (tag.endsWith(\"Array]\")) return true;\n\t// ArrayBuffer view covers DataView + all TypedArrays as a belt-and-braces.\n\tif (ArrayBuffer.isView(obj)) return true;\n\treturn BUILT_IN_TAGS.has(tag);\n}\n","import { isBuiltInObject } from \"./is-built-in\";\n\nconst objProto = Object.prototype;\nconst objToString = objProto.toString;\nconst objHasOwn = objProto.hasOwnProperty;\n\n/**\n * Performs a deep equality check between two values.\n *\n * This function compares values recursively, handling:\n * - Primitives (with special handling for NaN)\n * - Arrays (nested arrays supported)\n * - Objects (plain objects and class instances)\n * - TypedArrays (Uint8Array, Int32Array, etc.)\n * - DataView\n * - Maps and Sets\n * - Dates and RegExp\n * - Wrapper objects (Boolean, Number, String)\n * - Circular references (detected and handled)\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @returns `true` if the values are deeply equal, `false` otherwise\n *\n * @example\n * ```ts\n * deepEqual([1, 2, 3], [1, 2, 3]); // true\n * deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); // true\n * deepEqual(NaN, NaN); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n\treturn deepEqualInner(a, b, new WeakMap<object, WeakSet<object>>());\n}\n\n/**\n * Visited pair tracker for cycle detection. The cache is a pair-set:\n * for every left-hand object we keep the set of right-hand objects we\n * have already paired it with. Encountering an already-known pair returns\n * the cycle hypothesis (assume equal); a new (a, b') pair with b' ≠ any\n * previously cached b for that a is walked normally — the previous shape\n * (`WeakMap<object, object>`) could only remember one B per A, which\n * could short-circuit unrelated comparisons that happened to revisit the\n * same A with a different B.\n */\ntype VisitedPairs = WeakMap<object, WeakSet<object>>;\n\n/**\n * Internal recursive function for deep equality comparison.\n *\n * @internal\n */\nfunction deepEqualInner(\n\ta: unknown,\n\tb: unknown,\n\tvisited: VisitedPairs,\n): boolean {\n\t// 1. Fast path: reference equality\n\tif (a === b) return true;\n\n\tconst typeA = typeof a;\n\tconst typeB = typeof b;\n\n\t// 2. If one is not an object → primitive / function\n\tif (typeA !== \"object\" || a === null || typeB !== \"object\" || b === null) {\n\t\t// Special case: NaN should be equal\n\t\tif (typeA === \"number\" && typeB === \"number\") {\n\t\t\treturn Number.isNaN(a as number) && Number.isNaN(b as number);\n\t\t}\n\t\t// Everything else is directly unequal with !== (including functions)\n\t\treturn false;\n\t}\n\n\t// From here on: both are non-null objects\n\n\tconst objA = a as object;\n\tconst objB = b as object;\n\n\t// 3. Cycles: already seen this exact (a, b) pair?\n\tlet cachedBs = visited.get(objA);\n\tif (cachedBs?.has(objB)) {\n\t\t// Cycle hypothesis: pretend equal so the walk can terminate. If the\n\t\t// structure is actually unequal elsewhere, a different recursive\n\t\t// branch will surface the mismatch.\n\t\treturn true;\n\t}\n\tif (!cachedBs) {\n\t\tcachedBs = new WeakSet();\n\t\tvisited.set(objA, cachedBs);\n\t}\n\tcachedBs.add(objB);\n\n\t// 4. Handle Typed Arrays / DataView first\n\tif (ArrayBuffer.isView(objA) || ArrayBuffer.isView(objB)) {\n\t\tif (!ArrayBuffer.isView(objA) || !ArrayBuffer.isView(objB)) return false;\n\n\t\tconst tagA = objToString.call(objA);\n\t\tconst tagB = objToString.call(objB);\n\t\tif (tagA !== tagB) return false;\n\n\t\t// DataView: compare byte by byte\n\t\tif (tagA === \"[object DataView]\") {\n\t\t\tconst viewA = objA as DataView;\n\t\t\tconst viewB = objB as DataView;\n\t\t\tif (viewA.byteLength !== viewB.byteLength) return false;\n\n\t\t\tconst len = viewA.byteLength;\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (viewA.getUint8(i) !== viewB.getUint8(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// Typed Arrays: element by element (length + numeric index access are\n\t\t// part of the TypedArray contract; the indexed read is sound).\n\t\tconst arrA = objA as unknown as Record<number, unknown> & { length: number };\n\t\tconst arrB = objB as unknown as Record<number, unknown> & { length: number };\n\n\t\tconst len = arrA.length;\n\t\tif (len !== arrB.length) return false;\n\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tif (arrA[i] !== arrB[i]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// 5. Tag-based type detection (robust across realms)\n\tconst tagA = objToString.call(objA);\n\tconst tagB = objToString.call(objB);\n\tif (tagA !== tagB) return false;\n\n\tswitch (tagA) {\n\t\tcase \"[object Array]\": {\n\t\t\tconst arrA = objA as unknown[];\n\t\t\tconst arrB = objB as unknown[];\n\t\t\tconst len = arrA.length;\n\t\t\tif (len !== arrB.length) return false;\n\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (!deepEqualInner(arrA[i], arrB[i], visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Map]\": {\n\t\t\tconst mapA = objA as Map<unknown, unknown>;\n\t\t\tconst mapB = objB as Map<unknown, unknown>;\n\n\t\t\tif (mapA.size !== mapB.size) return false;\n\n\t\t\tfor (const [key, valA] of mapA) {\n\t\t\t\t// Map keys according to JS semantics: reference / SameValueZero\n\t\t\t\tif (!mapB.has(key)) return false;\n\t\t\t\tconst valB = mapB.get(key);\n\t\t\t\tif (!deepEqualInner(valA, valB, visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Set]\": {\n\t\t\tconst setA = objA as Set<unknown>;\n\t\t\tconst setB = objB as Set<unknown>;\n\n\t\t\tif (setA.size !== setB.size) return false;\n\n\t\t\t// Set elements: same reference (JS semantics)\n\t\t\tfor (const value of setA) {\n\t\t\t\tif (!setB.has(value)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Date]\": {\n\t\t\tconst timeA = (objA as Date).getTime();\n\t\t\tconst timeB = (objB as Date).getTime();\n\t\t\treturn timeA === timeB;\n\t\t}\n\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst regA = objA as RegExp;\n\t\t\tconst regB = objB as RegExp;\n\t\t\treturn regA.source === regB.source && regA.flags === regB.flags;\n\t\t}\n\n\t\tcase \"[object Boolean]\":\n\t\tcase \"[object Number]\":\n\t\tcase \"[object String]\": {\n\t\t\t// Wrapper objects (new Boolean/Number/String)\n\t\t\treturn (objA as any).valueOf() === (objB as any).valueOf();\n\t\t}\n\n\t\tdefault: {\n\t\t\t// 6. Check if this is an unhandled built-in type (future-proof)\n\t\t\t// If both are built-ins but not handled above, they should be compared by reference\n\t\t\t// (since we don't know their internal structure)\n\t\t\tif (isBuiltInObject(objA, tagA) && isBuiltInObject(objB, tagB)) {\n\t\t\t\t// Unhandled built-in types: compare by reference as fallback\n\t\t\t\t// This ensures new built-ins don't fall through to plain object comparison\n\t\t\t\treturn objA === objB;\n\t\t\t}\n\n\t\t\t// 7. Fallback: plain / custom objects → compare own enumerable keys + values\n\t\t\tconst recA = objA as Record<string | symbol, unknown>;\n\t\t\tconst recB = objB as Record<string | symbol, unknown>;\n\n\t\t\tconst stringKeysA = Object.keys(objA as object);\n\t\t\tconst stringKeysB = Object.keys(objB as object);\n\t\t\tif (stringKeysA.length !== stringKeysB.length) return false;\n\n\t\t\tconst symbolKeysA = Object.getOwnPropertySymbols(objA as object);\n\t\t\tconst symbolKeysB = Object.getOwnPropertySymbols(objB as object);\n\t\t\tif (symbolKeysA.length !== symbolKeysB.length) return false;\n\n\t\t\t// Build the B-side symbol set once; the previous impl rebuilt the\n\t\t\t// array and ran .includes per key, which was quadratic.\n\t\t\tconst symbolKeysBSet = new Set<symbol>(symbolKeysB);\n\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!objHasOwn.call(objB, key)) return false;\n\t\t\t}\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!symbolKeysBSet.has(key)) return false;\n\t\t\t}\n\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!deepEqualInner(recA[key], recB[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!deepEqualInner(recA[key], recB[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n}\n","import { isBuiltInObject } from \"./is-built-in\";\n\nexport type Key = string | symbol;\nexport type PathSegment = string | number | symbol;\n\nexport interface DeepOmitOptions {\n\t/**\n\t * Keys to ignore everywhere in the object tree.\n\t * Only applies to object properties, not Map/Set/TypedArray contents.\n\t */\n\treadonly ignoreKeys?: readonly Key[];\n\n\t/**\n\t * Fine-grained control: Key + path (without current key).\n\t * Example path: [\"user\", \"meta\", 0, \"data\"]\n\t */\n\treadonly ignoreKeyPredicate?: (\n\t\tkey: Key,\n\t\tpath: readonly PathSegment[],\n\t) => boolean;\n}\n\n/**\n * Creates a deep copy of `value` with certain keys removed according to the\n * provided rules.\n *\n * Walks the object tree and skips keys that match `ignoreKeys` /\n * `ignoreKeyPredicate`. Built-in atomic types (Date, RegExp, Map, Set,\n * TypedArrays, ArrayBuffer, DataView) are cloned by type rather than walked\n * — their internal structure has no key filtering to apply. Cycles are\n * preserved: a cycle `a → a` clones to `a' → a'`.\n *\n * **Prototype-pollution safety.** `__proto__` and `constructor` keys\n * encountered as *own* properties of the input (typical of `JSON.parse`\n * output) are copied as inert data properties via `Object.defineProperty`\n * so the clone graph cannot bleed into `Object.prototype`.\n *\n * **Class instances.** When the input is a class instance, the clone is\n * built via `Object.create(proto)` so the prototype is preserved, but the\n * constructor is NOT re-invoked — so class invariants enforced by the\n * constructor are not re-checked. `deepOmit` is therefore best used for\n * comparison/serialisation (`voEqualsExcept`, `deepEqualExcept`), not as\n * a general-purpose clone for behaviour-carrying objects.\n *\n * @param value - The value to create a deep copy from\n * @param options - Options specifying which keys to ignore\n * @returns A deep copy of `value` with specified keys removed\n */\nexport function deepOmit<T>(value: T, options: DeepOmitOptions): T {\n\tconst visited = new WeakMap<object, unknown>();\n\t// Materialise ignoreKeys as a Set once so the inner loop probes O(1).\n\tconst ignoreKeys = options.ignoreKeys\n\t\t? new Set<Key>(options.ignoreKeys)\n\t\t: undefined;\n\treturn omitInternal(value, options, ignoreKeys, [], visited) as T;\n}\n\nfunction omitInternal(\n\tvalue: unknown,\n\toptions: DeepOmitOptions,\n\tignoreKeys: ReadonlySet<Key> | undefined,\n\tpath: PathSegment[],\n\tvisited: WeakMap<object, unknown>,\n): unknown {\n\tif (value === null) return value;\n\tif (typeof value !== \"object\") return value;\n\n\tconst obj = value as object;\n\n\t// Cycles: return cached clone if already visited. Use `has` (not\n\t// `cached !== undefined`) so a legitimately-undefined cached clone\n\t// would not be misclassified as \"never seen\".\n\tif (visited.has(obj)) {\n\t\treturn visited.get(obj);\n\t}\n\n\tconst tag = Object.prototype.toString.call(obj);\n\n\t// Arrays: recursively process elements\n\tif (tag === \"[object Array]\") {\n\t\tconst arr = obj as unknown[];\n\t\tconst clone: unknown[] = new Array(arr.length);\n\t\tvisited.set(obj, clone);\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tpath.push(i);\n\t\t\tclone[i] = omitInternal(arr[i], options, ignoreKeys, path, visited);\n\t\t\tpath.pop();\n\t\t}\n\t\treturn clone;\n\t}\n\n\t// Built-in atomic types: clone by type rather than walk.\n\tif (isBuiltInObject(obj, tag)) {\n\t\tconst builtInClone = cloneBuiltIn(obj, tag);\n\t\tvisited.set(obj, builtInClone);\n\t\treturn builtInClone;\n\t}\n\n\t// Plain / Custom Objects: filter keys, recursively process values.\n\tconst clone = Object.create(Object.getPrototypeOf(obj));\n\tvisited.set(obj, clone);\n\n\tconst stringKeys = Object.keys(obj);\n\tconst symbolKeys = Object.getOwnPropertySymbols(obj);\n\n\tfor (const key of stringKeys) {\n\t\tif (shouldIgnoreKey(key, path, ignoreKeys, options)) continue;\n\t\tpath.push(key);\n\t\tassignOwn(\n\t\t\tclone,\n\t\t\tkey,\n\t\t\tomitInternal(\n\t\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\t\toptions,\n\t\t\t\tignoreKeys,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t\tpath.pop();\n\t}\n\tfor (const key of symbolKeys) {\n\t\tif (shouldIgnoreKey(key, path, ignoreKeys, options)) continue;\n\t\tpath.push(key);\n\t\tassignOwn(\n\t\t\tclone,\n\t\t\tkey,\n\t\t\tomitInternal(\n\t\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\t\toptions,\n\t\t\t\tignoreKeys,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t\tpath.pop();\n\t}\n\n\treturn clone;\n}\n\n/**\n * Assigns `value` as an OWN data property on `target` without going through\n * any inherited setter — critically, never invokes the `__proto__` setter\n * even when `key === \"__proto__\"`. Required to defeat prototype-pollution\n * payloads that ship `__proto__` as a parsed-JSON own key.\n */\nfunction assignOwn(target: object, key: PropertyKey, value: unknown): void {\n\tObject.defineProperty(target, key, {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t});\n}\n\n/**\n * Clones a built-in atomic type by case. Falls back to `structuredClone`\n * for anything not explicitly enumerated (e.g. ArrayBuffer, DataView,\n * Boolean/Number/String wrappers).\n */\nfunction cloneBuiltIn(obj: object, tag: string): unknown {\n\tswitch (tag) {\n\t\tcase \"[object Date]\":\n\t\t\treturn new Date((obj as Date).getTime());\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst re = obj as RegExp;\n\t\t\tconst copy = new RegExp(re.source, re.flags);\n\t\t\tcopy.lastIndex = re.lastIndex;\n\t\t\treturn copy;\n\t\t}\n\t\tcase \"[object Map]\": {\n\t\t\tconst m = obj as Map<unknown, unknown>;\n\t\t\treturn new Map(m);\n\t\t}\n\t\tcase \"[object Set]\": {\n\t\t\tconst s = obj as Set<unknown>;\n\t\t\treturn new Set(s);\n\t\t}\n\t\tdefault:\n\t\t\treturn structuredClone(obj);\n\t}\n}\n\nfunction shouldIgnoreKey(\n\tkey: Key,\n\tpath: readonly PathSegment[],\n\tignoreKeys: ReadonlySet<Key> | undefined,\n\toptions: DeepOmitOptions,\n): boolean {\n\tif (ignoreKeys?.has(key)) return true;\n\tif (options.ignoreKeyPredicate?.(key, path)) return true;\n\treturn false;\n}\n","import { deepEqual } from \"./deep-equal\";\nimport { type DeepOmitOptions, deepOmit } from \"./deep-omit\";\n\nexport type DeepEqualExceptOptions = DeepOmitOptions;\n\n/**\n * Performs a deep equality comparison between two values after omitting specified keys.\n * \n * This function first removes the specified keys from both values using `deepOmit`,\n * then performs a deep equality check using `deepEqual`.\n * \n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param options - Options specifying which keys to omit before comparison\n * @returns `true` if the values are deeply equal after omitting specified keys, `false` otherwise\n * \n * @example\n * ```ts\n * const obj1 = { id: 1, name: \"Alice\", updatedAt: \"2024-01-01\" };\n * const obj2 = { id: 2, name: \"Alice\", updatedAt: \"2024-01-02\" };\n * \n * deepEqualExcept(obj1, obj2, { ignoreKeys: [\"id\", \"updatedAt\"] }); // true\n * ```\n */\nexport function deepEqualExcept(\n\ta: unknown,\n\tb: unknown,\n\toptions: DeepEqualExceptOptions,\n): boolean {\n\tconst prunedA = deepOmit(a, options);\n\tconst prunedB = deepOmit(b, options);\n\treturn deepEqual(prunedA, prunedB);\n}\n","import { deepEqual } from \"../utils/array/deep-equal\";\nimport {\n deepEqualExcept,\n type DeepEqualExceptOptions,\n} from \"../utils/array/deep-equal-except\";\nimport { err, ok, type Result } from \"@shirudo/result\";\n\n// ============================================================================\n// Functional Value Object API\n// ============================================================================\n\nexport type VO<T> = Readonly<T>;\n\n/**\n * Deep freezes an object and all its nested properties recursively, then\n * returns it. Iterates both string-keyed and symbol-keyed own properties\n * so the freeze symmetry matches `deepEqual` (which also considers symbol\n * keys). Handles circular references by tracking visited objects.\n *\n * Note: `deepFreeze` mutates its argument in place — it sets `[[Frozen]]`\n * on the object you pass in. Callers that need to avoid touching the\n * input (e.g. `vo()`) should deep-clone first.\n */\nexport function deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n if (obj === null || typeof obj !== \"object\") {\n return obj as Readonly<T>;\n }\n if (visited.has(obj as object)) {\n return obj as Readonly<T>;\n }\n visited.add(obj as object);\n\n // Reflect.ownKeys returns both string and symbol own keys.\n const keys = Reflect.ownKeys(obj);\n for (const key of keys) {\n const value = (obj as Record<string | symbol, unknown>)[key];\n if (value !== null && typeof value === \"object\") {\n deepFreeze(value, visited);\n }\n }\n\n return Object.freeze(obj) as Readonly<T>;\n}\n\n/**\n * Creates a deeply immutable value object from the given data.\n *\n * The input is first deep-cloned with `structuredClone`, then the clone\n * is frozen — so calling `vo(input)` never freezes the caller's own\n * object graph as a side-effect. Mutating the input afterwards does not\n * bleed into the VO.\n *\n * @example\n * ```typescript\n * const nested = { lat: 52.5, lng: 13.4 };\n * const address = vo({ street: \"Main St\", coordinates: nested });\n * address.coordinates.lat = 99; // ❌ Cannot assign to read-only property\n * nested.lat = 0; // ✅ caller's input still mutable\n * ```\n */\nexport function vo<T>(t: T): VO<T> {\n return deepFreeze(structuredClone(t));\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison that handles:\n * - Nested objects and arrays\n * - Primitives (including NaN)\n * - Dates, Maps, Sets, RegExp\n * - TypedArrays and DataView\n * - Symbol keys\n * - Circular references\n *\n * @param a - First value object\n * @param b - Second value object\n * @returns true if both objects have the same values, false otherwise\n *\n * @example\n * ```typescript\n * const money1 = vo({ amount: 100, currency: \"USD\" });\n * const money2 = vo({ amount: 100, currency: \"USD\" });\n * voEquals(money1, money2); // true\n *\n * const address1 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * const address2 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * voEquals(address1, address2); // true\n * ```\n */\nexport function voEquals<T>(a: VO<T>, b: VO<T>): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * Compares two value objects for equality while ignoring specified keys.\n * Useful for comparing value objects that contain metadata or optional fields\n * that should not affect equality comparison.\n *\n * @param a - First value object\n * @param b - Second value object\n * @param options - Options specifying which keys to ignore during comparison\n * @returns true if both objects have the same values (after ignoring specified keys), false otherwise\n *\n * @example\n * ```typescript\n * // Value object with metadata\n * const address1 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-02\" }\n * });\n *\n * const address2 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-03\" }\n * });\n *\n * // Compare ignoring metadata timestamps\n * voEqualsExcept(address1, address2, {\n * ignoreKeys: [\"updatedAt\"],\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n *\n * // Compare ignoring all metadata\n * voEqualsExcept(address1, address2, {\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n * ```\n */\nexport function voEqualsExcept<T>(\n a: VO<T>,\n b: VO<T>,\n options: DeepEqualExceptOptions,\n): boolean {\n return deepEqualExcept(a, b, options);\n}\n\n/**\n * Creates a value object with optional validation.\n * Returns a Result type instead of throwing an error.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns Result containing the value object if valid, or an error message if validation fails\n *\n * @example\n * ```typescript\n * const result = voWithValidation(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n *\n * if (result.ok) {\n * console.log(result.value); // Use the value object\n * } else {\n * console.error(result.error); // Handle validation error\n * }\n * ```\n */\nexport function voWithValidation<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): Result<VO<T>, string> {\n if (!validate(t)) {\n return err(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return ok(vo(t));\n}\n\n// ============================================================================\n// Class-based Value Object API\n// ============================================================================\n\n/**\n * Interface for Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport interface IValueObject<T extends object> {\n /**\n * The immutable properties of the value object.\n */\n readonly props: Readonly<T>;\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal\n */\n equals(other: IValueObject<T>): boolean;\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n clone(props?: Partial<T>): IValueObject<T>;\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n toJSON(): Readonly<T>;\n}\n\n/**\n * Abstract base class for creating Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport abstract class ValueObject<T extends object> implements IValueObject<T> {\n public readonly props: Readonly<T>;\n\n /**\n * Creates a new ValueObject.\n * The properties are deeply frozen to ensure immutability.\n *\n * @param props - The properties of the value object\n * @example\n * ```ts\n * class Money extends ValueObject<{ amount: number; currency: string }> {\n * constructor(props: { amount: number; currency: string }) {\n * super(props);\n * }\n *\n * protected validate(props: { amount: number; currency: string }): void {\n * if (props.amount < 0) throw new Error(\"Amount cannot be negative\");\n * }\n * }\n * ```\n */\n constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze({ ...props });\n }\n\n /**\n * Optional validation hook that can be overridden by subclasses.\n * Should throw an error if validation fails.\n *\n * @param props - The properties to validate\n * @throws Error if validation fails\n */\n protected validate(props: T): void {\n // Default implementation does nothing\n }\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties and checks for constructor equality.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal and constructors match\n */\n public equals(other: ValueObject<T>): boolean {\n if (other === null || other === undefined) {\n return false;\n }\n\n if (this.constructor !== other.constructor) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n public clone(props?: Partial<T>): this {\n const Constructor = this.constructor as new (props: T) => this;\n return new Constructor({ ...this.props, ...(props || {}) });\n }\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n public toJSON(): Readonly<T> {\n return this.props;\n }\n\n\n}\n","import { deepFreeze } from \"../value-object/value-object\";\n\n/**\n * Factory function producing a fresh, unique event identifier for each call.\n *\n * The library ships a default that uses Web Crypto `crypto.randomUUID()`\n * (works on Node 19+, modern browsers in secure contexts, Deno, Bun,\n * Cloudflare Workers, Vercel Edge, and any runtime that implements Web\n * Crypto). Note that `crypto.randomUUID()` returns **UUID v4** (purely\n * random) — for production event stores prefer a **time-ordered** id\n * format (UUID v7 / ULID / KSUID) so B-tree indexes on the eventId\n * column stay clustered and `ORDER BY eventId` matches creation order.\n * Swap one in via `setEventIdFactory(() => uuidv7())` or `() => ulid()`.\n */\nexport type EventIdFactory = () => string;\n\nconst defaultEventIdFactory: EventIdFactory = () => crypto.randomUUID();\nlet currentEventIdFactory: EventIdFactory = defaultEventIdFactory;\n\n/**\n * Replaces the global event-id factory used by `createDomainEvent` and\n * `createDomainEventWithMetadata`. Call once during application bootstrap,\n * for example:\n *\n * ```ts\n * import { ulid } from \"ulid\";\n * import { setEventIdFactory } from \"@shirudo/ddd-kit\";\n *\n * setEventIdFactory(() => ulid());\n * ```\n *\n * The per-call `options.eventId` override always wins over this factory.\n *\n * **Module-scoped — last setter wins.** The factory lives as a single\n * module variable; importing two libraries that both call this races on\n * load order. For multi-tenant request isolation (e.g. one factory per\n * tenant in a single Worker invocation) **prefer the per-call\n * `options.eventId`** instead of mutating the global. Same caveat applies\n * to `setClockFactory`.\n */\nexport function setEventIdFactory(factory: EventIdFactory): void {\n\tcurrentEventIdFactory = factory;\n}\n\n/**\n * Restores the default event-id factory (`crypto.randomUUID()`).\n * Intended for use in test `afterEach` hooks.\n */\nexport function resetEventIdFactory(): void {\n\tcurrentEventIdFactory = defaultEventIdFactory;\n}\n\n/**\n * Clock function producing a fresh `Date` for each call. The library\n * defaults to `() => new Date()`; override globally via `setClockFactory`\n * for deterministic event-sourcing tests, time-travel debugging, or any\n * scenario where `occurredAt` must be reproducible.\n */\nexport type ClockFactory = () => Date;\n\nconst defaultClockFactory: ClockFactory = () => new Date();\nlet currentClockFactory: ClockFactory = defaultClockFactory;\n\n/**\n * Replaces the global clock factory used by `createDomainEvent` and\n * `createDomainEventWithMetadata`. Call once during application bootstrap\n * (or per-test in deterministic test suites):\n *\n * ```ts\n * import { setClockFactory } from \"@shirudo/ddd-kit\";\n *\n * setClockFactory(() => new Date(\"2026-01-01T00:00:00Z\"));\n * ```\n *\n * The per-call `options.occurredAt` override always wins over this\n * factory. Symmetric to `setEventIdFactory`.\n */\nexport function setClockFactory(factory: ClockFactory): void {\n\tcurrentClockFactory = factory;\n}\n\n/**\n * Restores the default clock factory (`() => new Date()`).\n * Intended for use in test `afterEach` hooks.\n */\nexport function resetClockFactory(): void {\n\tcurrentClockFactory = defaultClockFactory;\n}\n\n/**\n * Metadata associated with a domain event for traceability and correlation.\n * Used in event-driven architectures to track event flow across services.\n */\nexport interface EventMetadata {\n\t/**\n\t * Correlation ID for tracing events across multiple services/components.\n\t * Typically used to group related events in a distributed system.\n\t */\n\tcorrelationId?: string;\n\n\t/**\n\t * Causation ID referencing the event or command that caused this event.\n\t * Used to build event chains and understand causality.\n\t */\n\tcausationId?: string;\n\n\t/**\n\t * User ID of the person or system that triggered the event.\n\t */\n\tuserId?: string;\n\n\t/**\n\t * Source service or component that produced the event.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Additional custom metadata fields.\n\t * Allows extensibility for domain-specific metadata.\n\t */\n\t[key: string]: unknown;\n}\n\n/**\n * Domain Event represents something meaningful that happened in the domain.\n * Events are immutable and carry information about what occurred.\n *\n * @template T - The event type name (e.g., \"OrderCreated\")\n * @template P - The event payload type\n */\nexport interface DomainEvent<T extends string, P = void> {\n\t/**\n\t * Unique identifier for this specific event instance. Used by idempotent\n\t * consumers, outbox dispatch tracking, and as the target of\n\t * `metadata.causationId`. Defaults to `crypto.randomUUID()` if not\n\t * supplied.\n\t */\n\teventId: string;\n\n\t/**\n\t * The type of the event, used for routing and handling.\n\t */\n\ttype: T;\n\n\t/**\n\t * Identifier of the aggregate that produced the event. Optional at the\n\t * library level — set it whenever the producing aggregate is known so\n\t * downstream subscribers, outboxes, and projections can scope by entity.\n\t */\n\taggregateId?: string;\n\n\t/**\n\t * Name of the aggregate type that produced the event (e.g. \"Order\").\n\t * Pairs with `aggregateId` to fully qualify the source aggregate.\n\t */\n\taggregateType?: string;\n\n\t/**\n\t * The event payload containing the domain data. The field is always\n\t * present; its value is `undefined` when `P` is `void`.\n\t */\n\tpayload: P;\n\n\t/**\n\t * Timestamp when the event occurred.\n\t */\n\toccurredAt: Date;\n\n\t/**\n\t * Event schema version for handling schema evolution.\n\t * Required for safe schema migration in event-sourced systems.\n\t * Use 1 for the initial schema version.\n\t */\n\tversion: number;\n\n\t/**\n\t * Optional metadata for traceability, correlation, and auditing.\n\t * Includes correlationId, causationId, userId, source, and custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Shared option bag for the `createDomainEvent*` factories.\n */\nexport interface CreateDomainEventOptions {\n\t/**\n\t * Override for the auto-generated `eventId`. Pass an existing id (for\n\t * replay, tests, or deterministic event sourcing) instead of letting the\n\t * factory call `crypto.randomUUID()`.\n\t */\n\teventId?: string;\n\n\t/**\n\t * Identifier of the aggregate that produced the event.\n\t */\n\taggregateId?: string;\n\n\t/**\n\t * Name of the aggregate type that produced the event.\n\t */\n\taggregateType?: string;\n\n\t/**\n\t * Override for the auto-generated `occurredAt` timestamp.\n\t */\n\toccurredAt?: Date;\n\n\t/**\n\t * Override for the default schema version (1).\n\t */\n\tversion?: number;\n\n\t/**\n\t * Event metadata — correlation, causation, user, source, custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Creates a domain event with default values.\n * Sets occurredAt to current date and version to 1 if not provided.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param options - Optional event configuration\n * @returns A domain event\n *\n * @example\n * ```typescript\n * const event = createDomainEvent(\"OrderCreated\", { orderId: \"123\" });\n * ```\n */\nexport function createDomainEvent<T extends string>(\n\ttype: T,\n\tpayload?: undefined,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, void>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, P>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload?: P,\n\toptions?: CreateDomainEventOptions,\n): DomainEvent<T, P> {\n\tconst event: DomainEvent<T, P> = {\n\t\teventId: options?.eventId ?? currentEventIdFactory(),\n\t\ttype,\n\t\taggregateId: options?.aggregateId,\n\t\taggregateType: options?.aggregateType,\n\t\tpayload: payload as P,\n\t\toccurredAt: options?.occurredAt ?? currentClockFactory(),\n\t\tversion: options?.version ?? 1,\n\t\tmetadata: options?.metadata,\n\t};\n\t// Deep-freeze so a mutating subscriber cannot poison subsequent\n\t// handlers — events are facts of the past and must be immutable\n\t// (Vernon, IDDD §8).\n\treturn deepFreeze(event) as DomainEvent<T, P>;\n}\n\n/**\n * Creates a domain event with metadata for traceability.\n * Convenience function for creating events with correlation and causation IDs.\n *\n * @example\n * ```typescript\n * const event = createDomainEventWithMetadata(\n * \"OrderCreated\",\n * { orderId: \"123\" },\n * { correlationId: \"corr-123\", causationId: \"cmd-456\", userId: \"user-789\" }\n * );\n * ```\n */\nexport function createDomainEventWithMetadata<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\tmetadata: EventMetadata,\n\toptions?: Omit<CreateDomainEventOptions, \"metadata\">,\n): DomainEvent<T, P> {\n\treturn createDomainEvent(type, payload, {\n\t\t...options,\n\t\tmetadata,\n\t});\n}\n\n/**\n * Copies metadata from a source event to a new event.\n * Useful for maintaining correlation chains in event-driven architectures.\n *\n * @example\n * ```typescript\n * const newEvent = createDomainEvent(\n * \"OrderShipped\",\n * { orderId: \"123\" },\n * { metadata: copyMetadata(previousEvent, { causationId: previousEvent.type }) }\n * );\n * ```\n */\nexport function copyMetadata(\n\tsourceEvent: DomainEvent<string, unknown>,\n\tadditionalMetadata?: Partial<EventMetadata>,\n): EventMetadata {\n\treturn {\n\t\t...(sourceEvent.metadata ?? {}),\n\t\t...(additionalMetadata ?? {}),\n\t};\n}\n\n/**\n * Merges multiple metadata objects into one.\n * Later metadata objects override earlier ones for the same keys.\n *\n * @example\n * ```typescript\n * const metadata = mergeMetadata(\n * { correlationId: \"corr-123\" },\n * { userId: \"user-456\" },\n * { source: \"order-service\" }\n * );\n * ```\n */\nexport function mergeMetadata(\n\t...metadataObjects: Array<EventMetadata | undefined>\n): EventMetadata {\n\treturn Object.assign({}, ...metadataObjects.filter(Boolean));\n}\n","import type { Id } from \"../core/id\";\n\n// Re-export domain event types for convenience\nexport * from \"./domain-event\";\n\n// Re-export interfaces from their respective files\nexport type { IAggregateRoot } from \"./aggregate-root\";\nexport type { IEventSourcedAggregate } from \"./event-sourced-aggregate\";\n\n// --- Aggregate types ---\n\nexport type Version = number & { readonly __v: true };\n\n/**\n * Snapshot of an aggregate state at a specific point in time.\n * Used for optimizing event replay by starting from a snapshot\n * instead of replaying all events from the beginning.\n *\n * @template TState - The type of the aggregate state\n */\nexport interface AggregateSnapshot<TState> {\n\t/**\n\t * The state of the aggregate at the time of the snapshot.\n\t */\n\tstate: TState;\n\n\t/**\n\t * The version of the aggregate when the snapshot was taken.\n\t */\n\tversion: Version;\n\n\t/**\n\t * Timestamp when the snapshot was created.\n\t */\n\tsnapshotAt: Date;\n}\n\n/**\n * Checks if two aggregates are at the same version (same ID and version).\n * Useful for optimistic concurrency control checks.\n *\n * Note: Two aggregates with the same ID ARE the same aggregate (identity).\n * This function checks if they are at the same version — i.e., no concurrent modification.\n *\n * @example\n * ```typescript\n * const before = await repository.getById(id);\n * // ... some operations ...\n * const after = await repository.getById(id);\n *\n * if (!sameVersion(before, after)) {\n * throw new Error(\"Aggregate was modified by another process\");\n * }\n * ```\n */\nexport function sameVersion<TId extends Id<string>>(\n\ta: { id: TId; version: Version },\n\tb: { id: TId; version: Version },\n): boolean {\n\treturn a.id === b.id && a.version === b.version;\n}\n","/**\n * Entity utilities and interfaces for Domain-Driven Design.\n *\n * In Domain-Driven Design, there are two types of entities:\n *\n * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.\n * - Has identity (id), state, and version\n * - Implemented by classes extending `AggregateRoot` or `EventSourcedAggregate`\n * - Represents the aggregate externally\n * - Loaded/saved through repositories\n *\n * 2. **Child Entities**: Entities within an aggregate.\n * - Have identity (id) and state, but no own version\n * - Can extend `EntityBase<TState, TId>` for class-based entities\n * - Or use functional style with `Identifiable<TId> & TProps`\n * - Exist only within the aggregate boundary\n * - Versioned through the Aggregate Root\n * - Cannot be referenced directly from outside the aggregate\n *\n * This module provides:\n * - `EntityBase<TState, TId>` - Base class for entities with state\n * - `Entity<TId>` - Simple class for entities without state management\n * - `Identifiable<TId>` - Minimal interface for objects with id\n * - Helper functions for working with collections of entities\n *\n * @example\n * ```typescript\n * // Class-based child entity with logic\n * class OrderItem extends EntityBase<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n *\n * calculateSubtotal(): number {\n * return this._state.price * this._state.quantity;\n * }\n * }\n *\n * // Functional-style child entity (simpler, no logic)\n * type OrderItem = Identifiable<ItemId> & {\n * productId: string;\n * quantity: number;\n * price: number;\n * };\n *\n * // Aggregate Root (Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * // Order is an Aggregate Root Entity\n * // OrderState contains OrderItem child entities\n * }\n * ```\n */\nimport type { Id } from \"../core/id\";\n\n/**\n * Functional definition of an Entity via its capability — an object is\n * identifiable if it has an `id`.\n *\n * `TId` is constrained to `Id<string>` so the brand discipline that\n * `Id<Tag>` enforces is preserved end-to-end: an `Identifiable<UserId>`\n * cannot accidentally be paired with an `Identifiable<OrderId>` or with\n * a plain `string`.\n */\nexport type Identifiable<TId extends Id<string>> = {\n\treadonly id: TId;\n};\n\n/**\n * Interface for Entities with state.\n *\n * In Domain-Driven Design, Entities have:\n * - Identity (id): Distinguishes one entity from another\n * - State: The attributes/properties of the entity\n *\n * Unlike Value Objects (which are immutable and compared by value),\n * Entities are compared by identity and can have mutable state.\n *\n * @template TId - The type of the entity identifier\n * @template TState - The type of the entity state\n */\nexport interface IEntity<TId extends Id<string>, TState> extends Identifiable<TId> {\n\t/**\n\t * Unique identifier of the entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * The current state of the entity.\n\t */\n\treadonly state: TState;\n}\n\n/**\n * Abstract base class for Entities with state.\n *\n * Provides:\n * - Identity management (id)\n * - State management\n * - State validation hook\n * - Immutable state access through getter\n *\n * This is the foundation for all Entities in DDD:\n * - Child Entities within aggregates can extend this\n * - Aggregate Roots extend this and add version + events\n *\n * @template TState - The type of the entity state\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * // Child Entity within an aggregate\n * class OrderItem extends Entity<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n * }\n * ```\n */\nexport abstract class Entity<TState, TId extends Id<string>>\n\timplements IEntity<TId, TState> {\n\tpublic readonly id: TId;\n\n\t/**\n\t * Returns the current state of the entity.\n\t *\n\t * The state object is **shallowly frozen** — direct property writes\n\t * (`entity.state.foo = …`) throw in strict mode, but writes to nested\n\t * objects (`entity.state.address.zip = …`) bypass the freeze. For deep\n\t * immutability either model nested data with `vo()` (which freezes\n\t * deeply) or reach for a structural-sharing library like Immer at the\n\t * App layer. The shallow contract is intentional: deep freezing on\n\t * every state write is too expensive for hot paths, and DDD aggregates\n\t * normally treat their own state as private (`Tell, Don't Ask`).\n\t */\n\tpublic get state(): TState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * The state is 'protected' so that only the subclass can modify it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(id: TId, initialState: TState) {\n\t\tif (id === null || id === undefined) {\n\t\t\tthrow new Error(\"Entity ID cannot be null or undefined\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis._state = freezeShallow(initialState);\n\t\tthis.validateState(this._state);\n\t}\n\n\t/**\n\t * Optional validation hook to ensure state invariants. Called during\n\t * construction (from `Entity`'s constructor) and again on every\n\t * `setState()` call. Throw to reject invalid state.\n\t *\n\t * **⚠️ Must not read subclass instance fields via `this`.** The\n\t * constructor calls `validateState(initialState)` BEFORE the subclass's\n\t * field initializers run, so `this.someField` is `undefined` at that\n\t * point — a classic TypeScript/JavaScript constructor-ordering footgun.\n\t * The `state` argument is the single source of truth; treat the method\n\t * as pure with respect to `this`.\n\t *\n\t * If your invariants genuinely depend on per-instance configuration\n\t * that isn't part of the state, pass that configuration into the state\n\t * itself (DDD-canonical: the aggregate's state contains everything it\n\t * needs) or perform the additional check after construction in a\n\t * dedicated factory method.\n\t *\n\t * @param state - The state to validate\n\t * @throws Error (or `DomainError` subclass) if validation fails\n\t */\n\tprotected validateState(_state: TState): void {\n\t\t// Default implementation does nothing\n\t}\n\n\t/**\n\t * Sets the state of the entity.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t *\n\t * @param newState - The new state\n\t */\n\tprotected setState(newState: TState): void {\n\t\tthis.validateState(newState);\n\t\tthis._state = freezeShallow(newState);\n\t}\n}\n\n/**\n * Shallow-freezes `value` when it's a non-null object or array, so that\n * direct property writes throw in strict mode. Returns the value as-is for\n * primitives. Used internally by `Entity` and its subclasses to prevent\n * outside mutation of state read through the `state` getter without paying\n * the cost of a deep clone on every read.\n *\n * Exported so that sibling classes (`EventSourcedAggregate`, `AggregateRoot`)\n * can apply the same freeze when they bypass `setState` and assign\n * `this._state` directly.\n */\nexport function freezeShallow<T>(value: T): T {\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.freeze(value);\n\t}\n\treturn value;\n}\n\n\n/**\n * Checks if two entities have the same ID.\n * Works with any object that has an 'id' property.\n *\n * @param a - First entity\n * @param b - Second entity\n * @returns true if both entities have the same ID, false otherwise\n *\n * @example\n * ```typescript\n * const item1: OrderItem = { id: itemId1, productId: \"prod-1\", quantity: 2 };\n * const item2: OrderItem = { id: itemId2, productId: \"prod-2\", quantity: 1 };\n *\n * sameEntity(item1, item2); // false\n * sameEntity(item1, item1); // true\n * ```\n */\nexport function sameEntity<TId extends Id<string>>(a: Identifiable<TId>, b: Identifiable<TId>): boolean {\n\treturn a.id === b.id;\n}\n\n/**\n * Finds an entity by ID in a collection.\n * Returns undefined if not found.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to search for\n * @returns The entity if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const item = findEntityById(items, itemId1);\n * // item is { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ```\n */\nexport function findEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T | undefined {\n\treturn entities.find((entity) => entity.id === id);\n}\n\n/**\n * Checks if an entity with the given ID exists in the collection.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to check for\n * @returns true if an entity with the ID exists, false otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * hasEntityId(items, itemId1); // true\n * hasEntityId(items, itemId2); // false\n * ```\n */\nexport function hasEntityId<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): boolean {\n\treturn entities.some((entity) => entity.id === id);\n}\n\n/**\n * Removes an entity with the given ID from the collection.\n * Returns a new array without the entity.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to remove\n * @returns A new array without the entity with the given ID\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const updated = removeEntityById(items, itemId1);\n * // updated is [{ id: itemId2, productId: \"prod-2\", quantity: 1 }]\n * ```\n */\nexport function removeEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T[] {\n\treturn entities.filter((entity) => entity.id !== id);\n}\n\n/**\n * Updates an entity with the given ID in the collection.\n * Returns a new array with the updated entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to update\n * @param updater - Function that takes the entity and returns the updated entity\n * @returns A new array with the updated entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = updateEntityById(items, itemId1, (item) => ({\n * ...item,\n * quantity: item.quantity + 1\n * }));\n * // updated is [{ id: itemId1, productId: \"prod-1\", quantity: 3 }]\n * ```\n */\nexport function updateEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\tupdater: (entity: T) => T,\n): T[] {\n\treturn entities.map((entity) => (entity.id === id ? updater(entity) : entity));\n}\n\n/**\n * Replaces an entity with the given ID in the collection.\n * Returns a new array with the replaced entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to replace\n * @param replacement - The replacement entity\n * @returns A new array with the replaced entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = replaceEntityById(items, itemId1, {\n * id: itemId1,\n * productId: \"prod-1\",\n * quantity: 5\n * });\n * ```\n */\nexport function replaceEntityById<TId extends Id<string>, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\treplacement: T,\n): T[] {\n\treturn entities.map((entity) => (entity.id === id ? replacement : entity));\n}\n\n/**\n * Extracts all IDs from a collection of entities.\n *\n * @param entities - Array of entities\n * @returns Array of entity IDs\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const ids = entityIds(items);\n * // ids is [itemId1, itemId2]\n * ```\n */\nexport function entityIds<TId extends Id<string>, T extends Identifiable<TId>>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\n\n","import type { Id } from \"../core/id\";\nimport { Entity, freezeShallow } from \"../entity/entity\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Marker interface for Aggregate Roots.\n *\n * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).\n * It represents the aggregate externally and is the only object that external code\n * is allowed to hold references to. All access to child entities within the aggregate\n * must go through the Aggregate Root.\n *\n * An Aggregate consists of:\n * - One Aggregate Root (Entity with id + version)\n * - Optional child entities (Entities with id + state, but no own version)\n * - Optional value objects\n *\n * The Aggregate Root has identity (id), state, and version for optimistic concurrency control.\n * Child entities exist only within the aggregate boundary and are versioned through\n * the Aggregate Root.\n *\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {\n * // Order is an Aggregate Root (an Entity with version)\n * // OrderState contains child entities (e.g., OrderItem) and value objects\n * }\n * ```\n */\nexport interface IAggregateRoot<TId extends Id<string>> {\n\t/**\n\t * Unique identifier of the aggregate root entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * Version number for optimistic concurrency control.\n\t * Incremented on each state change to detect concurrent modifications.\n\t * This version applies to the entire aggregate, including all child entities.\n\t */\n\treadonly version: Version;\n\n\t/**\n\t * Post-save hook: a `Repository.save()` implementation calls this with\n\t * the persisted version after a successful write to push the new\n\t * version back into the aggregate and clear any recorded domain events\n\t * (they are now safely on the write side / in the outbox).\n\t *\n\t * Required by the interface so a Repository implementation can call it\n\t * via the published `IAggregateRoot` contract without taking the\n\t * abstract class as a compile-time dependency.\n\t *\n\t * @param version - The version assigned by the persistence layer\n\t */\n\tmarkPersisted(version: Version): void;\n}\n\n/**\n * Configuration options for AggregateRoot behavior.\n */\nexport interface AggregateConfig {\n\t/**\n\t * Whether `setState()` should bump the version automatically.\n\t *\n\t * Defaults to **`false`** for `AggregateRoot` — because `setState()`\n\t * already takes an explicit `bumpVersion` argument per call, so adding\n\t * an \"always bump\" config on top would be redundant. Keep it `false`\n\t * unless you have a subclass that never passes `bumpVersion` and you\n\t * want every state change to advance the version anyway.\n\t *\n\t * (Contrast with `EventSourcedAggregate`, which defaults this to\n\t * `true` because every event-sourced state change is per definition a\n\t * versioned commit.)\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Aggregate Roots without Event Sourcing.\n *\n * In DDD (Evans), an Aggregate is a cluster of objects — root entity, child entities,\n * and value objects — treated as a unit for consistency. The **Aggregate Root** is the\n * root entity that represents the aggregate externally and is the only entry point\n * for external code. This class serves as both: it IS the root entity and it contains\n * the aggregate state (`TState`) which holds child entities and value objects.\n *\n * Provides:\n * - Identity (id) and state management (via `Entity`)\n * - Version management for optimistic concurrency control\n * - Domain event tracking for side-effects\n * - Snapshot support for performance optimization\n *\n * All changes to child entities within `TState` are versioned through this root.\n * Use `setState()` for state mutations to ensure invariant validation.\n *\n * For event sourcing, use `EventSourcedAggregate` instead.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The type of domain events recorded by this aggregate (defaults to unknown)\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * constructor(id: OrderId, initialState: OrderState) {\n * super(id, initialState);\n * }\n *\n * confirm(): void {\n * this.setState({ ...this.state, status: \"confirmed\" }, true);\n * }\n * }\n * ```\n */\nexport abstract class AggregateRoot<\n\tTState,\n\tTId extends Id<string>,\n\tTEvent = never,\n>\n\textends Entity<TState, TId>\n\timplements IAggregateRoot<TId> {\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprotected setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\tprivate _domainEvents: TEvent[] = [];\n\n\t/**\n\t * Returns a read-only list of domain events recorded by this aggregate.\n\t * These events are side-effects of state changes.\n\t */\n\tpublic get domainEvents(): ReadonlyArray<TEvent> {\n\t\treturn Object.freeze(this._domainEvents.slice());\n\t}\n\n\t/**\n\t * Clears the list of recorded domain events.\n\t * Call this after dispatching the events.\n\t */\n\tpublic clearDomainEvents(): void {\n\t\tthis._domainEvents = [];\n\t}\n\n\t/**\n\t * Post-save hook called by a `Repository.save()` implementation to push\n\t * the persisted version back into the in-memory aggregate and clear the\n\t * recorded domain events (they are now safely on the write side / in\n\t * the outbox).\n\t *\n\t * Use this so `save()` can keep its `Promise<void>` return type: the\n\t * caller holds the aggregate reference, which is up to date after this\n\t * call.\n\t */\n\tpublic markPersisted(version: Version): void {\n\t\tthis.setVersion(version);\n\t\tthis._domainEvents = [];\n\t}\n\n\t/**\n\t * Mutates state and records the resulting domain events in the\n\t * **canonical record-after-mutation order**. Use this instead of calling\n\t * `setState` + `addDomainEvent` separately and you cannot trip the\n\t * \"event for a fact that never happened\" footgun.\n\t *\n\t * Order of operations:\n\t * 1. `setState(newState, true)` — runs `validateState` first.\n\t * If it throws, the method propagates and **no event is recorded\n\t * and no version is bumped**.\n\t * 2. Each event in `events` is appended via `addDomainEvent`.\n\t *\n\t * `commit()` **always bumps the version**, regardless of the aggregate's\n\t * `autoVersionBump` config. Recording a domain event implies \"something\n\t * happened that the outside world cares about\", and optimistic-\n\t * concurrency callers must see a fresh version every time. The config\n\t * still governs the un-coupled `setState` path. If you need to mutate\n\t * state without bumping (e.g. cosmetic caches), call `setState(newState,\n\t * false)` and skip `commit` entirely.\n\t *\n\t * `events` accepts a single event or an array. Omit it (or pass `[]`)\n\t * for state-only mutations.\n\t *\n\t * @example\n\t * ```ts\n\t * confirm(): void {\n\t * if (this.state.status === \"confirmed\") {\n\t * throw new OrderAlreadyConfirmedError(this.id);\n\t * }\n\t * this.commit(\n\t * { ...this.state, status: \"confirmed\" },\n\t * { type: \"OrderConfirmed\", orderId: this.id },\n\t * );\n\t * }\n\t * ```\n\t *\n\t * `EventSourcedAggregate.apply()` enforces the same ordering\n\t * structurally; `commit()` is the opt-in equivalent on `AggregateRoot`,\n\t * where `setState` and `addDomainEvent` are otherwise decoupled and the\n\t * ordering is convention-only.\n\t *\n\t * @param newState - The new state (validated by `validateState`)\n\t * @param events - One event, an array of events, or none (default)\n\t */\n\tprotected commit(\n\t\tnewState: TState,\n\t\tevents: TEvent | readonly TEvent[] = [],\n\t): void {\n\t\tthis.setState(newState, true);\n\t\tconst list: readonly TEvent[] = Array.isArray(events)\n\t\t\t? events\n\t\t\t: [events as TEvent];\n\t\tfor (const ev of list) {\n\t\t\tthis.addDomainEvent(ev);\n\t\t}\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\n\t}\n\n\t/**\n\t * Records a domain event for later publication.\n\t *\n\t * **Ordering: record AFTER state mutation.** Vernon (IDDD §8) is\n\t * explicit: a domain event describes something that has just happened\n\t * to the aggregate — its existence implies the state change already\n\t * occurred. Concretely:\n\t *\n\t * ```ts\n\t * confirm(): void {\n\t * if (this.state.status === \"confirmed\") {\n\t * throw new OrderAlreadyConfirmedError(this.id);\n\t * }\n\t * this.setState({ ...this.state, status: \"confirmed\" }, true);\n\t * this.addDomainEvent({ type: \"OrderConfirmed\", orderId: this.id });\n\t * // ↑ post-mutation. The event represents the committed fact.\n\t * }\n\t * ```\n\t *\n\t * Recording before mutation is a footgun: if a subsequent invariant\n\t * check throws, the event has already been queued but the state never\n\t * actually changed — consumers see an event for a fact that did not\n\t * happen.\n\t *\n\t * `EventSourcedAggregate.apply()` enforces this ordering structurally;\n\t * `AggregateRoot` leaves it as a convention because the state-mutation\n\t * path (`setState`) is decoupled from event recording.\n\t *\n\t * @param event - The domain event to record\n\t */\n\tprotected addDomainEvent(event: TEvent): void {\n\t\tthis._domainEvents.push(event);\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Call this after state changes for Optimistic Concurrency Control.\n\t *\n\t * If `autoVersionBump` is enabled, this is called automatically\n\t * when using `setState()`.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t/**\n\t * Sets the state and optionally bumps the version automatically.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t * Overrides Entity.setState to add version bumping.\n\t *\n\t * @param newState - The new state\n\t * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)\n\t */\n\tprotected setState(\n\t\tnewState: TState,\n\t\tbumpVersion?: boolean,\n\t): void {\n\t\tsuper.setState(newState);\n\t\tconst shouldBump = bumpVersion ?? this._autoVersionBump;\n\t\tif (shouldBump) {\n\t\t\tthis.bumpVersion();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t * Useful for performance optimization, backup/restore, and audit trails.\n\t *\n\t * @returns A snapshot containing the current state and version\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = aggregate.createSnapshot();\n\t * await snapshotRepository.save(aggregate.id, snapshot);\n\t * ```\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this.version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot.\n\t * This is useful for loading aggregates from snapshots instead of\n\t * rebuilding them from scratch.\n\t * Validates the restored state.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * aggregate.restoreFromSnapshot(snapshot);\n\t * ```\n\t */\n\tpublic restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void {\n\t\tthis.validateState(snapshot.state);\n\t\tthis._state = freezeShallow(snapshot.state);\n\t\tthis.setVersion(snapshot.version);\n\t}\n}\n","/**\n * Abstract base for all domain-layer exceptions in ddd-kit.\n *\n * Domain methods throw `DomainError`-derived exceptions when invariants are\n * violated. Consumers derive their own concrete errors from this base\n * (e.g. `OrderAlreadyShippedError extends DomainError`) so that domain\n * failures have sprechende names and can be caught via `instanceof`.\n *\n * The library itself uses this base only for its own internal errors\n * (`MissingHandlerError`, `AggregateNotFoundError`) — everything else\n * is consumer territory.\n */\nexport abstract class DomainError extends Error {\n\tconstructor(message: string, options?: ErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.name = new.target.name;\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Thrown by `EventSourcedAggregate.apply()` when no handler is registered\n * for the given event type. Indicates a missing entry in the aggregate's\n * `handlers` map — a programming error in the aggregate definition.\n */\nexport class MissingHandlerError extends DomainError {\n\tconstructor(public readonly eventType: string) {\n\t\tsuper(`Missing handler for event type: ${eventType}`);\n\t}\n}\n\n/**\n * Thrown by `IRepository.getByIdOrFail()` when an aggregate with the given\n * id does not exist. Use the nullable variant `getById()` if \"not found\"\n * is an expected outcome.\n */\nexport class AggregateNotFoundError extends DomainError {\n\tconstructor(\n\t\tpublic readonly aggregateType: string,\n\t\tpublic readonly id: string,\n\t) {\n\t\tsuper(`Aggregate not found: ${aggregateType}(${id})`);\n\t}\n}\n\n/**\n * Thrown by `IRepository.save()` when the aggregate's expected version does\n * not match the version currently persisted — i.e. another writer updated\n * the aggregate concurrently. The canonical DDD optimistic-concurrency\n * signal; callers typically reload, re-apply the use case, and retry.\n */\nexport class ConcurrencyConflictError extends DomainError {\n\tconstructor(\n\t\tpublic readonly aggregateType: string,\n\t\tpublic readonly aggregateId: string,\n\t\tpublic readonly expectedVersion: number,\n\t\tpublic readonly actualVersion: number,\n\t) {\n\t\tsuper(\n\t\t\t`Concurrency conflict on ${aggregateType}(${aggregateId}): expected version ${expectedVersion}, actual ${actualVersion}`,\n\t\t);\n\t}\n}\n","import { err, ok, type Result } from \"@shirudo/result\";\nimport type { Id } from \"../core/id\";\nimport { DomainError, MissingHandlerError } from \"../core/errors\";\nimport { Entity, freezeShallow } from \"../entity/entity\";\nimport type { IAggregateRoot } from \"./aggregate-root\";\nimport type { DomainEvent } from \"./domain-event\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Interface for Event-Sourced Aggregate Roots.\n * Defines the contract for aggregates that manage state changes via event sourcing.\n *\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The union type of all domain events\n */\nexport interface IEventSourcedAggregate<\n\tTId extends Id<string>,\n\tTEvent extends DomainEvent<string, unknown>,\n> extends IAggregateRoot<TId> {\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\treadonly pendingEvents: ReadonlyArray<TEvent>;\n\n\t/**\n\t * Reconstitutes the aggregate from an event history. Returns `Result`\n\t * because event-stream corruption is an expected recoverable failure\n\t * at the infrastructure boundary.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tloadFromHistory(history: TEvent[]): Result<void, DomainError>;\n\n\t/**\n\t * Clears the list of pending events.\n\t */\n\tclearPendingEvents(): void;\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t */\n\thasPendingEvents(): boolean;\n\n\t/**\n\t * Returns the number of pending events.\n\t */\n\tgetEventCount(): number;\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t */\n\tgetLatestEvent(): TEvent | undefined;\n}\n\ntype Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;\n\n/**\n * Configuration options for EventSourcedAggregate behavior.\n */\nexport interface EventSourcedAggregateConfig {\n\t/**\n\t * Whether `apply()` should bump the version per event.\n\t *\n\t * Defaults to **`true`** for `EventSourcedAggregate` — each applied\n\t * event is by definition a versioned state change, so the canonical\n\t * event-sourcing pattern is \"one event = one version bump\". Set to\n\t * `false` only if your event store assigns version numbers itself\n\t * and you want the aggregate to track them via `bumpVersion()` /\n\t * `setVersion()` calls instead.\n\t *\n\t * (Contrast with `AggregateRoot`, which defaults this to `false`\n\t * because its `setState()` already takes a per-call `bumpVersion`\n\t * argument.)\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Event-Sourced Aggregate Roots (Vernon, IDDD Chapter 8).\n *\n * Like `AggregateRoot`, this is both the root entity and the aggregate boundary.\n * The difference is persistence: state is derived from events, not stored directly.\n * Events are the single source of truth — all state changes go through `apply()` → handler.\n *\n * Extends `Entity` directly (not `AggregateRoot`) so that `setState()` and\n * `addDomainEvent()` are not available. This enforces the event sourcing pattern\n * at the type level — there is no way to mutate state without going through an event handler.\n *\n * `apply()` and `validateEvent()` throw `DomainError`-derived exceptions on\n * invariant violations. Subclasses override `validateEvent()` to throw their\n * own concrete subclasses (e.g. `OrderAlreadyConfirmedError`). Only the\n * infrastructure-boundary methods (`loadFromHistory`,\n * `restoreFromSnapshotWithEvents`) return `Result` — they catch `DomainError`\n * during replay so callers can react to corrupted event streams without\n * try/catch.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class OrderAlreadyConfirmedError extends DomainError {\n * constructor(id: OrderId) { super(`Order ${id} is already confirmed`); }\n * }\n *\n * class Order extends EventSourcedAggregate<OrderState, OrderEvent, OrderId> {\n * confirm(): void {\n * this.apply(createDomainEvent(\"OrderConfirmed\", {}));\n * }\n *\n * protected validateEvent(event: OrderEvent): void {\n * if (event.type === \"OrderConfirmed\" && this.state.status === \"confirmed\") {\n * throw new OrderAlreadyConfirmedError(this.id);\n * }\n * }\n *\n * protected readonly handlers = {\n * OrderConfirmed: (state: OrderState): OrderState => ({\n * ...state,\n * status: \"confirmed\",\n * }),\n * };\n * }\n * ```\n */\nexport abstract class EventSourcedAggregate<\n\tTState,\n\tTEvent extends DomainEvent<string, unknown>,\n\tTId extends Id<string>,\n> extends Entity<TState, TId>\n\timplements IEventSourcedAggregate<TId, TEvent> {\n\n\t// --- Version management (own, not inherited from AggregateRoot) ---\n\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprivate setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\t// --- Event tracking ---\n\n\tprivate _pendingEvents: TEvent[] = [];\n\tprivate readonly _autoVersionBump: boolean;\n\n\tpublic get pendingEvents(): ReadonlyArray<TEvent> {\n\t\treturn Object.freeze(this._pendingEvents.slice());\n\t}\n\n\tpublic clearPendingEvents(): void {\n\t\tthis._pendingEvents = [];\n\t}\n\n\t/**\n\t * Post-save hook called by a `Repository.save()` implementation to push\n\t * the persisted version back into the in-memory aggregate and clear the\n\t * pending events (they are now in the event store / outbox). Lets\n\t * `save()` keep its `Promise<void>` return type.\n\t */\n\tpublic markPersisted(version: Version): void {\n\t\tthis.setVersion(version);\n\t\tthis._pendingEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: EventSourcedAggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._autoVersionBump = config?.autoVersionBump ?? true;\n\t}\n\n\t// --- Event application ---\n\n\t/**\n\t * Validates an event before it is applied. Default is no-op.\n\t * Subclasses override to throw a concrete `DomainError` subclass when\n\t * the event violates an invariant in the current state.\n\t */\n\tprotected validateEvent(_event: TEvent): void {\n\t\t// no-op by default\n\t}\n\n\t/**\n\t * Applies an event: validates, locates the handler, computes the next\n\t * state, then commits state + pending event + version bump atomically.\n\t *\n\t * Throws `DomainError` (or a subclass) on validation failure.\n\t * Throws `MissingHandlerError` if no handler is registered for `event.type`.\n\t *\n\t * State is not mutated if any step throws — the handler is invoked into\n\t * a local and only assigned to `_state` once all checks pass.\n\t *\n\t * The method is generic in the event tag `K`, so concrete callers\n\t * (`this.apply(orderCreated)`) narrow to the literal tag and the\n\t * dispatched handler is typed as `Handler<TState, Extract<TEvent, { type: K }>>`\n\t * — no `as` cast required at the call site.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Whether the event is new (needs persisting) or replayed from history\n\t */\n\tprotected apply<K extends TEvent[\"type\"]>(\n\t\tevent: Extract<TEvent, { type: K }>,\n\t\tisNew = true,\n\t): void {\n\t\tthis.dispatchAndCommit(event, isNew);\n\t}\n\n\t/**\n\t * Internal dispatch path used by `apply()` and the replay methods\n\t * (`loadFromHistory`, `restoreFromSnapshotWithEvents`). The replay loop\n\t * iterates over `TEvent[]` and therefore cannot supply a narrowed `K`\n\t * generic, so this helper accepts `TEvent` and the discriminator is\n\t * resolved via the (statically-sound) `handlers` map.\n\t */\n\tprivate dispatchAndCommit(event: TEvent, isNew: boolean): void {\n\t\tthis.validateEvent(event);\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers] as\n\t\t\t| Handler<TState, TEvent>\n\t\t\t| undefined;\n\t\tif (!handler) {\n\t\t\tthrow new MissingHandlerError(event.type);\n\t\t}\n\n\t\tconst nextState = handler(this._state, event);\n\n\t\t// Atomic commit: nothing above this line mutated aggregate state.\n\t\tthis._state = freezeShallow(nextState);\n\t\tif (isNew) {\n\t\t\tthis._pendingEvents.push(event);\n\t\t\tif (this._autoVersionBump) {\n\t\t\t\tthis.setVersion((this._version + 1) as Version);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Only needed if `autoVersionBump` is disabled.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t// --- History & Snapshots ---\n\n\t/**\n\t * Reconstitutes the aggregate from an event history. Catches `DomainError`\n\t * thrown during replay and returns it as an `Err` — this is the\n\t * infrastructure boundary, where event-stream corruption is an expected\n\t * recoverable failure. Unexpected (non-DomainError) throws propagate.\n\t *\n\t * Version advances additively: the aggregate's pre-existing version plus\n\t * `history.length`. A fresh aggregate (v=0) loading 3 events ends at v=3;\n\t * an aggregate already at v=1 (e.g. after a creation event) loading\n\t * 2 events ends at v=3, not v=2.\n\t */\n\tpublic loadFromHistory(history: TEvent[]): Result<void, DomainError> {\n\t\tconst startVersion = this._version;\n\t\tfor (const event of history) {\n\t\t\ttry {\n\t\t\t\tthis.dispatchAndCommit(event, false);\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof DomainError) return err(e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.setVersion((startVersion + history.length) as Version);\n\t\treturn ok();\n\t}\n\n\tpublic hasPendingEvents(): boolean {\n\t\treturn this._pendingEvents.length > 0;\n\t}\n\n\tpublic getEventCount(): number {\n\t\treturn this._pendingEvents.length;\n\t}\n\n\tpublic getLatestEvent(): TEvent | undefined {\n\t\treturn this._pendingEvents[this._pendingEvents.length - 1];\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this._version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot and applies events that occurred\n\t * after. Same infrastructure-boundary semantics as `loadFromHistory`:\n\t * catches `DomainError` and returns it as an `Err`; non-domain throws\n\t * propagate.\n\t *\n\t * All-or-nothing: if any event mid-stream throws a `DomainError`, the\n\t * aggregate is rolled back to its pre-call state + version. Partial\n\t * restoration is never observable to the caller.\n\t */\n\tpublic restoreFromSnapshotWithEvents(\n\t\tsnapshot: AggregateSnapshot<TState>,\n\t\teventsAfterSnapshot: TEvent[],\n\t): Result<void, DomainError> {\n\t\tconst previousState = this._state;\n\t\tconst previousVersion = this._version;\n\n\t\tthis._state = freezeShallow(snapshot.state);\n\t\tthis.setVersion(snapshot.version);\n\n\t\tfor (const event of eventsAfterSnapshot) {\n\t\t\ttry {\n\t\t\t\tthis.dispatchAndCommit(event, false);\n\t\t\t} catch (e) {\n\t\t\t\tthis._state = previousState;\n\t\t\t\tthis.setVersion(previousVersion);\n\t\t\t\tif (e instanceof DomainError) return err(e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\n\t\tthis.setVersion((snapshot.version + eventsAfterSnapshot.length) as Version);\n\t\treturn ok();\n\t}\n\n\t/**\n\t * A map of event types to their corresponding handlers.\n\t * Subclasses MUST implement this property.\n\t */\n\tprotected abstract readonly handlers: {\n\t\t[K in TEvent[\"type\"]]: Handler<TState, Extract<TEvent, { type: K }>>;\n\t};\n}\n","import { err, type Result } from \"@shirudo/result\";\nimport type { Command, CommandHandler } from \"./command\";\n\n/**\n * Type map for command types to their return types.\n * Used to improve type inference in CommandBus.\n *\n * @example\n * ```typescript\n * type MyCommandMap = {\n * CreateOrder: OrderId;\n * CancelOrder: void;\n * };\n *\n * const bus = new CommandBus<MyCommandMap>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string> ← automatically inferred\n * ```\n */\ntype CommandTypeMap = Record<string, unknown>;\n\n/**\n * Command Bus interface for dispatching commands to their handlers.\n * Provides a centralized way to execute commands with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) – return type is inferred\n * type MyCommands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<MyCommands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map – works like before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", createOrderHandler);\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface ICommandBus<TMap extends CommandTypeMap = CommandTypeMap> {\n\t/**\n\t * Executes a command by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the command type.\n\t *\n\t * @param command - The command to execute\n\t * @returns Result containing the success value or error message\n\t */\n\texecute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\texecute<C extends Command, R>(command: C): Promise<Result<R, string>>;\n\n\t/**\n\t * Registers a handler for a specific command type.\n\t *\n\t * When `TMap` is supplied, the `commandType` argument is restricted to\n\t * its keys and the handler signature is forced to match `TMap[K]` for the\n\t * return value — typos and wrong-typed handlers are compile errors.\n\t * Without `TMap` the registration is loose (any string key, any return\n\t * type) so the no-config path keeps working.\n\t *\n\t * @param commandType - The command type to register the handler for\n\t * @param handler - The handler function for this command type\n\t */\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tC extends Command & { type: K } = Command & { type: K },\n\t>(\n\t\tcommandType: K,\n\t\thandler: CommandHandler<C, TMap[K]>,\n\t): void;\n}\n\n/**\n * Simple in-memory command bus implementation.\n * Handlers are stored in a Map and dispatched based on command type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` infers the result type from the command type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, validation, authorization)\n * - Error handling and retry logic\n * - Timeout handling\n * - Metrics and observability\n * - Transaction management\n * - Dead letter queue support\n *\n * The `CommandHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map – full inference\n * type Commands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<Commands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map – same as before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", async (cmd) => ok(orderId));\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * ```\n */\nexport class CommandBus<TMap extends CommandTypeMap = CommandTypeMap>\n\timplements ICommandBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, CommandHandler<any, any>>();\n\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tC extends Command & { type: K } = Command & { type: K },\n\t>(\n\t\tcommandType: K,\n\t\thandler: CommandHandler<C, TMap[K]>,\n\t): void {\n\t\tthis.handlers.set(commandType, handler);\n\t}\n\n\tasync execute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(command.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for command type: ${command.type}`);\n\t\t}\n\t\ttry {\n\t\t\treturn await handler(command);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n}\n","import type { EventBus, Outbox } from \"../events/ports\";\nimport type { TransactionScope } from \"../repo/scope\";\n\n/**\n * Helper for executing a write Use Case inside a Unit of Work.\n *\n * Order of operations:\n * 1. `fn()` runs inside `uow.transactional(...)` — domain mutations + repo\n * writes happen here.\n * 2. `outbox.add(events)` is also inside the transaction, so events\n * persist atomically with the state change (outbox pattern).\n * 3. The transaction commits.\n * 4. **After** the commit, `bus.publish(events)` fires for the in-process\n * fast path.\n *\n * Publishing AFTER commit prevents the classic \"publish before commit\"\n * footgun: in-process subscribers can never react to events from a\n * transaction that later rolled back. If `bus.publish` itself fails, the\n * outbox still holds the events and an outbox-dispatcher will deliver them\n * (eventual consistency).\n *\n * @example\n * ```typescript\n * const result = await withCommit(\n * { outbox, bus, uow },\n * async () => {\n * const order = Order.create(customerId, items);\n * await repository.save(order);\n * return { result: order.id, events: order.domainEvents };\n * }\n * );\n * ```\n */\nexport async function withCommit<Evt extends { type: string }, R>(\n\tdeps: {\n\t\toutbox: Outbox<Evt>;\n\t\tbus?: EventBus<Evt>;\n\t\tscope: TransactionScope;\n\t},\n\tfn: () => Promise<{ result: R; events: ReadonlyArray<Evt> }>,\n): Promise<R> {\n\tconst { result, events } = await deps.scope.transactional(async () => {\n\t\tconst fnResult = await fn();\n\t\tawait deps.outbox.add(fnResult.events);\n\t\treturn fnResult;\n\t});\n\n\tif (deps.bus) {\n\t\tawait deps.bus.publish(events);\n\t}\n\n\treturn result;\n}\n","import { err, ok, type Result } from \"@shirudo/result\";\nimport type { Query, QueryHandler } from \"./query\";\n\n/**\n * Type map for query types to their return types.\n * Used to improve type inference in QueryBus.\n *\n * @example\n * ```typescript\n * type MyQueryMap = {\n * GetOrder: Order | null;\n * ListOrders: Order[];\n * };\n *\n * const bus = new QueryBus<MyQueryMap>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string> ← automatically inferred\n * ```\n */\ntype QueryTypeMap = Record<string, unknown>;\n\n/**\n * Query Bus interface for dispatching queries to their handlers.\n * Provides a centralized way to execute queries with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) – return type is inferred\n * type MyQueries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<MyQueries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map – works like before\n * const bus = new QueryBus();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface IQueryBus<TMap extends QueryTypeMap = QueryTypeMap> {\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the query type.\n\t *\n\t * @param query - The query to execute\n\t * @returns Result containing the query result if successful, or an error message\n\t */\n\texecute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\texecute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Throws an error if no handler is registered.\n\t *\n\t * @param query - The query to execute\n\t * @returns The query result\n\t * @throws Error if no handler is registered for the query type\n\t */\n\texecuteUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\texecuteUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\n\t/**\n\t * Registers a handler for a specific query type.\n\t *\n\t * When `TMap` is supplied, the `queryType` argument is restricted to its\n\t * keys and the handler signature is forced to match `TMap[K]` for the\n\t * return value — typos and wrong-typed handlers are compile errors.\n\t * Without `TMap` the registration is loose (any string key, any return\n\t * type) so the no-config path keeps working.\n\t *\n\t * @param queryType - The query type to register the handler for\n\t * @param handler - The handler function for this query type\n\t */\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tQ extends Query & { type: K } = Query & { type: K },\n\t>(\n\t\tqueryType: K,\n\t\thandler: QueryHandler<Q, TMap[K]>,\n\t): void;\n}\n\n/**\n * Simple in-memory query bus implementation.\n * Handlers are stored in a Map and dispatched based on query type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` and `executeUnsafe()` infer the result type from the query type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, caching, rate limiting)\n * - Error handling\n * - Timeout handling\n * - Metrics and observability\n * - Query result caching\n * - Rate limiting\n *\n * The `QueryHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map – full inference\n * type Queries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<Queries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map – same as before\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", async (query) => repository.getById(query.orderId));\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * ```\n */\nexport class QueryBus<TMap extends QueryTypeMap = QueryTypeMap>\n\timplements IQueryBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, QueryHandler<any, any>>();\n\n\tregister<\n\t\tK extends keyof TMap & string,\n\t\tQ extends Query & { type: K } = Query & { type: K },\n\t>(\n\t\tqueryType: K,\n\t\thandler: QueryHandler<Q, TMap[K]>,\n\t): void {\n\t\tthis.handlers.set(queryType, handler);\n\t}\n\n\tasync execute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await handler(query);\n\t\t\treturn ok(result);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tasync executeUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\treturn handler(query);\n\t}\n}\n","import type { DomainEvent } from \"../aggregate/domain-event\";\nimport type { EventBus, EventHandler, OnceOptions } from \"./ports\";\n\n/**\n * Simple in-memory event bus implementation.\n * Supports multiple subscribers per event type (pub/sub pattern).\n *\n * @template Evt - The type of domain events (must extend DomainEvent)\n *\n * @example\n * ```typescript\n * const bus = new EventBusImpl<OrderEvent>();\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await sendEmail(event.payload.customerId);\n * });\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await logEvent(event);\n * });\n *\n * await bus.publish([orderCreatedEvent]);\n * // Both handlers will be called\n * ```\n */\nexport class EventBusImpl<Evt extends DomainEvent<string, unknown>>\n\timplements EventBus<Evt>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, EventHandler<any>[]>();\n\n\tsubscribe<K extends Evt[\"type\"]>(\n\t\teventType: K,\n\t\thandler: EventHandler<Extract<Evt, { type: K }>>,\n\t): () => void {\n\t\tconst type = eventType;\n\t\tif (!this.handlers.has(type)) {\n\t\t\tthis.handlers.set(type, []);\n\t\t}\n\t\tconst handlersForType = this.handlers.get(type)!;\n\t\tconst casted = handler as EventHandler<Evt>;\n\t\thandlersForType.push(casted);\n\n\t\t// Return unsubscribe — removes exactly this subscription, even if the\n\t\t// same handler reference was subscribed multiple times (each call to\n\t\t// subscribe gets its own unsubscribe).\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tconst idx = handlersForType.indexOf(casted);\n\t\t\tif (idx !== -1) {\n\t\t\t\thandlersForType.splice(idx, 1);\n\t\t\t\tremoved = true;\n\t\t\t}\n\t\t\tif (handlersForType.length === 0) {\n\t\t\t\tthis.handlers.delete(type);\n\t\t\t}\n\t\t};\n\t}\n\n\tonce<K extends Evt[\"type\"]>(\n\t\teventType: K,\n\t\toptions?: OnceOptions,\n\t): Promise<Extract<Evt, { type: K }>> {\n\t\treturn new Promise<Extract<Evt, { type: K }>>((resolve, reject) => {\n\t\t\t// Reject synchronously if the signal is already aborted — don't\n\t\t\t// even subscribe.\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\treject(options.signal.reason ?? new Error(\"EventBus.once aborted\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet settled = false;\n\t\t\tlet abortListener: (() => void) | undefined;\n\n\t\t\tconst cleanup = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tunsubscribe();\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tif (abortListener && options?.signal) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", abortListener);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst unsubscribe = this.subscribe(eventType, (event) => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(event);\n\t\t\t});\n\n\t\t\tif (options?.signal) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(\n\t\t\t\t\t\toptions.signal!.reason ?? new Error(\"EventBus.once aborted\"),\n\t\t\t\t\t);\n\t\t\t\t};\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t}\n\n\t\t\tif (typeof options?.timeoutMs === \"number\") {\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`EventBus.once timed out after ${options.timeoutMs}ms waiting for \"${eventType}\"`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}, options.timeoutMs);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * See {@link EventBus.publish} for the full ordering / parallelism /\n\t * error-aggregation contract this implementation realises:\n\t * - events in input order, sequentially;\n\t * - handlers within one event in parallel via `Promise.allSettled`;\n\t * - errors collected and thrown after the batch (single Error, or\n\t * `AggregateError` for multiple failures).\n\t */\n\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\n\t\tconst errors: Error[] = [];\n\n\t\tfor (const event of events) {\n\t\t\tconst handlersForType = this.handlers.get(event.type);\n\t\t\tif (handlersForType) {\n\t\t\t\t// Snapshot so a handler unsubscribing during dispatch doesn't\n\t\t\t\t// shift indices while we iterate.\n\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\thandlersForType.slice().map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason\n\t\t\t\t\t\t\t\t: new Error(String(result.reason)),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (errors.length === 1) {\n\t\t\tthrow errors[0];\n\t\t}\n\t\tif (errors.length > 1) {\n\t\t\tthrow new AggregateError(errors, \"Multiple event handlers failed\");\n\t\t}\n\t}\n}\n\n"]}
|