@event-driven-io/emmett 0.23.0-alpha.5 → 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;
@@ -251,6 +334,23 @@ declare const isEquatable: <T>(left: T) => left is Equatable<T>;
251
334
 
252
335
  declare const sum: (iterator: Iterator<number, number, number> | Iterator<number>) => number;
253
336
 
337
+ type LockOptions = {
338
+ lockId: number;
339
+ };
340
+ type AcquireLockOptions = {
341
+ lockId: string;
342
+ };
343
+ type ReleaseLockOptions = {
344
+ lockId: string;
345
+ };
346
+ type Lock = {
347
+ acquire(options: AcquireLockOptions): Promise<void>;
348
+ tryAcquire(options: AcquireLockOptions): Promise<boolean>;
349
+ release(options: ReleaseLockOptions): Promise<boolean>;
350
+ withAcquire: <Result = unknown>(handle: () => Promise<Result>, options: AcquireLockOptions) => Promise<Result>;
351
+ };
352
+ declare const InProcessLock: () => Lock;
353
+
254
354
  declare const merge: <T>(array: T[], item: T, where: (current: T) => boolean, onExisting: (current: T) => T, onNotFound?: () => T | undefined) => T[];
255
355
 
256
356
  type AsyncRetryOptions = retry.Options & {
@@ -278,51 +378,11 @@ type HandleOptions<Store extends EventStore> = Parameters<Store['appendToStream'
278
378
  } | {
279
379
  retry?: CommandHandlerRetryOptions;
280
380
  });
281
- 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>>;
282
382
 
283
383
  type DeciderCommandHandlerOptions<State, CommandType extends Command, StreamEvent extends Event> = CommandHandlerOptions<State, StreamEvent> & Decider<State, CommandType, StreamEvent>;
284
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>>;
285
385
 
286
- interface CommandSender {
287
- send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
288
- }
289
- interface EventsPublisher {
290
- publish<EventType extends Event = Event>(event: EventType): Promise<void>;
291
- }
292
- type ScheduleOptions = {
293
- afterInMs: number;
294
- } | {
295
- at: Date;
296
- };
297
- interface MessageScheduler<CommandOrEvent extends Command | Event> {
298
- schedule<MessageType extends CommandOrEvent>(message: MessageType, when?: ScheduleOptions): void;
299
- }
300
- interface CommandBus extends CommandSender, MessageScheduler<Command> {
301
- }
302
- interface EventBus extends EventsPublisher, MessageScheduler<Event> {
303
- }
304
- interface MessageBus extends CommandBus, EventBus {
305
- schedule<MessageType extends Command | Event>(message: MessageType, when?: ScheduleOptions): void;
306
- }
307
- type CommandHandler<CommandType extends Command = Command> = (command: CommandType) => Promise<void> | void;
308
- interface CommandProcessor {
309
- handle<CommandType extends Command>(commandHandler: CommandHandler<CommandType>, ...commandTypes: CommandTypeOf<CommandType>[]): void;
310
- }
311
- type EventHandler<EventType extends Event = Event> = (event: EventType) => Promise<void> | void;
312
- interface EventProcessor {
313
- subscribe<EventType extends Event>(eventHandler: EventHandler<EventType>, ...eventTypes: EventTypeOf<EventType>[]): void;
314
- }
315
- type ScheduledMessage = {
316
- message: Event | Command;
317
- options?: ScheduleOptions;
318
- };
319
- interface ScheduledMessageProcessor {
320
- dequeue(): ScheduledMessage[];
321
- }
322
- type MessageHandler = CommandHandler | EventHandler;
323
- type MessageProcessor = EventProcessor | CommandProcessor;
324
- declare const getInMemoryMessageBus: () => MessageBus & EventProcessor & CommandProcessor & ScheduledMessageProcessor;
325
-
326
386
  type ProjectionHandlingType = 'inline' | 'async';
327
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;
328
388
  interface ProjectionDefinition<ReadEventMetadataType extends ReadEventMetadata<any, any> = ReadEventMetadata<any, any>, ProjectionHandlerContext extends DefaultRecord = DefaultRecord> {
@@ -478,6 +538,40 @@ declare const streamTransformations: {
478
538
  waitAtMost: <Item>(waitTimeInMs: number) => web_streams_polyfill.TransformStream<Item, Item>;
479
539
  };
480
540
 
541
+ type TaskQueue = TaskQueueItem[];
542
+ type TaskQueueItem = {
543
+ task: () => Promise<void>;
544
+ options?: EnqueueTaskOptions;
545
+ };
546
+ type TaskProcessorOptions = {
547
+ maxActiveTasks: number;
548
+ maxQueueSize: number;
549
+ maxTaskIdleTime?: number;
550
+ };
551
+ type Task<T> = (context: TaskContext) => Promise<T>;
552
+ type TaskContext = {
553
+ ack: () => void;
554
+ };
555
+ type EnqueueTaskOptions = {
556
+ taskGroupId?: string;
557
+ };
558
+ declare class TaskProcessor {
559
+ private options;
560
+ private queue;
561
+ private isProcessing;
562
+ private activeTasks;
563
+ private activeGroups;
564
+ constructor(options: TaskProcessorOptions);
565
+ enqueue<T>(task: Task<T>, options?: EnqueueTaskOptions): Promise<T>;
566
+ waitForEndOfProcessing(): Promise<void>;
567
+ private schedule;
568
+ private ensureProcessing;
569
+ private processQueue;
570
+ private executeItem;
571
+ private takeFirstAvailableItem;
572
+ private hasItemsToProcess;
573
+ }
574
+
481
575
  declare class AssertionError extends Error {
482
576
  constructor(message: string);
483
577
  }
@@ -584,4 +678,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
584
678
  declare const assertPositiveNumber: (value: unknown) => number;
585
679
  declare const assertUnsignedBigInt: (value: string) => bigint;
586
680
 
587
- export { 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 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, JSONParser, JsonDecoder, 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, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, type StreamPositionTypeOfEventStore, type StreamPositionTypeOfReadEventMetadata, StreamingCoordinator, StringDecoder, type StringifyOptions, 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;
@@ -251,6 +334,23 @@ declare const isEquatable: <T>(left: T) => left is Equatable<T>;
251
334
 
252
335
  declare const sum: (iterator: Iterator<number, number, number> | Iterator<number>) => number;
253
336
 
337
+ type LockOptions = {
338
+ lockId: number;
339
+ };
340
+ type AcquireLockOptions = {
341
+ lockId: string;
342
+ };
343
+ type ReleaseLockOptions = {
344
+ lockId: string;
345
+ };
346
+ type Lock = {
347
+ acquire(options: AcquireLockOptions): Promise<void>;
348
+ tryAcquire(options: AcquireLockOptions): Promise<boolean>;
349
+ release(options: ReleaseLockOptions): Promise<boolean>;
350
+ withAcquire: <Result = unknown>(handle: () => Promise<Result>, options: AcquireLockOptions) => Promise<Result>;
351
+ };
352
+ declare const InProcessLock: () => Lock;
353
+
254
354
  declare const merge: <T>(array: T[], item: T, where: (current: T) => boolean, onExisting: (current: T) => T, onNotFound?: () => T | undefined) => T[];
255
355
 
256
356
  type AsyncRetryOptions = retry.Options & {
@@ -278,51 +378,11 @@ type HandleOptions<Store extends EventStore> = Parameters<Store['appendToStream'
278
378
  } | {
279
379
  retry?: CommandHandlerRetryOptions;
280
380
  });
281
- 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>>;
282
382
 
283
383
  type DeciderCommandHandlerOptions<State, CommandType extends Command, StreamEvent extends Event> = CommandHandlerOptions<State, StreamEvent> & Decider<State, CommandType, StreamEvent>;
284
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>>;
285
385
 
286
- interface CommandSender {
287
- send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
288
- }
289
- interface EventsPublisher {
290
- publish<EventType extends Event = Event>(event: EventType): Promise<void>;
291
- }
292
- type ScheduleOptions = {
293
- afterInMs: number;
294
- } | {
295
- at: Date;
296
- };
297
- interface MessageScheduler<CommandOrEvent extends Command | Event> {
298
- schedule<MessageType extends CommandOrEvent>(message: MessageType, when?: ScheduleOptions): void;
299
- }
300
- interface CommandBus extends CommandSender, MessageScheduler<Command> {
301
- }
302
- interface EventBus extends EventsPublisher, MessageScheduler<Event> {
303
- }
304
- interface MessageBus extends CommandBus, EventBus {
305
- schedule<MessageType extends Command | Event>(message: MessageType, when?: ScheduleOptions): void;
306
- }
307
- type CommandHandler<CommandType extends Command = Command> = (command: CommandType) => Promise<void> | void;
308
- interface CommandProcessor {
309
- handle<CommandType extends Command>(commandHandler: CommandHandler<CommandType>, ...commandTypes: CommandTypeOf<CommandType>[]): void;
310
- }
311
- type EventHandler<EventType extends Event = Event> = (event: EventType) => Promise<void> | void;
312
- interface EventProcessor {
313
- subscribe<EventType extends Event>(eventHandler: EventHandler<EventType>, ...eventTypes: EventTypeOf<EventType>[]): void;
314
- }
315
- type ScheduledMessage = {
316
- message: Event | Command;
317
- options?: ScheduleOptions;
318
- };
319
- interface ScheduledMessageProcessor {
320
- dequeue(): ScheduledMessage[];
321
- }
322
- type MessageHandler = CommandHandler | EventHandler;
323
- type MessageProcessor = EventProcessor | CommandProcessor;
324
- declare const getInMemoryMessageBus: () => MessageBus & EventProcessor & CommandProcessor & ScheduledMessageProcessor;
325
-
326
386
  type ProjectionHandlingType = 'inline' | 'async';
327
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;
328
388
  interface ProjectionDefinition<ReadEventMetadataType extends ReadEventMetadata<any, any> = ReadEventMetadata<any, any>, ProjectionHandlerContext extends DefaultRecord = DefaultRecord> {
@@ -478,6 +538,40 @@ declare const streamTransformations: {
478
538
  waitAtMost: <Item>(waitTimeInMs: number) => web_streams_polyfill.TransformStream<Item, Item>;
479
539
  };
480
540
 
541
+ type TaskQueue = TaskQueueItem[];
542
+ type TaskQueueItem = {
543
+ task: () => Promise<void>;
544
+ options?: EnqueueTaskOptions;
545
+ };
546
+ type TaskProcessorOptions = {
547
+ maxActiveTasks: number;
548
+ maxQueueSize: number;
549
+ maxTaskIdleTime?: number;
550
+ };
551
+ type Task<T> = (context: TaskContext) => Promise<T>;
552
+ type TaskContext = {
553
+ ack: () => void;
554
+ };
555
+ type EnqueueTaskOptions = {
556
+ taskGroupId?: string;
557
+ };
558
+ declare class TaskProcessor {
559
+ private options;
560
+ private queue;
561
+ private isProcessing;
562
+ private activeTasks;
563
+ private activeGroups;
564
+ constructor(options: TaskProcessorOptions);
565
+ enqueue<T>(task: Task<T>, options?: EnqueueTaskOptions): Promise<T>;
566
+ waitForEndOfProcessing(): Promise<void>;
567
+ private schedule;
568
+ private ensureProcessing;
569
+ private processQueue;
570
+ private executeItem;
571
+ private takeFirstAvailableItem;
572
+ private hasItemsToProcess;
573
+ }
574
+
481
575
  declare class AssertionError extends Error {
482
576
  constructor(message: string);
483
577
  }
@@ -584,4 +678,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
584
678
  declare const assertPositiveNumber: (value: unknown) => number;
585
679
  declare const assertUnsignedBigInt: (value: string) => bigint;
586
680
 
587
- export { 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 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, JSONParser, JsonDecoder, 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, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, type StreamPositionTypeOfEventStore, type StreamPositionTypeOfReadEventMetadata, StreamingCoordinator, StringDecoder, type StringifyOptions, 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 };