@shirudo/ddd-kit 0.8.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:true});function T(t,e=0){return {state:t,version:e,pendingEvents:[]}}o(T,"aggregate");function E(t,e){return {...t,pendingEvents:[...t.pendingEvents,e]}}o(E,"withEvent");function h(t){return {...t,version:t.version+1}}o(h,"bump");function m(t,e,r){return {type:t,payload:e,occurredAt:r?.occurredAt??new Date,version:r?.version??1,metadata:r?.metadata}}o(m,"createDomainEvent");function x(t,e,r,n){return m(t,e,{...n,metadata:r})}o(x,"createDomainEventWithMetadata");function b(t,e){return {...t.metadata??{},...e??{}}}o(b,"copyMetadata");function R(...t){return Object.assign({},...t.filter(Boolean))}o(R,"mergeMetadata");function I(t,e){return t.id===e.id&&t.version===e.version}o(I,"sameAggregate");var d=class{static{o(this,"AggregateBase");}id;version=0;_config;_autoVersionBump;get state(){return this._state}_state;constructor(e,r,n){this.id=e,this._state=r,this._config=n??{},this._autoVersionBump=this._config.autoVersionBump??false;}bumpVersion(){this.version=this.version+1;}setState(e,r){this._state=e,(r??this._autoVersionBump)&&this.bumpVersion();}createSnapshot(){return {state:{...this._state},version:this.version,snapshotAt:new Date}}restoreFromSnapshot(e){this._state=e.state,this.version=e.version;}};function a(t){return {ok:true,value:t}}o(a,"ok");function s(t){return {ok:false,error:t}}o(s,"err");function _(t){return t.ok===true}o(_,"isOk");function w(t){return t.ok===false}o(w,"isErr");var u=class extends d{static{o(this,"AggregateEventSourced");}_eventConfig;_eventAutoVersionBump;_pendingEvents=[];constructor(e,r,n){super(e,r,n),this._eventConfig=n??{},this._eventAutoVersionBump=this._eventConfig.autoVersionBump??true;}get pendingEvents(){return this._pendingEvents}clearPendingEvents(){this._pendingEvents.length=0;}validateEvent(e){return a(true)}apply(e,r=true){let n=this.validateEvent(e);if(!n.ok)return s(`Event validation failed for ${e.type}: ${n.error}`);let i=this.handlers[e.type];return i?(this._state=i(this._state,e),r&&(this._pendingEvents.push(e),this._eventAutoVersionBump&&(this.version=this.version+1)),a()):s(`Missing handler for event type: ${e.type}`)}applyUnsafe(e,r=true){let n=this.validateEvent(e);if(!n.ok)throw new Error(`Event validation failed for ${e.type}: ${n.error}`);let i=this.handlers[e.type];if(!i)throw new Error(`Missing handler for event type: ${e.type}`);this._state=i(this._state,e),r&&(this._pendingEvents.push(e),this._eventAutoVersionBump&&(this.version=this.version+1));}bumpVersion(){this.version=this.version+1;}loadFromHistory(e){for(let r of e){let n=this.apply(r,false);if(!n.ok)return n}return this.version=e.length,a()}hasPendingEvents(){return this._pendingEvents.length>0}getEventCount(){return this._pendingEvents.length}getLatestEvent(){return this._pendingEvents[this._pendingEvents.length-1]}restoreFromSnapshotWithEvents(e,r){this._state=e.state,this.version=e.version;for(let n of r){let i=this.apply(n,false);if(!i.ok)return i}return this.version=e.version+r.length,a()}};var p=class{static{o(this,"CommandBus");}handlers=new Map;register(e,r){this.handlers.set(e,r);}async execute(e){let r=this.handlers.get(e.type);return r?r(e):s(`No handler registered for command type: ${e.type}`)}};function N(t,e){return t.uow.transactional(async()=>{let{result:r,events:n}=await e();return await t.outbox.add(n),t.bus&&await t.bus.publish(n),r})}o(N,"withCommit");var l=class{static{o(this,"QueryBus");}handlers=new Map;register(e,r){this.handlers.set(e,r);}async execute(e){let r=this.handlers.get(e.type);if(!r)return s(`No handler registered for query type: ${e.type}`);try{let n=await r(e);return a(n)}catch(n){return s(n instanceof Error?n.message:String(n))}}async executeUnsafe(e){let r=this.handlers.get(e.type);if(!r)throw new Error(`No handler registered for query type: ${e.type}`);return r(e)}};function z(t,e){return t?a(true):s(e)}o(z,"guard");function G(t,e){return t.id===e.id}o(G,"sameEntity");function X(t,e){return t.find(r=>r.id===e)}o(X,"findEntityById");function Y(t,e){return t.some(r=>r.id===e)}o(Y,"hasEntityId");function Z(t,e){return t.filter(r=>r.id!==e)}o(Z,"removeEntityById");function ee(t,e,r){return t.map(n=>n.id===e?r(n):n)}o(ee,"updateEntityById");function te(t,e,r){return t.map(n=>n.id===e?r:n)}o(te,"replaceEntityById");function re(t){return t.map(e=>e.id)}o(re,"entityIds");var g=class{static{o(this,"EventBusImpl");}handlers=new Map;subscribe(e,r){let n=e;this.handlers.has(n)||this.handlers.set(n,new Set);let i=this.handlers.get(n);return i.add(r),()=>{i.delete(r),i.size===0&&this.handlers.delete(n);}}async publish(e){for(let r of e){let n=this.handlers.get(r.type);n&&await Promise.all(Array.from(n).map(i=>i(r)));}}};function v(t,e=new WeakSet){if(t===null||typeof t!="object"||e.has(t))return t;e.add(t);let r=Object.getOwnPropertyNames(t);for(let n of r){let i=t[n];i&&(typeof i=="object"||Array.isArray(i))&&v(i,e);}return Object.freeze(t)}o(v,"deepFreeze");function f(t){return v({...t})}o(f,"vo");function de(t,e){return JSON.stringify(t)===JSON.stringify(e)}o(de,"voEquals");function ue(t,e,r){return e(t)?a(f(t)):s(r??`Validation failed for value object: ${JSON.stringify(t)}`)}o(ue,"voWithValidation");function pe(t,e,r){if(!e(t))throw new Error(r??`Validation failed for value object: ${JSON.stringify(t)}`);return f(t)}o(pe,"voWithValidationUnsafe");export{d as AggregateBase,u as AggregateEventSourced,p as CommandBus,g as EventBusImpl,l as QueryBus,T as aggregate,h as bump,b as copyMetadata,m as createDomainEvent,x as createDomainEventWithMetadata,re as entityIds,s as err,X as findEntityById,z as guard,Y as hasEntityId,w as isErr,_ as isOk,R as mergeMetadata,a as ok,Z as removeEntityById,te as replaceEntityById,I as sameAggregate,G as sameEntity,ee as updateEntityById,f as vo,de as voEquals,ue as voWithValidation,pe as voWithValidationUnsafe,N as withCommit,E as withEvent};//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/aggregate/aggregate.ts","../src/aggregate/aggregate-base.ts","../src/core/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/entity/entity.ts","../src/events/event-bus.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","AggregateBase","id","initialState","config","newState","bumpVersion","snapshot","ok","value","err","error","isOk","result","isErr","AggregateEventSourced","_event","event","isNew","validation","handler","history","eventsAfterSnapshot","CommandBus","commandType","command","withCommit","deps","fn","events","QueryBus","queryType","query","guard","cond","sameEntity","findEntityById","entities","entity","hasEntityId","removeEntityById","updateEntityById","updater","replaceEntityById","replacement","entityIds","EventBusImpl","eventType","handlersForType","deepFreeze","obj","visited","propNames","name","vo","voEquals","voWithValidation","validate","errorMessage","voWithValidationUnsafe"],"mappings":"AAgFO,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,CAAAA,CACfC,CAAAA,CACAC,EACkB,CAClB,OAAO,CAAE,GAAGD,CAAAA,CAAK,aAAA,CAAe,CAAC,GAAGA,EAAI,aAAA,CAAeC,CAAG,CAAE,CAC7D,CALgBH,CAAAA,CAAAC,CAAAA,CAAA,WAAA,CAAA,CAOT,SAASG,CAAAA,CACfF,CAAAA,CACkB,CAClB,OAAO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RjD,CAAAA,CAAG8C,CAAAA,CAAG,CAAC,CAAC,CAAA,CAJP5C,CAAAA,CACNgD,CAAAA,EAAgB,CAAA,oCAAA,EAAuC,KAAK,SAAA,CAAU,CAAC,CAAC,CAAA,CACzE,CAGF,CAXgB5E,CAAAA,CAAA0E,EAAAA,CAAA,oBAgCT,SAASG,EAAAA,CACf,CAAA,CACAF,CAAAA,CACAC,CAAAA,CACiB,CACjB,GAAI,CAACD,EAAS,CAAC,CAAA,CACd,MAAM,IAAI,KAAA,CACTC,CAAAA,EAAgB,CAAA,oCAAA,EAAuC,IAAA,CAAK,UAAU,CAAC,CAAC,CAAA,CACzE,CAAA,CAED,OAAOJ,CAAAA,CAAG,CAAC,CACZ,CAXgBxE,EAAA6E,EAAAA,CAAA,wBAAA,CAAA","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> {\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 */\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\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, 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,\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","import type { Id } from \"../core/id\";\nimport type { AggregateSnapshot, Version } from \"./aggregate\";\n\n/**\n * Configuration options for AggregateBase 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 Aggregates without Event Sourcing.\n * Provides core functionality for aggregates:\n * - ID and Version management (for Optimistic Concurrency Control)\n * - State management\n * - Snapshot support for performance optimization\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\n * @template TId - The type of the aggregate identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateBase<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();\n * }\n * }\n * ```\n */\nexport abstract class AggregateBase<TState, TId extends Id<string>> {\n\tpublic readonly id: TId;\n\tpublic version: Version = 0 as Version;\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\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 change it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tthis.id = id;\n\t\tthis._state = initialState;\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\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 *\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\tthis._state = 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 *\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._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<ValueObject<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","import { err, ok, type Result } from \"../core/result\";\nimport type { Id } from \"../core/id\";\nimport { AggregateBase, type AggregateConfig } from \"./aggregate-base\";\nimport type {\n\tAggregateSnapshot,\n\tDomainEvent,\n\tVersion,\n} from \"./aggregate\";\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 Aggregates.\n * Extends `AggregateBase` 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\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate identifier\n *\n * @example\n * ```typescript\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 AggregateBase<TState, TId> {\n\tprivate readonly _eventConfig: AggregateEventSourcedConfig;\n\tprivate readonly _eventAutoVersionBump: boolean;\n\n\tprivate readonly _pendingEvents: TEvent[] = [];\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._pendingEvents;\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._pendingEvents.length = 0;\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._pendingEvents.push(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._pendingEvents.push(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._pendingEvents.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._pendingEvents.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\treturn this._pendingEvents[this._pendingEvents.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 } 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\treturn handler(command);\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 * 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 implements IQueryBus {\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, 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","/**\n * Optional interface for entities with identity.\n * Use this when you need explicit entity types for nested entities\n * within aggregates or for entities that are not aggregate roots.\n *\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * type OrderItem = Entity<ItemId> & {\n * productId: string;\n * quantity: number;\n * };\n * ```\n */\nexport interface Entity<TId> {\n\treadonly id: TId;\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: { id: TId }, b: { id: 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, T extends { id: 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, T extends { id: 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, T extends { id: 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, T extends { id: 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, T extends { id: 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, T extends { id: TId }>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\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\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\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// Call all handlers for this event type\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tArray.from(handlersForType).map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\n","import { err, ok, type Result } from \"../core/result\";\n\nexport type ValueObject<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 */\nfunction deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n\t// Handle null and non-objects\n\tif (obj === null || typeof obj !== \"object\") {\n\t\treturn obj as Readonly<T>;\n\t}\n\n\t// Handle circular references\n\tif (visited.has(obj as object)) {\n\t\treturn obj as Readonly<T>;\n\t}\n\n\t// Mark as visited\n\tvisited.add(obj as object);\n\n\t// Retrieve the property names defined on obj\n\tconst propNames = Object.getOwnPropertyNames(obj);\n\n\t// Freeze properties before freezing self\n\tfor (const name of propNames) {\n\t\tconst value = (obj as Record<string, unknown>)[name];\n\n\t\t// Freeze value if it is an object or array\n\t\tif (value && (typeof value === \"object\" || Array.isArray(value))) {\n\t\t\tdeepFreeze(value, visited);\n\t\t}\n\t}\n\n\treturn 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): ValueObject<T> {\n\treturn deepFreeze({ ...t });\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison by serializing both objects to JSON.\n *\n * Note: This is a simple implementation. For production use with complex objects,\n * consider using a more robust deep equality library or implementing custom equality logic.\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 */\nexport function voEquals<T>(a: ValueObject<T>, b: ValueObject<T>): boolean {\n\treturn JSON.stringify(a) === JSON.stringify(b);\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\tt: T,\n\tvalidate: (value: T) => boolean,\n\terrorMessage?: string,\n): Result<ValueObject<T>, string> {\n\tif (!validate(t)) {\n\t\treturn err(\n\t\t\terrorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n\t\t);\n\t}\n\treturn 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\tt: T,\n\tvalidate: (value: T) => boolean,\n\terrorMessage?: string,\n): ValueObject<T> {\n\tif (!validate(t)) {\n\t\tthrow new Error(\n\t\t\terrorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n\t\t);\n\t}\n\treturn vo(t);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shirudo/ddd-kit",
3
- "version": "0.8.8",
3
+ "version": "0.9.0",
4
4
  "description": "Composable TypeScript toolkit for tactical DDD",
5
5
  "type": "module",
6
6
  "repository": {
@@ -19,7 +19,7 @@
19
19
  "dist"
20
20
  ],
21
21
  "scripts": {
22
- "build": "tsc",
22
+ "build": "tsup",
23
23
  "test": "vitest",
24
24
  "clean": "rm -rf dist",
25
25
  "lint": "biome lint .",
@@ -38,6 +38,7 @@
38
38
  },
39
39
  "devDependencies": {
40
40
  "@biomejs/biome": "2.1.4",
41
+ "tsup": "^8.5.0",
41
42
  "typescript": "^5.9.2",
42
43
  "vitest": "^3.2.4"
43
44
  },