@event-driven-io/emmett 0.23.0-alpha.6 → 0.23.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -211,6 +211,79 @@ type AppendToStreamResultWithGlobalPosition<StreamVersion = BigIntStreamPosition
211
211
  lastEventGlobalPosition: GlobalPosition;
212
212
  };
213
213
  type AppendStreamResultOfEventStore<Store extends EventStore> = Store['appendToStream'] extends (...args: any[]) => Promise<infer R> ? R : never;
214
+ type DefaultEventStoreOptions<Store extends EventStore, HandlerContext = never> = {
215
+ /**
216
+ * Pluggable set of hooks informing about the event store internal behaviour.
217
+ */
218
+ hooks?: {
219
+ /**
220
+ * This hook will be called **AFTER** events were stored in the event store.
221
+ * It's designed to handle scenarios where delivery and ordering guarantees do not matter much.
222
+ *
223
+ * **WARNINGS:**
224
+ *
225
+ * 1. It will be called **EXACTLY ONCE** if append succeded.
226
+ * 2. If the hook fails, its append **will still silently succeed**, and no error will be thrown.
227
+ * 3. Wen process crashes after events were committed, but before the hook was called, delivery won't be retried.
228
+ * That can lead to state inconsistencies.
229
+ * 4. In the case of high concurrent traffic, **race conditions may cause ordering issues**.
230
+ * For instance, where the second hook takes longer to process than the first one, ordering won't be guaranteed.
231
+ *
232
+ * @type {AfterEventStoreCommitHandler<Store, HandlerContext>}
233
+ */
234
+ onAfterCommit?: AfterEventStoreCommitHandler<Store, HandlerContext>;
235
+ };
236
+ };
237
+
238
+ type AfterEventStoreCommitHandlerWithoutContext<Store extends EventStore> = (messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[]) => Promise<void> | void;
239
+ type AfterEventStoreCommitHandler<Store extends EventStore, HandlerContext = never> = [HandlerContext] extends [never] ? AfterEventStoreCommitHandlerWithoutContext<Store> : (messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[], context: HandlerContext) => Promise<void> | void;
240
+ type TryPublishMessagesAfterCommitOptions<Store extends EventStore, HandlerContext = never> = {
241
+ onAfterCommit?: AfterEventStoreCommitHandler<Store, HandlerContext>;
242
+ };
243
+ declare function tryPublishMessagesAfterCommit<Store extends EventStore>(messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[], options: TryPublishMessagesAfterCommitOptions<Store, undefined> | undefined): Promise<boolean>;
244
+ declare function tryPublishMessagesAfterCommit<Store extends EventStore, HandlerContext>(messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[], options: TryPublishMessagesAfterCommitOptions<Store, HandlerContext> | undefined, context: HandlerContext): Promise<boolean>;
245
+
246
+ interface CommandSender {
247
+ send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
248
+ }
249
+ interface EventsPublisher {
250
+ publish<EventType extends Event = Event>(event: EventType): Promise<void>;
251
+ }
252
+ type ScheduleOptions = {
253
+ afterInMs: number;
254
+ } | {
255
+ at: Date;
256
+ };
257
+ interface MessageScheduler<CommandOrEvent extends Command | Event> {
258
+ schedule<MessageType extends CommandOrEvent>(message: MessageType, when?: ScheduleOptions): void;
259
+ }
260
+ interface CommandBus extends CommandSender, MessageScheduler<Command> {
261
+ }
262
+ interface EventBus extends EventsPublisher, MessageScheduler<Event> {
263
+ }
264
+ interface MessageBus extends CommandBus, EventBus {
265
+ schedule<MessageType extends Command | Event>(message: MessageType, when?: ScheduleOptions): void;
266
+ }
267
+ type CommandHandler$1<CommandType extends Command = Command> = (command: CommandType) => Promise<void> | void;
268
+ interface CommandProcessor {
269
+ handle<CommandType extends Command>(commandHandler: CommandHandler$1<CommandType>, ...commandTypes: CommandTypeOf<CommandType>[]): void;
270
+ }
271
+ type EventHandler<EventType extends Event = Event> = (event: EventType) => Promise<void> | void;
272
+ interface EventProcessor {
273
+ subscribe<EventType extends Event>(eventHandler: EventHandler<EventType>, ...eventTypes: EventTypeOf<EventType>[]): void;
274
+ }
275
+ type ScheduledMessage = {
276
+ message: Event | Command;
277
+ options?: ScheduleOptions;
278
+ };
279
+ interface ScheduledMessageProcessor {
280
+ dequeue(): ScheduledMessage[];
281
+ }
282
+ type MessageHandler = CommandHandler$1 | EventHandler;
283
+ type MessageProcessor = EventProcessor | CommandProcessor;
284
+ declare const getInMemoryMessageBus: () => MessageBus & EventProcessor & CommandProcessor & ScheduledMessageProcessor;
285
+
286
+ declare const forwardToMessageBus: <Store extends EventStore, HandlerContext = never>(eventPublisher: EventsPublisher) => AfterEventStoreCommitHandler<Store, HandlerContext>;
214
287
 
215
288
  declare const GlobalStreamCaughtUpType = "__emt:GlobalStreamCaughtUp";
216
289
  type GlobalStreamCaughtUp = Event<'__emt:GlobalStreamCaughtUp', {
@@ -225,10 +298,11 @@ declare const isSubscriptionEvent: (event: Event) => event is GlobalSubscription
225
298
  declare const isNotInternalEvent: (event: Event) => boolean;
226
299
  type GlobalSubscriptionEvent = GlobalStreamCaughtUp;
227
300
 
228
- type EventHandler$1<E extends Event = Event> = (eventEnvelope: ReadEvent<E>) => void;
229
301
  declare const InMemoryEventStoreDefaultStreamVersion = 0n;
230
302
  type InMemoryEventStore = EventStore<ReadEventMetadataWithGlobalPosition>;
231
- declare const getInMemoryEventStore: () => InMemoryEventStore;
303
+ type InMemoryEventStoreOptions = DefaultEventStoreOptions<InMemoryEventStore>;
304
+ type InMemoryReadEvent<EventType extends Event = Event> = ReadEvent<EventType, ReadEventMetadataWithGlobalPosition>;
305
+ declare const getInMemoryEventStore: (eventStoreOptions?: InMemoryEventStoreOptions) => InMemoryEventStore;
232
306
 
233
307
  declare const streamTrackingGlobalPosition: (currentEvents: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[]) => CaughtUpTransformStream;
234
308
  declare class CaughtUpTransformStream extends TransformStream<ReadEvent<Event, ReadEventMetadataWithGlobalPosition>, ReadEvent<Event, ReadEventMetadataWithGlobalPosition> | GlobalSubscriptionEvent> {
@@ -243,6 +317,15 @@ declare const StreamingCoordinator: () => {
243
317
  stream: () => web_streams_polyfill.ReadableStream<GlobalStreamCaughtUp | ReadEvent<Event, ReadEventMetadataWithGlobalPosition>>;
244
318
  };
245
319
 
320
+ type Closeable = {
321
+ /**
322
+ * Gracefully cleans up managed resources
323
+ *
324
+ * @memberof Closeable
325
+ */
326
+ close: () => Promise<void>;
327
+ };
328
+
246
329
  declare const deepEquals: <T>(left: T, right: T) => boolean;
247
330
  type Equatable<T> = {
248
331
  equals: (right: T) => boolean;
@@ -295,51 +378,11 @@ type HandleOptions<Store extends EventStore> = Parameters<Store['appendToStream'
295
378
  } | {
296
379
  retry?: CommandHandlerRetryOptions;
297
380
  });
298
- declare const CommandHandler$1: <State, StreamEvent extends Event>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[] | Promise<StreamEvent> | Promise<StreamEvent[]>, handleOptions?: HandleOptions<Store>) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
381
+ declare const CommandHandler: <State, StreamEvent extends Event>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[] | Promise<StreamEvent> | Promise<StreamEvent[]>, handleOptions?: HandleOptions<Store>) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
299
382
 
300
383
  type DeciderCommandHandlerOptions<State, CommandType extends Command, StreamEvent extends Event> = CommandHandlerOptions<State, StreamEvent> & Decider<State, CommandType, StreamEvent>;
301
384
  declare const DeciderCommandHandler: <State, CommandType extends Command, StreamEvent extends Event>(options: DeciderCommandHandlerOptions<State, CommandType, StreamEvent>) => <Store extends EventStore>(eventStore: Store, id: string, command: CommandType, handleOptions?: HandleOptions<Store>) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
302
385
 
303
- interface CommandSender {
304
- send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
305
- }
306
- interface EventsPublisher {
307
- publish<EventType extends Event = Event>(event: EventType): Promise<void>;
308
- }
309
- type ScheduleOptions = {
310
- afterInMs: number;
311
- } | {
312
- at: Date;
313
- };
314
- interface MessageScheduler<CommandOrEvent extends Command | Event> {
315
- schedule<MessageType extends CommandOrEvent>(message: MessageType, when?: ScheduleOptions): void;
316
- }
317
- interface CommandBus extends CommandSender, MessageScheduler<Command> {
318
- }
319
- interface EventBus extends EventsPublisher, MessageScheduler<Event> {
320
- }
321
- interface MessageBus extends CommandBus, EventBus {
322
- schedule<MessageType extends Command | Event>(message: MessageType, when?: ScheduleOptions): void;
323
- }
324
- type CommandHandler<CommandType extends Command = Command> = (command: CommandType) => Promise<void> | void;
325
- interface CommandProcessor {
326
- handle<CommandType extends Command>(commandHandler: CommandHandler<CommandType>, ...commandTypes: CommandTypeOf<CommandType>[]): void;
327
- }
328
- type EventHandler<EventType extends Event = Event> = (event: EventType) => Promise<void> | void;
329
- interface EventProcessor {
330
- subscribe<EventType extends Event>(eventHandler: EventHandler<EventType>, ...eventTypes: EventTypeOf<EventType>[]): void;
331
- }
332
- type ScheduledMessage = {
333
- message: Event | Command;
334
- options?: ScheduleOptions;
335
- };
336
- interface ScheduledMessageProcessor {
337
- dequeue(): ScheduledMessage[];
338
- }
339
- type MessageHandler = CommandHandler | EventHandler;
340
- type MessageProcessor = EventProcessor | CommandProcessor;
341
- declare const getInMemoryMessageBus: () => MessageBus & EventProcessor & CommandProcessor & ScheduledMessageProcessor;
342
-
343
386
  type ProjectionHandlingType = 'inline' | 'async';
344
387
  type ProjectionHandler<EventType extends Event = Event, EventMetaDataType extends EventMetaDataOf<EventType> & ReadEventMetadata<any, any> = EventMetaDataOf<EventType> & ReadEventMetadata<any, any>, ProjectionHandlerContext extends DefaultRecord = DefaultRecord> = (events: ReadEvent<EventType, EventMetaDataType>[], context: ProjectionHandlerContext) => Promise<void> | void;
345
388
  interface ProjectionDefinition<ReadEventMetadataType extends ReadEventMetadata<any, any> = ReadEventMetadata<any, any>, ProjectionHandlerContext extends DefaultRecord = DefaultRecord> {
@@ -635,4 +678,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
635
678
  declare const assertPositiveNumber: (value: unknown) => number;
636
679
  declare const assertUnsignedBigInt: (value: string) => bigint;
637
680
 
638
- export { type AcquireLockOptions, type AggregateStreamOptions, type AggregateStreamResult, type AggregateStreamResultOfEventStore, type AggregateStreamResultWithGlobalPosition, type AppendStreamResultOfEventStore, type AppendToStreamOptions, type AppendToStreamResult, type AppendToStreamResultWithGlobalPosition, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, type BigIntGlobalPosition, type BigIntStreamPosition, BinaryJsonDecoder, type Brand, type CanHandle, CaughtUpTransformStream, type Command, type CommandBus, type CommandDataOf, CommandHandler$1 as CommandHandler, type CommandHandlerOptions, type CommandHandlerResult, type CommandHandlerRetryOptions, CommandHandlerStreamVersionConflictRetryOptions, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderCommandHandlerOptions, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultRecord, type EnqueueTaskOptions, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreReadEventMetadata, type EventStoreSession, type EventStoreSessionFactory, type EventStoreWrapper, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalPositionTypeOfEventStore, type GlobalPositionTypeOfReadEventMetadata, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, type HandleOptions, type InMemoryEventStore, InMemoryEventStoreDefaultStreamVersion, InProcessLock, JSONParser, JsonDecoder, type Lock, type LockOptions, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, NoRetries, type NonNullable, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadEventMetadataWithoutGlobalPosition, type ReadStreamOptions, type ReadStreamResult, type ReleaseLockOptions, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, type StreamPositionTypeOfEventStore, type StreamPositionTypeOfReadEventMetadata, StreamingCoordinator, StringDecoder, type StringifyOptions, type Task, type TaskContext, TaskProcessor, type TaskProcessorOptions, type TaskQueue, type TaskQueueItem, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertDoesNotThrow, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertRejects, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, asyncRetry, canCreateEventStoreSession, caughtUpEventFrom, collect, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, getInMemoryEventStore, getInMemoryMessageBus, globalStreamCaughtUp, ignore, inlineProjections, isEquatable, isExpectedVersionConflictError, isGlobalStreamCaughtUp, isNotInternalEvent, isNumber, isString, isSubscriptionEvent, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, streamGenerators, streamTrackingGlobalPosition, streamTransformations, sum, verifyThat };
681
+ export { type AcquireLockOptions, type AfterEventStoreCommitHandler, type AggregateStreamOptions, type AggregateStreamResult, type AggregateStreamResultOfEventStore, type AggregateStreamResultWithGlobalPosition, type AppendStreamResultOfEventStore, type AppendToStreamOptions, type AppendToStreamResult, type AppendToStreamResultWithGlobalPosition, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, type BigIntGlobalPosition, type BigIntStreamPosition, BinaryJsonDecoder, type Brand, type CanHandle, CaughtUpTransformStream, type Closeable, type Command, type CommandBus, type CommandDataOf, CommandHandler, type CommandHandlerOptions, type CommandHandlerResult, type CommandHandlerRetryOptions, CommandHandlerStreamVersionConflictRetryOptions, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderCommandHandlerOptions, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultEventStoreOptions, type DefaultRecord, type EnqueueTaskOptions, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreReadEventMetadata, type EventStoreSession, type EventStoreSessionFactory, type EventStoreWrapper, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalPositionTypeOfEventStore, type GlobalPositionTypeOfReadEventMetadata, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, type HandleOptions, type InMemoryEventStore, InMemoryEventStoreDefaultStreamVersion, type InMemoryEventStoreOptions, type InMemoryReadEvent, InProcessLock, JSONParser, JsonDecoder, type Lock, type LockOptions, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, NoRetries, type NonNullable, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadEventMetadataWithoutGlobalPosition, type ReadStreamOptions, type ReadStreamResult, type ReleaseLockOptions, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, type StreamPositionTypeOfEventStore, type StreamPositionTypeOfReadEventMetadata, StreamingCoordinator, StringDecoder, type StringifyOptions, type Task, type TaskContext, TaskProcessor, type TaskProcessorOptions, type TaskQueue, type TaskQueueItem, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertDoesNotThrow, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertRejects, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, asyncRetry, canCreateEventStoreSession, caughtUpEventFrom, collect, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, forwardToMessageBus, getInMemoryEventStore, getInMemoryMessageBus, globalStreamCaughtUp, ignore, inlineProjections, isEquatable, isExpectedVersionConflictError, isGlobalStreamCaughtUp, isNotInternalEvent, isNumber, isString, isSubscriptionEvent, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, streamGenerators, streamTrackingGlobalPosition, streamTransformations, sum, tryPublishMessagesAfterCommit, verifyThat };
package/dist/index.d.ts CHANGED
@@ -211,6 +211,79 @@ type AppendToStreamResultWithGlobalPosition<StreamVersion = BigIntStreamPosition
211
211
  lastEventGlobalPosition: GlobalPosition;
212
212
  };
213
213
  type AppendStreamResultOfEventStore<Store extends EventStore> = Store['appendToStream'] extends (...args: any[]) => Promise<infer R> ? R : never;
214
+ type DefaultEventStoreOptions<Store extends EventStore, HandlerContext = never> = {
215
+ /**
216
+ * Pluggable set of hooks informing about the event store internal behaviour.
217
+ */
218
+ hooks?: {
219
+ /**
220
+ * This hook will be called **AFTER** events were stored in the event store.
221
+ * It's designed to handle scenarios where delivery and ordering guarantees do not matter much.
222
+ *
223
+ * **WARNINGS:**
224
+ *
225
+ * 1. It will be called **EXACTLY ONCE** if append succeded.
226
+ * 2. If the hook fails, its append **will still silently succeed**, and no error will be thrown.
227
+ * 3. Wen process crashes after events were committed, but before the hook was called, delivery won't be retried.
228
+ * That can lead to state inconsistencies.
229
+ * 4. In the case of high concurrent traffic, **race conditions may cause ordering issues**.
230
+ * For instance, where the second hook takes longer to process than the first one, ordering won't be guaranteed.
231
+ *
232
+ * @type {AfterEventStoreCommitHandler<Store, HandlerContext>}
233
+ */
234
+ onAfterCommit?: AfterEventStoreCommitHandler<Store, HandlerContext>;
235
+ };
236
+ };
237
+
238
+ type AfterEventStoreCommitHandlerWithoutContext<Store extends EventStore> = (messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[]) => Promise<void> | void;
239
+ type AfterEventStoreCommitHandler<Store extends EventStore, HandlerContext = never> = [HandlerContext] extends [never] ? AfterEventStoreCommitHandlerWithoutContext<Store> : (messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[], context: HandlerContext) => Promise<void> | void;
240
+ type TryPublishMessagesAfterCommitOptions<Store extends EventStore, HandlerContext = never> = {
241
+ onAfterCommit?: AfterEventStoreCommitHandler<Store, HandlerContext>;
242
+ };
243
+ declare function tryPublishMessagesAfterCommit<Store extends EventStore>(messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[], options: TryPublishMessagesAfterCommitOptions<Store, undefined> | undefined): Promise<boolean>;
244
+ declare function tryPublishMessagesAfterCommit<Store extends EventStore, HandlerContext>(messages: ReadEvent<Event, EventStoreReadEventMetadata<Store>>[], options: TryPublishMessagesAfterCommitOptions<Store, HandlerContext> | undefined, context: HandlerContext): Promise<boolean>;
245
+
246
+ interface CommandSender {
247
+ send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
248
+ }
249
+ interface EventsPublisher {
250
+ publish<EventType extends Event = Event>(event: EventType): Promise<void>;
251
+ }
252
+ type ScheduleOptions = {
253
+ afterInMs: number;
254
+ } | {
255
+ at: Date;
256
+ };
257
+ interface MessageScheduler<CommandOrEvent extends Command | Event> {
258
+ schedule<MessageType extends CommandOrEvent>(message: MessageType, when?: ScheduleOptions): void;
259
+ }
260
+ interface CommandBus extends CommandSender, MessageScheduler<Command> {
261
+ }
262
+ interface EventBus extends EventsPublisher, MessageScheduler<Event> {
263
+ }
264
+ interface MessageBus extends CommandBus, EventBus {
265
+ schedule<MessageType extends Command | Event>(message: MessageType, when?: ScheduleOptions): void;
266
+ }
267
+ type CommandHandler$1<CommandType extends Command = Command> = (command: CommandType) => Promise<void> | void;
268
+ interface CommandProcessor {
269
+ handle<CommandType extends Command>(commandHandler: CommandHandler$1<CommandType>, ...commandTypes: CommandTypeOf<CommandType>[]): void;
270
+ }
271
+ type EventHandler<EventType extends Event = Event> = (event: EventType) => Promise<void> | void;
272
+ interface EventProcessor {
273
+ subscribe<EventType extends Event>(eventHandler: EventHandler<EventType>, ...eventTypes: EventTypeOf<EventType>[]): void;
274
+ }
275
+ type ScheduledMessage = {
276
+ message: Event | Command;
277
+ options?: ScheduleOptions;
278
+ };
279
+ interface ScheduledMessageProcessor {
280
+ dequeue(): ScheduledMessage[];
281
+ }
282
+ type MessageHandler = CommandHandler$1 | EventHandler;
283
+ type MessageProcessor = EventProcessor | CommandProcessor;
284
+ declare const getInMemoryMessageBus: () => MessageBus & EventProcessor & CommandProcessor & ScheduledMessageProcessor;
285
+
286
+ declare const forwardToMessageBus: <Store extends EventStore, HandlerContext = never>(eventPublisher: EventsPublisher) => AfterEventStoreCommitHandler<Store, HandlerContext>;
214
287
 
215
288
  declare const GlobalStreamCaughtUpType = "__emt:GlobalStreamCaughtUp";
216
289
  type GlobalStreamCaughtUp = Event<'__emt:GlobalStreamCaughtUp', {
@@ -225,10 +298,11 @@ declare const isSubscriptionEvent: (event: Event) => event is GlobalSubscription
225
298
  declare const isNotInternalEvent: (event: Event) => boolean;
226
299
  type GlobalSubscriptionEvent = GlobalStreamCaughtUp;
227
300
 
228
- type EventHandler$1<E extends Event = Event> = (eventEnvelope: ReadEvent<E>) => void;
229
301
  declare const InMemoryEventStoreDefaultStreamVersion = 0n;
230
302
  type InMemoryEventStore = EventStore<ReadEventMetadataWithGlobalPosition>;
231
- declare const getInMemoryEventStore: () => InMemoryEventStore;
303
+ type InMemoryEventStoreOptions = DefaultEventStoreOptions<InMemoryEventStore>;
304
+ type InMemoryReadEvent<EventType extends Event = Event> = ReadEvent<EventType, ReadEventMetadataWithGlobalPosition>;
305
+ declare const getInMemoryEventStore: (eventStoreOptions?: InMemoryEventStoreOptions) => InMemoryEventStore;
232
306
 
233
307
  declare const streamTrackingGlobalPosition: (currentEvents: ReadEvent<Event, ReadEventMetadataWithGlobalPosition>[]) => CaughtUpTransformStream;
234
308
  declare class CaughtUpTransformStream extends TransformStream<ReadEvent<Event, ReadEventMetadataWithGlobalPosition>, ReadEvent<Event, ReadEventMetadataWithGlobalPosition> | GlobalSubscriptionEvent> {
@@ -243,6 +317,15 @@ declare const StreamingCoordinator: () => {
243
317
  stream: () => web_streams_polyfill.ReadableStream<GlobalStreamCaughtUp | ReadEvent<Event, ReadEventMetadataWithGlobalPosition>>;
244
318
  };
245
319
 
320
+ type Closeable = {
321
+ /**
322
+ * Gracefully cleans up managed resources
323
+ *
324
+ * @memberof Closeable
325
+ */
326
+ close: () => Promise<void>;
327
+ };
328
+
246
329
  declare const deepEquals: <T>(left: T, right: T) => boolean;
247
330
  type Equatable<T> = {
248
331
  equals: (right: T) => boolean;
@@ -295,51 +378,11 @@ type HandleOptions<Store extends EventStore> = Parameters<Store['appendToStream'
295
378
  } | {
296
379
  retry?: CommandHandlerRetryOptions;
297
380
  });
298
- declare const CommandHandler$1: <State, StreamEvent extends Event>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[] | Promise<StreamEvent> | Promise<StreamEvent[]>, handleOptions?: HandleOptions<Store>) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
381
+ declare const CommandHandler: <State, StreamEvent extends Event>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[] | Promise<StreamEvent> | Promise<StreamEvent[]>, handleOptions?: HandleOptions<Store>) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
299
382
 
300
383
  type DeciderCommandHandlerOptions<State, CommandType extends Command, StreamEvent extends Event> = CommandHandlerOptions<State, StreamEvent> & Decider<State, CommandType, StreamEvent>;
301
384
  declare const DeciderCommandHandler: <State, CommandType extends Command, StreamEvent extends Event>(options: DeciderCommandHandlerOptions<State, CommandType, StreamEvent>) => <Store extends EventStore>(eventStore: Store, id: string, command: CommandType, handleOptions?: HandleOptions<Store>) => Promise<CommandHandlerResult<State, StreamEvent, Store>>;
302
385
 
303
- interface CommandSender {
304
- send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
305
- }
306
- interface EventsPublisher {
307
- publish<EventType extends Event = Event>(event: EventType): Promise<void>;
308
- }
309
- type ScheduleOptions = {
310
- afterInMs: number;
311
- } | {
312
- at: Date;
313
- };
314
- interface MessageScheduler<CommandOrEvent extends Command | Event> {
315
- schedule<MessageType extends CommandOrEvent>(message: MessageType, when?: ScheduleOptions): void;
316
- }
317
- interface CommandBus extends CommandSender, MessageScheduler<Command> {
318
- }
319
- interface EventBus extends EventsPublisher, MessageScheduler<Event> {
320
- }
321
- interface MessageBus extends CommandBus, EventBus {
322
- schedule<MessageType extends Command | Event>(message: MessageType, when?: ScheduleOptions): void;
323
- }
324
- type CommandHandler<CommandType extends Command = Command> = (command: CommandType) => Promise<void> | void;
325
- interface CommandProcessor {
326
- handle<CommandType extends Command>(commandHandler: CommandHandler<CommandType>, ...commandTypes: CommandTypeOf<CommandType>[]): void;
327
- }
328
- type EventHandler<EventType extends Event = Event> = (event: EventType) => Promise<void> | void;
329
- interface EventProcessor {
330
- subscribe<EventType extends Event>(eventHandler: EventHandler<EventType>, ...eventTypes: EventTypeOf<EventType>[]): void;
331
- }
332
- type ScheduledMessage = {
333
- message: Event | Command;
334
- options?: ScheduleOptions;
335
- };
336
- interface ScheduledMessageProcessor {
337
- dequeue(): ScheduledMessage[];
338
- }
339
- type MessageHandler = CommandHandler | EventHandler;
340
- type MessageProcessor = EventProcessor | CommandProcessor;
341
- declare const getInMemoryMessageBus: () => MessageBus & EventProcessor & CommandProcessor & ScheduledMessageProcessor;
342
-
343
386
  type ProjectionHandlingType = 'inline' | 'async';
344
387
  type ProjectionHandler<EventType extends Event = Event, EventMetaDataType extends EventMetaDataOf<EventType> & ReadEventMetadata<any, any> = EventMetaDataOf<EventType> & ReadEventMetadata<any, any>, ProjectionHandlerContext extends DefaultRecord = DefaultRecord> = (events: ReadEvent<EventType, EventMetaDataType>[], context: ProjectionHandlerContext) => Promise<void> | void;
345
388
  interface ProjectionDefinition<ReadEventMetadataType extends ReadEventMetadata<any, any> = ReadEventMetadata<any, any>, ProjectionHandlerContext extends DefaultRecord = DefaultRecord> {
@@ -635,4 +678,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
635
678
  declare const assertPositiveNumber: (value: unknown) => number;
636
679
  declare const assertUnsignedBigInt: (value: string) => bigint;
637
680
 
638
- export { type AcquireLockOptions, type AggregateStreamOptions, type AggregateStreamResult, type AggregateStreamResultOfEventStore, type AggregateStreamResultWithGlobalPosition, type AppendStreamResultOfEventStore, type AppendToStreamOptions, type AppendToStreamResult, type AppendToStreamResultWithGlobalPosition, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, type BigIntGlobalPosition, type BigIntStreamPosition, BinaryJsonDecoder, type Brand, type CanHandle, CaughtUpTransformStream, type Command, type CommandBus, type CommandDataOf, CommandHandler$1 as CommandHandler, type CommandHandlerOptions, type CommandHandlerResult, type CommandHandlerRetryOptions, CommandHandlerStreamVersionConflictRetryOptions, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderCommandHandlerOptions, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultRecord, type EnqueueTaskOptions, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreReadEventMetadata, type EventStoreSession, type EventStoreSessionFactory, type EventStoreWrapper, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalPositionTypeOfEventStore, type GlobalPositionTypeOfReadEventMetadata, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, type HandleOptions, type InMemoryEventStore, InMemoryEventStoreDefaultStreamVersion, InProcessLock, JSONParser, JsonDecoder, type Lock, type LockOptions, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, NoRetries, type NonNullable, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadEventMetadataWithoutGlobalPosition, type ReadStreamOptions, type ReadStreamResult, type ReleaseLockOptions, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, type StreamPositionTypeOfEventStore, type StreamPositionTypeOfReadEventMetadata, StreamingCoordinator, StringDecoder, type StringifyOptions, type Task, type TaskContext, TaskProcessor, type TaskProcessorOptions, type TaskQueue, type TaskQueueItem, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertDoesNotThrow, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertRejects, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, asyncRetry, canCreateEventStoreSession, caughtUpEventFrom, collect, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, getInMemoryEventStore, getInMemoryMessageBus, globalStreamCaughtUp, ignore, inlineProjections, isEquatable, isExpectedVersionConflictError, isGlobalStreamCaughtUp, isNotInternalEvent, isNumber, isString, isSubscriptionEvent, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, streamGenerators, streamTrackingGlobalPosition, streamTransformations, sum, verifyThat };
681
+ export { type AcquireLockOptions, type AfterEventStoreCommitHandler, type AggregateStreamOptions, type AggregateStreamResult, type AggregateStreamResultOfEventStore, type AggregateStreamResultWithGlobalPosition, type AppendStreamResultOfEventStore, type AppendToStreamOptions, type AppendToStreamResult, type AppendToStreamResultWithGlobalPosition, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, type BigIntGlobalPosition, type BigIntStreamPosition, BinaryJsonDecoder, type Brand, type CanHandle, CaughtUpTransformStream, type Closeable, type Command, type CommandBus, type CommandDataOf, CommandHandler, type CommandHandlerOptions, type CommandHandlerResult, type CommandHandlerRetryOptions, CommandHandlerStreamVersionConflictRetryOptions, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderCommandHandlerOptions, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultEventStoreOptions, type DefaultRecord, type EnqueueTaskOptions, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreReadEventMetadata, type EventStoreSession, type EventStoreSessionFactory, type EventStoreWrapper, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalPositionTypeOfEventStore, type GlobalPositionTypeOfReadEventMetadata, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, type HandleOptions, type InMemoryEventStore, InMemoryEventStoreDefaultStreamVersion, type InMemoryEventStoreOptions, type InMemoryReadEvent, InProcessLock, JSONParser, JsonDecoder, type Lock, type LockOptions, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, NoRetries, type NonNullable, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadEventMetadataWithoutGlobalPosition, type ReadStreamOptions, type ReadStreamResult, type ReleaseLockOptions, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, type StreamPositionTypeOfEventStore, type StreamPositionTypeOfReadEventMetadata, StreamingCoordinator, StringDecoder, type StringifyOptions, type Task, type TaskContext, TaskProcessor, type TaskProcessorOptions, type TaskQueue, type TaskQueueItem, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertDoesNotThrow, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertRejects, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, asyncRetry, canCreateEventStoreSession, caughtUpEventFrom, collect, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, forwardToMessageBus, getInMemoryEventStore, getInMemoryMessageBus, globalStreamCaughtUp, ignore, inlineProjections, isEquatable, isExpectedVersionConflictError, isGlobalStreamCaughtUp, isNotInternalEvent, isNumber, isString, isSubscriptionEvent, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, streamGenerators, streamTrackingGlobalPosition, streamTransformations, sum, tryPublishMessagesAfterCommit, verifyThat };
package/dist/index.js CHANGED
@@ -17,18 +17,6 @@ import {
17
17
  parseDateFromUtcYYYYMMDD
18
18
  } from "./chunk-AEEEXE2R.js";
19
19
 
20
- // src/eventStore/eventStore.ts
21
- var canCreateEventStoreSession = (eventStore) => "withSession" in eventStore;
22
- var nulloSessionFactory = (eventStore) => ({
23
- withSession: (callback) => {
24
- const nulloSession = {
25
- eventStore,
26
- close: () => Promise.resolve()
27
- };
28
- return callback(nulloSession);
29
- }
30
- });
31
-
32
20
  // src/typing/command.ts
33
21
  var command = (type, data, metadata) => {
34
22
  return {
@@ -94,6 +82,25 @@ var accept = () => {
94
82
  return { kind: "Accept" };
95
83
  };
96
84
 
85
+ // src/eventStore/afterCommit/afterEventStoreCommitHandler.ts
86
+ async function tryPublishMessagesAfterCommit(messages, options, context) {
87
+ if (options?.onAfterCommit === void 0) return false;
88
+ try {
89
+ await options?.onAfterCommit(messages, context);
90
+ return true;
91
+ } catch (error2) {
92
+ console.error(`Error in on after commit hook`, error2);
93
+ return false;
94
+ }
95
+ }
96
+
97
+ // src/eventStore/afterCommit/forwardToMessageBus.ts
98
+ var forwardToMessageBus = (eventPublisher) => async (messages) => {
99
+ for (const message of messages) {
100
+ await eventPublisher.publish(message);
101
+ }
102
+ };
103
+
97
104
  // src/eventStore/events/index.ts
98
105
  var GlobalStreamCaughtUpType = "__emt:GlobalStreamCaughtUp";
99
106
  var isGlobalStreamCaughtUp = (event2) => event2.type === GlobalStreamCaughtUpType;
@@ -104,6 +111,18 @@ var globalStreamCaughtUp = (data) => event(GlobalStreamCaughtUpType, data, {
104
111
  var isSubscriptionEvent = (event2) => isGlobalStreamCaughtUp(event2);
105
112
  var isNotInternalEvent = (event2) => !isGlobalStreamCaughtUp(event2);
106
113
 
114
+ // src/eventStore/eventStore.ts
115
+ var canCreateEventStoreSession = (eventStore) => "withSession" in eventStore;
116
+ var nulloSessionFactory = (eventStore) => ({
117
+ withSession: (callback) => {
118
+ const nulloSession = {
119
+ eventStore,
120
+ close: () => Promise.resolve()
121
+ };
122
+ return callback(nulloSession);
123
+ }
124
+ });
125
+
107
126
  // src/eventStore/expectedVersion.ts
108
127
  var STREAM_EXISTS = "STREAM_EXISTS";
109
128
  var STREAM_DOES_NOT_EXIST = "STREAM_DOES_NOT_EXIST";
@@ -257,7 +276,7 @@ var StreamingCoordinator = () => {
257
276
 
258
277
  // src/eventStore/inMemoryEventStore.ts
259
278
  var InMemoryEventStoreDefaultStreamVersion = 0n;
260
- var getInMemoryEventStore = () => {
279
+ var getInMemoryEventStore = (eventStoreOptions) => {
261
280
  const streams = /* @__PURE__ */ new Map();
262
281
  const streamingCoordinator = StreamingCoordinator();
263
282
  const getAllEventsCount = () => {
@@ -325,6 +344,7 @@ var getInMemoryEventStore = () => {
325
344
  nextExpectedStreamVersion: positionOfLastEventInTheStream,
326
345
  createdNewStream: currentStreamVersion === InMemoryEventStoreDefaultStreamVersion
327
346
  };
347
+ await tryPublishMessagesAfterCommit(newEvents, eventStoreOptions?.hooks);
328
348
  return result;
329
349
  }
330
350
  //streamEvents: streamingCoordinator.stream,
@@ -1541,6 +1561,7 @@ export {
1541
1561
  error,
1542
1562
  event,
1543
1563
  formatDateToUtcYYYYMMDD,
1564
+ forwardToMessageBus,
1544
1565
  getInMemoryEventStore,
1545
1566
  getInMemoryMessageBus,
1546
1567
  globalStreamCaughtUp,
@@ -1572,6 +1593,7 @@ export {
1572
1593
  streamTrackingGlobalPosition,
1573
1594
  streamTransformations,
1574
1595
  sum,
1596
+ tryPublishMessagesAfterCommit,
1575
1597
  verifyThat
1576
1598
  };
1577
1599
  //# sourceMappingURL=index.js.map