@event-driven-io/emmett 0.20.0-alpha.1 → 0.20.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
@@ -142,6 +142,7 @@ declare const assertExpectedVersionMatchesCurrent: <StreamVersion = bigint>(curr
142
142
  declare class ExpectedVersionConflictError<VersionType = DefaultStreamVersionType> extends ConcurrencyError {
143
143
  constructor(current: VersionType, expected: ExpectedStreamVersion<VersionType>);
144
144
  }
145
+ declare const isExpectedVersionConflictError: (error: unknown) => error is ExpectedVersionConflictError;
145
146
 
146
147
  interface EventStore<StreamVersion = DefaultStreamVersionType, ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata> {
147
148
  aggregateStream<State, EventType extends Event>(streamName: string, options: AggregateStreamOptions<State, EventType, StreamVersion, ReadEventMetadataType>): Promise<AggregateStreamResult<State, StreamVersion>>;
@@ -252,19 +253,17 @@ type CommandHandlerOptions<State, StreamEvent extends Event> = {
252
253
  evolve: (state: State, event: StreamEvent) => State;
253
254
  initialState: () => State;
254
255
  mapToStreamId?: (id: string) => string;
256
+ retry?: CommandHandlerRetryOptions;
255
257
  };
256
- declare const CommandHandler$1: <State, StreamEvent extends Event, StreamVersion = bigint>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore<StreamVersion>>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[], handleOptions?: Parameters<Store["appendToStream"]>[2] & ({
258
+ type HandleOptions<StreamVersion, Store extends EventStore<StreamVersion>> = Parameters<Store['appendToStream']>[2] & ({
257
259
  expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;
258
260
  } | {
259
261
  retry?: CommandHandlerRetryOptions;
260
- })) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
262
+ });
263
+ declare const CommandHandler$1: <State, StreamEvent extends Event, StreamVersion = bigint>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore<StreamVersion>>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[] | Promise<StreamEvent> | Promise<StreamEvent[]>, handleOptions?: HandleOptions<StreamVersion, EventStore<StreamVersion>>) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
261
264
 
262
265
  type DeciderCommandHandlerOptions<State, CommandType extends Command, StreamEvent extends Event> = CommandHandlerOptions<State, StreamEvent> & Decider<State, CommandType, StreamEvent>;
263
- declare const DeciderCommandHandler: <State, CommandType extends Command, StreamEvent extends Event, StreamVersion = bigint>({ decide, evolve, initialState }: Decider<State, CommandType, StreamEvent>, mapToStreamId?: (id: string) => string) => (eventStore: EventStore<StreamVersion>, id: string, command: CommandType, handleOptions?: {
264
- expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;
265
- } | {
266
- retry?: CommandHandlerRetryOptions;
267
- }) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
266
+ declare const DeciderCommandHandler: <State, CommandType extends Command, StreamEvent extends Event, StreamVersion = bigint>(options: DeciderCommandHandlerOptions<State, CommandType, StreamEvent>) => (eventStore: EventStore<StreamVersion>, id: string, command: CommandType, handleOptions?: HandleOptions<StreamVersion, EventStore<StreamVersion>>) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
268
267
 
269
268
  interface CommandSender {
270
269
  send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
@@ -570,4 +569,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
570
569
  declare const assertPositiveNumber: (value: unknown) => number;
571
570
  declare const assertUnsignedBigInt: (value: string) => bigint;
572
571
 
573
- export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, 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 DefaultStreamVersionType, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, 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 ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StreamingCoordinator, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, 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, isGlobalStreamCaughtUp, isNotInternalEvent, isNumber, isString, isSubscriptionEvent, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, streamGenerators, streamTrackingGlobalPosition, streamTransformations, sum, verifyThat };
572
+ export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, 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 DefaultStreamVersionType, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, type HandleOptions, 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 ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StreamingCoordinator, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, 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 };
package/dist/index.d.ts CHANGED
@@ -142,6 +142,7 @@ declare const assertExpectedVersionMatchesCurrent: <StreamVersion = bigint>(curr
142
142
  declare class ExpectedVersionConflictError<VersionType = DefaultStreamVersionType> extends ConcurrencyError {
143
143
  constructor(current: VersionType, expected: ExpectedStreamVersion<VersionType>);
144
144
  }
145
+ declare const isExpectedVersionConflictError: (error: unknown) => error is ExpectedVersionConflictError;
145
146
 
146
147
  interface EventStore<StreamVersion = DefaultStreamVersionType, ReadEventMetadataType extends ReadEventMetadata = ReadEventMetadata> {
147
148
  aggregateStream<State, EventType extends Event>(streamName: string, options: AggregateStreamOptions<State, EventType, StreamVersion, ReadEventMetadataType>): Promise<AggregateStreamResult<State, StreamVersion>>;
@@ -252,19 +253,17 @@ type CommandHandlerOptions<State, StreamEvent extends Event> = {
252
253
  evolve: (state: State, event: StreamEvent) => State;
253
254
  initialState: () => State;
254
255
  mapToStreamId?: (id: string) => string;
256
+ retry?: CommandHandlerRetryOptions;
255
257
  };
256
- declare const CommandHandler$1: <State, StreamEvent extends Event, StreamVersion = bigint>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore<StreamVersion>>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[], handleOptions?: Parameters<Store["appendToStream"]>[2] & ({
258
+ type HandleOptions<StreamVersion, Store extends EventStore<StreamVersion>> = Parameters<Store['appendToStream']>[2] & ({
257
259
  expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;
258
260
  } | {
259
261
  retry?: CommandHandlerRetryOptions;
260
- })) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
262
+ });
263
+ declare const CommandHandler$1: <State, StreamEvent extends Event, StreamVersion = bigint>(options: CommandHandlerOptions<State, StreamEvent>) => <Store extends EventStore<StreamVersion>>(store: Store, id: string, handle: (state: State) => StreamEvent | StreamEvent[] | Promise<StreamEvent> | Promise<StreamEvent[]>, handleOptions?: HandleOptions<StreamVersion, EventStore<StreamVersion>>) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
261
264
 
262
265
  type DeciderCommandHandlerOptions<State, CommandType extends Command, StreamEvent extends Event> = CommandHandlerOptions<State, StreamEvent> & Decider<State, CommandType, StreamEvent>;
263
- declare const DeciderCommandHandler: <State, CommandType extends Command, StreamEvent extends Event, StreamVersion = bigint>({ decide, evolve, initialState }: Decider<State, CommandType, StreamEvent>, mapToStreamId?: (id: string) => string) => (eventStore: EventStore<StreamVersion>, id: string, command: CommandType, handleOptions?: {
264
- expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;
265
- } | {
266
- retry?: CommandHandlerRetryOptions;
267
- }) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
266
+ declare const DeciderCommandHandler: <State, CommandType extends Command, StreamEvent extends Event, StreamVersion = bigint>(options: DeciderCommandHandlerOptions<State, CommandType, StreamEvent>) => (eventStore: EventStore<StreamVersion>, id: string, command: CommandType, handleOptions?: HandleOptions<StreamVersion, EventStore<StreamVersion>>) => Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>>;
268
267
 
269
268
  interface CommandSender {
270
269
  send<CommandType extends Command = Command>(command: CommandType): Promise<void>;
@@ -570,4 +569,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
570
569
  declare const assertPositiveNumber: (value: unknown) => number;
571
570
  declare const assertUnsignedBigInt: (value: string) => bigint;
572
571
 
573
- export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, 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 DefaultStreamVersionType, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, 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 ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StreamingCoordinator, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, 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, isGlobalStreamCaughtUp, isNotInternalEvent, isNumber, isString, isSubscriptionEvent, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, streamGenerators, streamTrackingGlobalPosition, streamTransformations, sum, verifyThat };
572
+ export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, type AsyncRetryOptions, 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 DefaultStreamVersionType, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, type GlobalStreamCaughtUp, GlobalStreamCaughtUpType, type GlobalSubscriptionEvent, type HandleOptions, 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 ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StreamingCoordinator, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, 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 };
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import{a as Be,b as Ue,c as $e,d as Je,e as Ke,f as Xe,g as Le,h as Ye,i as ze,j as K,k as j,l as X,m as Qe,n as Ze,o as et,p as tt}from"./chunk-6TXKRKDJ.js";var L=t=>"withSession"in t,Y=t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var nt=(t,e,r)=>({type:t,data:e,metadata:r});var z=(t,e,r)=>({type:t,data:e,metadata:r});var st=t=>({kind:"Reply",message:t}),it=t=>({kind:"Send",message:t}),mt=t=>({kind:"Publish",message:t}),dt=(t,e)=>({kind:"Schedule",message:t,when:e}),pt=()=>({kind:"Complete"}),lt=t=>({kind:"Ignore",reason:t}),ct=t=>({kind:"Error",reason:t}),ut=()=>({kind:"Accept"});var F="__emt:GlobalStreamCaughtUp",Q=t=>t.type===F,ht=t=>e=>e.type===F&&e.metadata?.globalPosition>=t,N=t=>z(F,t,{globalPosition:t.globalPosition}),Ct=t=>Q(t),Rt=t=>!Q(t);var ge="STREAM_EXISTS",W="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK",he=(t,e,r)=>e===O?!0:e==W?t===r:e==ge?t!==r:t===e,_=(t,e,r)=>{if(e??=O,!he(t,e,r))throw new E(t,e)},E=class t extends X{constructor(e,r){super(e?.toString(),r?.toString()),Object.setPrototypeOf(this,t.prototype)}};import{v4 as Me}from"uuid";import{ReadableStream as Ce,TransformStream as Re,WritableStream as be}from"web-streams-polyfill";var De={ReadableStream:Ce,WritableStream:be,TransformStream:Re};var Mt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,w;if(globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream)w=globalThis;else try{w=await import("node:stream/web")}catch{w=De}var s=w;var Z=t=>new G(t),G=class extends s.TransformStream{_currentPosition;_logPosition;constructor(e){super({start:r=>{let n=0n;for(let o of e)r.enqueue(o),n=o.metadata.globalPosition;r.enqueue(N({globalPosition:n}))},transform:(r,n)=>{this._currentPosition=r.metadata.globalPosition,n.enqueue(r),!(this._currentPosition<this._logPosition)&&n.enqueue(N({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}};import{v4 as we}from"uuid";import{v4 as Oe}from"uuid";var M=(t,e={})=>new x(t,e),x=class extends s.TransformStream{constructor(r,n={}){super({cancel:o=>{console.log("Stream was canceled. Reason:",o),this.stopChecking()}});this.onNoActiveReaderCallback=r;this.streamId=n?.streamId??Oe(),this.onNoActiveReaderCallback=r,this.startChecking(n?.intervalCheckInMs??20)}checkInterval=null;streamId;_isStopped=!1;get hasActiveSubscribers(){return!this._isStopped}startChecking(r){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},r)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}};var ee=async(t,e)=>{if(t.writable.locked)return!1;let r=t.writable.getWriter();if(await r.ready,!t.readable.locked)return!1;try{for(let n of e)await r.write(n)}catch(n){console.log(n)}finally{await r.close()}return!0};var te=()=>{let t=[],e=new Map;return{notify:async r=>{if(r.length!==0){t.push(...r);for(let n of e.values())n.logPosition=r[r.length-1].metadata.globalPosition,await ee(n,r)}},stream:()=>{let r=we(),n=Z(t);return e.set(r,n),n.readable.pipeThrough(M(o=>{e.has(o.streamId)&&e.delete(o.streamId)},{streamId:r}))}}};var g=0n,nr=()=>{let t=new Map,e=te(),r=()=>Array.from(t.values()).map(n=>n.length).reduce((n,o)=>n+o,0);return{async aggregateStream(n,o){let{evolve:a,initialState:m,read:d}=o,c=await this.readStream(n,d),v=c?.events??[];return{currentStreamVersion:BigInt(v.length),state:v.reduce(a,m()),streamExists:c.streamExists}},readStream:(n,o)=>{let a=t.get(n),m=a?BigInt(a.length):g;_(m,o?.expectedStreamVersion,g);let d=Number(o&&"from"in o?o.from:0),c=Number(o&&"to"in o?o.to:o&&"maxCount"in o&&o.maxCount?o.from+o.maxCount:a?.length??1),v=a!==void 0&&a.length>0?a.map(y=>y).slice(d,c):[],T={currentStreamVersion:m,events:v,streamExists:a!==void 0&&a.length>0};return Promise.resolve(T)},appendToStream:async(n,o,a)=>{let m=t.get(n)??[],d=m.length>0?BigInt(m.length):g;_(d,a?.expectedStreamVersion,g);let c=o.map((y,S)=>({...y,metadata:{...y.metadata??{},streamName:n,eventId:Me(),streamPosition:BigInt(m.length+S+1),globalPosition:BigInt(r()+S+1)}})),v=BigInt(c.slice(-1)[0].metadata.streamPosition);return t.set(n,[...m,...c]),await e.notify(c),{nextExpectedStreamVersion:v,createdNewStream:d===g}}}};var p=(t,e)=>{if(Ve(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>p(o,e[a]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length||!r.every(o=>n.includes(o)))return!1;for(let o in t){if(t[o]instanceof Function&&e[o]instanceof Function)continue;if(!p(t[o],e[o]))return!1}return!0},Ve=t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var cr=t=>{let e,r,n=0;do({value:e,done:r}=t.next()),n+=e||0;while(!r);return n};var fr=(t,e,r,n,o=()=>{})=>{let a=!1,m=t.map(d=>r(d)?(a=!0,n(d)):d).filter(d=>d!==void 0).map(d=>{if(!d)throw Error("That should not happen");return d});return!a&&o()!==void 0?[...t,e]:m};import Pe from"async-retry";var re={retries:0},V=async(t,e)=>e===void 0||e.retries===0?t():Pe(async r=>{try{return await t()}catch(n){throw e?.shouldRetryError&&!e.shouldRetryError(n)&&r(n),n}},e??{retries:0});var ne={retries:3,shouldRetryError:t=>t instanceof E},ke=t=>t===void 0?re:"onVersionConflict"in t?typeof t.onVersionConflict=="boolean"?ne:typeof t.onVersionConflict=="number"?{...ne,retries:t.onVersionConflict}:t.onVersionConflict:t,oe=t=>async(e,r,n,o)=>V(async()=>await Ae(e,async({eventStore:m})=>{let{evolve:d,initialState:c}=t,T=(t.mapToStreamId??(xe=>xe))(r),y=await m.aggregateStream(T,{evolve:d,initialState:c,read:{expectedStreamVersion:o?.expectedStreamVersion??O}}),S=y.state,J=y.currentStreamVersion,H=n(S),D=Array.isArray(H)?H:[H];if(D.length===0)return{newEvents:[],newState:S,nextExpectedStreamVersion:J,createdNewStream:!1};let Ee=o?.expectedStreamVersion??(y.streamExists?J:W);return{...await m.appendToStream(T,D,{...o,expectedStreamVersion:Ee}),newEvents:D,newState:D.reduce(d,S)}}),ke(o&&"retry"in o?o.retry:void 0)),Ae=(t,e)=>(L(t)?t:Y(t)).withSession(e);var Or=({decide:t,evolve:e,initialState:r},n=o=>o)=>async(o,a,m,d)=>oe({evolve:e,initialState:r,mapToStreamId:n})(o,a,c=>t(m,c),d);var Ir=()=>{let t=new Map,e=[];return{send:async r=>{let n=t.get(r.type);if(n===void 0||n.length===0)throw new j(`No handler registered for command ${r.type}!`);let o=n[0];await o(r)},publish:async r=>{let n=t.get(r.type)??[];for(let o of n)await o(r)},schedule:(r,n)=>{e=[...e,{message:r,options:n}]},handle:(r,...n)=>{let o=[...t.keys()].filter(a=>n.includes(a));if(o.length>0)throw new j(`Cannot register handler for commands ${o.join(", ")} as they're already registered!`);for(let a of n)t.set(a,[r])},subscribe(r,...n){for(let o of n)t.has(o)||t.set(o,[]),t.set(o,[...t.get(o)??[],r])},dequeue:()=>{let r=e;return e=[],r}}};var jr=t=>t,Ie=t=>t.map(e=>({type:"inline",projection:e})),He=t=>t.map(e=>({type:"async",projection:e})),Fr={inline:Ie,async:He};var q=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u={stringify:(t,e)=>JSON.stringify(e?.map?e.map(t):t,(r,n)=>typeof n=="bigint"?n.toString():n),parse:(t,e)=>{let r=JSON.parse(t,e?.reviver);if(e?.typeCheck&&!e?.typeCheck(r))throw new q(t);return e?.map?e.map(r):r}};var B=t=>{let e=t.reduce((o,a)=>o+a.length,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r};var $r=async t=>{let e=[];for await(let r of t)e.push(r);return e};var P=class{buffer=[];addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){let e=B(this.buffer);return new TextDecoder().decode(e).includes(`
1
+ import{a as Ue,b as $e,c as Je,d as Ke,e as Xe,f as Le,g as Ye,h as ze,i as Qe,j as K,k as j,l as X,m as Ze,n as et,o as tt,p as rt}from"./chunk-6TXKRKDJ.js";var L=t=>"withSession"in t,Y=t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var ot=(t,e,r)=>({type:t,data:e,metadata:r});var z=(t,e,r)=>({type:t,data:e,metadata:r});var it=t=>({kind:"Reply",message:t}),mt=t=>({kind:"Send",message:t}),dt=t=>({kind:"Publish",message:t}),pt=(t,e)=>({kind:"Schedule",message:t,when:e}),lt=()=>({kind:"Complete"}),ct=t=>({kind:"Ignore",reason:t}),ut=t=>({kind:"Error",reason:t}),ft=()=>({kind:"Accept"});var F="__emt:GlobalStreamCaughtUp",Q=t=>t.type===F,Ct=t=>e=>e.type===F&&e.metadata?.globalPosition>=t,N=t=>z(F,t,{globalPosition:t.globalPosition}),Rt=t=>Q(t),bt=t=>!Q(t);var he="STREAM_EXISTS",W="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK",Ce=(t,e,r)=>e===O?!0:e==W?t===r:e==he?t!==r:t===e,_=(t,e,r)=>{if(e??=O,!Ce(t,e,r))throw new D(t,e)},D=class t extends X{constructor(e,r){super(e?.toString(),r?.toString()),Object.setPrototypeOf(this,t.prototype)}},Z=t=>t instanceof D;import{v4 as Ve}from"uuid";import{ReadableStream as Re,TransformStream as be,WritableStream as De}from"web-streams-polyfill";var Oe={ReadableStream:Re,WritableStream:De,TransformStream:be};var Vt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,w;if(globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream)w=globalThis;else try{w=await import("node:stream/web")}catch{w=Oe}var s=w;var ee=t=>new G(t),G=class extends s.TransformStream{_currentPosition;_logPosition;constructor(e){super({start:r=>{let n=0n;for(let o of e)r.enqueue(o),n=o.metadata.globalPosition;r.enqueue(N({globalPosition:n}))},transform:(r,n)=>{this._currentPosition=r.metadata.globalPosition,n.enqueue(r),!(this._currentPosition<this._logPosition)&&n.enqueue(N({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}};import{v4 as Me}from"uuid";import{v4 as we}from"uuid";var M=(t,e={})=>new E(t,e),E=class extends s.TransformStream{constructor(r,n={}){super({cancel:o=>{console.log("Stream was canceled. Reason:",o),this.stopChecking()}});this.onNoActiveReaderCallback=r;this.streamId=n?.streamId??we(),this.onNoActiveReaderCallback=r,this.startChecking(n?.intervalCheckInMs??20)}checkInterval=null;streamId;_isStopped=!1;get hasActiveSubscribers(){return!this._isStopped}startChecking(r){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},r)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}};var te=async(t,e)=>{if(t.writable.locked)return!1;let r=t.writable.getWriter();if(await r.ready,!t.readable.locked)return!1;try{for(let n of e)await r.write(n)}catch(n){console.log(n)}finally{await r.close()}return!0};var re=()=>{let t=[],e=new Map;return{notify:async r=>{if(r.length!==0){t.push(...r);for(let n of e.values())n.logPosition=r[r.length-1].metadata.globalPosition,await te(n,r)}},stream:()=>{let r=Me(),n=ee(t);return e.set(r,n),n.readable.pipeThrough(M(o=>{e.has(o.streamId)&&e.delete(o.streamId)},{streamId:r}))}}};var x=0n,or=()=>{let t=new Map,e=re(),r=()=>Array.from(t.values()).map(n=>n.length).reduce((n,o)=>n+o,0);return{async aggregateStream(n,o){let{evolve:a,initialState:m,read:d}=o,c=await this.readStream(n,d),v=c?.events??[];return{currentStreamVersion:BigInt(v.length),state:v.reduce(a,m()),streamExists:c.streamExists}},readStream:(n,o)=>{let a=t.get(n),m=a?BigInt(a.length):x;_(m,o?.expectedStreamVersion,x);let d=Number(o&&"from"in o?o.from:0),c=Number(o&&"to"in o?o.to:o&&"maxCount"in o&&o.maxCount?o.from+o.maxCount:a?.length??1),v=a!==void 0&&a.length>0?a.map(y=>y).slice(d,c):[],T={currentStreamVersion:m,events:v,streamExists:a!==void 0&&a.length>0};return Promise.resolve(T)},appendToStream:async(n,o,a)=>{let m=t.get(n)??[],d=m.length>0?BigInt(m.length):x;_(d,a?.expectedStreamVersion,x);let c=o.map((y,S)=>({...y,metadata:{...y.metadata??{},streamName:n,eventId:Ve(),streamPosition:BigInt(m.length+S+1),globalPosition:BigInt(r()+S+1)}})),v=BigInt(c.slice(-1)[0].metadata.streamPosition);return t.set(n,[...m,...c]),await e.notify(c),{nextExpectedStreamVersion:v,createdNewStream:d===x}}}};var p=(t,e)=>{if(Pe(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>p(o,e[a]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length||!r.every(o=>n.includes(o)))return!1;for(let o in t){if(t[o]instanceof Function&&e[o]instanceof Function)continue;if(!p(t[o],e[o]))return!1}return!0},Pe=t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var ur=t=>{let e,r,n=0;do({value:e,done:r}=t.next()),n+=e||0;while(!r);return n};var yr=(t,e,r,n,o=()=>{})=>{let a=!1,m=t.map(d=>r(d)?(a=!0,n(d)):d).filter(d=>d!==void 0).map(d=>{if(!d)throw Error("That should not happen");return d});return!a&&o()!==void 0?[...t,e]:m};import ke from"async-retry";var ne={retries:0},V=async(t,e)=>e===void 0||e.retries===0?t():ke(async r=>{try{return await t()}catch(n){throw e?.shouldRetryError&&!e.shouldRetryError(n)&&r(n),n}},e??{retries:0});var oe={retries:3,minTimeout:100,factor:1.5,shouldRetryError:Z},Ae=t=>t===void 0?ne:"onVersionConflict"in t?typeof t.onVersionConflict=="boolean"?oe:typeof t.onVersionConflict=="number"?{...oe,retries:t.onVersionConflict}:t.onVersionConflict:t,ae=t=>async(e,r,n,o)=>V(async()=>await Ie(e,async({eventStore:m})=>{let{evolve:d,initialState:c}=t,T=(t.mapToStreamId??(ge=>ge))(r),y=await m.aggregateStream(T,{evolve:d,initialState:c,read:{expectedStreamVersion:o?.expectedStreamVersion??O}}),S=y.state,J=y.currentStreamVersion,H=await n(S),b=Array.isArray(H)?H:[H];if(b.length===0)return{newEvents:[],newState:S,nextExpectedStreamVersion:J,createdNewStream:!1};let xe=o?.expectedStreamVersion??(y.streamExists?J:W);return{...await m.appendToStream(T,b,{...o,expectedStreamVersion:xe}),newEvents:b,newState:b.reduce(d,S)}}),Ae(o&&"retry"in o?o.retry:t.retry)),Ie=(t,e)=>(L(t)?t:Y(t)).withSession(e);var wr=t=>async(e,r,n,o)=>{let{decide:a,...m}=t;return ae(m)(e,r,d=>a(n,d),o)};var Hr=()=>{let t=new Map,e=[];return{send:async r=>{let n=t.get(r.type);if(n===void 0||n.length===0)throw new j(`No handler registered for command ${r.type}!`);let o=n[0];await o(r)},publish:async r=>{let n=t.get(r.type)??[];for(let o of n)await o(r)},schedule:(r,n)=>{e=[...e,{message:r,options:n}]},handle:(r,...n)=>{let o=[...t.keys()].filter(a=>n.includes(a));if(o.length>0)throw new j(`Cannot register handler for commands ${o.join(", ")} as they're already registered!`);for(let a of n)t.set(a,[r])},subscribe(r,...n){for(let o of n)t.has(o)||t.set(o,[]),t.set(o,[...t.get(o)??[],r])},dequeue:()=>{let r=e;return e=[],r}}};var Fr=t=>t,He=t=>t.map(e=>({type:"inline",projection:e})),je=t=>t.map(e=>({type:"async",projection:e})),Nr={inline:He,async:je};var q=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u={stringify:(t,e)=>JSON.stringify(e?.map?e.map(t):t,(r,n)=>typeof n=="bigint"?n.toString():n),parse:(t,e)=>{let r=JSON.parse(t,e?.reviver);if(e?.typeCheck&&!e?.typeCheck(r))throw new q(t);return e?.map?e.map(r):r}};var B=t=>{let e=t.reduce((o,a)=>o+a.length,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r};var Jr=async t=>{let e=[];for await(let r of t)e.push(r);return e};var P=class{buffer=[];addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){let e=B(this.buffer);return new TextDecoder().decode(e).includes(`
2
2
  `)}decode(){if(!this.hasCompleteMessage())return null;let e=B(this.buffer),r=new TextDecoder().decode(e),n=r.indexOf(`
3
3
  `);if(n===-1)return null;let o=r.slice(0,n),a=new Uint8Array(e.buffer,n+1);return this.buffer=a.byteLength>0?[a]:[],JSON.parse(o)}};var k=class{constructor(e){this.transform=e;this.transform=e}buffer=[];addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){return this.buffer.some(e=>e.includes(`
4
4
  `))}decode(){let e=this.buffer.join("");if(!this.hasCompleteMessage()){if(e.trim().length>0)throw new Error("Unterminated string in JSON at position");return null}let r=e.indexOf(`
5
- `),n=e.slice(0,r).trim();return this.buffer=[e.slice(r+1)],this.transform(n)}};var A=class extends k{constructor(){super(e=>JSON.parse(e))}};var I=class{buffer=null;addToBuffer(e){this.buffer=e}clearBuffer(){this.buffer=null}hasCompleteMessage(){return this.buffer!==null}decode(){if(!this.hasCompleteMessage()||!this.buffer)return null;let e=this.buffer;return this.clearBuffer(),e}};var U=class{constructor(e){this.decoders=e}decoderFor(e){let r=this.decoders.find(n=>n[0](e));return r?r[1]:null}addToBuffer(e){this.decoderFor(e)?.addToBuffer(e)}clearBuffer(){for(let e of this.decoders.map(r=>r[1]))e.clearBuffer()}hasCompleteMessage(){return this.decoders.some(e=>e[1].hasCompleteMessage())}decode(){return this.decoders.map(r=>r[1]).find(r=>r.hasCompleteMessage())?.decode()??null}},h=class extends U{constructor(){super([[e=>typeof e=="string",new A],[e=>e instanceof Uint8Array,new P],[e=>typeof e=="object",new I]])}};var ae=t=>new s.ReadableStream({start(e){for(let r of t)e.enqueue(r);e.close()}});var un={fromArray:ae};var se=t=>new s.TransformStream({transform(e,r){t(e)&&r.enqueue(e)}});var ie=t=>new s.TransformStream({transform(e,r){r.enqueue(t(e))}});var me=(t,e)=>new C(t,e),C=class extends s.TransformStream{accumulator;reducer;constructor(e,r){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=r,this.reducer=e}};var de=(t,e,r={forever:!0,minTimeout:25})=>new s.TransformStream({start(n){V(()=>je(t,e,n),r).catch(o=>{n.error(o)})}}),je=async(t,e,r)=>{let o=t().getReader();try{let a;do{let m=await o.read();a=m.done,await e(m,r),a&&r.terminate()}while(!a)}finally{o.releaseLock()}};var pe=t=>new R(t),R=class extends s.TransformStream{count=0;skip;constructor(e){super({transform:(r,n)=>{this.count++,this.count>this.skip&&n.enqueue(r)}}),this.skip=e}};var le=t=>new s.TransformStream({transform(e,r){r.enqueue(e),t(e)&&r.terminate()}});var ce=t=>new s.TransformStream({async transform(e,r){if(!t(e)){r.enqueue(e);return}await Promise.resolve(),r.terminate()}});var ue=t=>new b(t),b=class extends s.TransformStream{count=0;limit;constructor(e){super({transform:(r,n)=>{this.count<this.limit?(this.count++,n.enqueue(r)):n.terminate()}}),this.limit=e}};var fe=t=>new s.TransformStream({start(e){let r=setTimeout(()=>{e.terminate()},t),n=e.terminate.bind(e);e.terminate=()=>{clearTimeout(r),n()}},transform(e,r){r.enqueue(e)}});var ye={filter:se,take:ue,TakeTransformStream:b,skip:pe,SkipTransformStream:R,map:ie,notifyAboutNoActiveReadersStream:M,NotifyAboutNoActiveReadersStream:x,reduce:me,ReduceTransformStream:C,retry:de,stopAfter:le,stopOn:ce,waitAtMost:fe};var{retry:Fe}=ye,Xn=(t,e=o=>o,r={forever:!0,minTimeout:25},n=new h)=>Fe(t,Ne(e,n),r).readable,Ne=(t=r=>r,e=new h)=>(r,n)=>{let{done:o,value:a}=r;a&&e.addToBuffer(a),!(!o&&!e.hasCompleteMessage())&&We(e,t,n)},We=(t,e,r)=>{try{let n=t.decode();if(!n)return;let o=e(n);r.enqueue(o)}catch(n){r.error(new Error(`Decoding error: ${n?.toString()}`))}};var l=class extends Error{constructor(e){super(e)}},ve=(t,e)=>{let r=t,n=e;return $(r),$(n),Object.keys(n).every(o=>typeof n[o]=="object"?ve(r[o],n[o]):n[o]===r[o])},ao=t=>{throw new l(t??"That should not ever happened, right?")},so=async(t,e)=>{try{throw await t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},io=(t,e)=>{try{throw t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},mo=async(t,e)=>{try{throw await t,new l("Function didn't throw expected error")}catch(r){if(!e)return;e instanceof Error?_e(r,e):i(e(r))}},Se=(t,e,r)=>{if(!ve(t,e))throw new l(r??`subObj:
5
+ `),n=e.slice(0,r).trim();return this.buffer=[e.slice(r+1)],this.transform(n)}};var A=class extends k{constructor(){super(e=>JSON.parse(e))}};var I=class{buffer=null;addToBuffer(e){this.buffer=e}clearBuffer(){this.buffer=null}hasCompleteMessage(){return this.buffer!==null}decode(){if(!this.hasCompleteMessage()||!this.buffer)return null;let e=this.buffer;return this.clearBuffer(),e}};var U=class{constructor(e){this.decoders=e}decoderFor(e){let r=this.decoders.find(n=>n[0](e));return r?r[1]:null}addToBuffer(e){this.decoderFor(e)?.addToBuffer(e)}clearBuffer(){for(let e of this.decoders.map(r=>r[1]))e.clearBuffer()}hasCompleteMessage(){return this.decoders.some(e=>e[1].hasCompleteMessage())}decode(){return this.decoders.map(r=>r[1]).find(r=>r.hasCompleteMessage())?.decode()??null}},g=class extends U{constructor(){super([[e=>typeof e=="string",new A],[e=>e instanceof Uint8Array,new P],[e=>typeof e=="object",new I]])}};var se=t=>new s.ReadableStream({start(e){for(let r of t)e.enqueue(r);e.close()}});var fn={fromArray:se};var ie=t=>new s.TransformStream({transform(e,r){t(e)&&r.enqueue(e)}});var me=t=>new s.TransformStream({transform(e,r){r.enqueue(t(e))}});var de=(t,e)=>new h(t,e),h=class extends s.TransformStream{accumulator;reducer;constructor(e,r){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=r,this.reducer=e}};var pe=(t,e,r={forever:!0,minTimeout:25})=>new s.TransformStream({start(n){V(()=>Fe(t,e,n),r).catch(o=>{n.error(o)})}}),Fe=async(t,e,r)=>{let o=t().getReader();try{let a;do{let m=await o.read();a=m.done,await e(m,r),a&&r.terminate()}while(!a)}finally{o.releaseLock()}};var le=t=>new C(t),C=class extends s.TransformStream{count=0;skip;constructor(e){super({transform:(r,n)=>{this.count++,this.count>this.skip&&n.enqueue(r)}}),this.skip=e}};var ce=t=>new s.TransformStream({transform(e,r){r.enqueue(e),t(e)&&r.terminate()}});var ue=t=>new s.TransformStream({async transform(e,r){if(!t(e)){r.enqueue(e);return}await Promise.resolve(),r.terminate()}});var fe=t=>new R(t),R=class extends s.TransformStream{count=0;limit;constructor(e){super({transform:(r,n)=>{this.count<this.limit?(this.count++,n.enqueue(r)):n.terminate()}}),this.limit=e}};var ye=t=>new s.TransformStream({start(e){let r=setTimeout(()=>{e.terminate()},t),n=e.terminate.bind(e);e.terminate=()=>{clearTimeout(r),n()}},transform(e,r){r.enqueue(e)}});var ve={filter:ie,take:fe,TakeTransformStream:R,skip:le,SkipTransformStream:C,map:me,notifyAboutNoActiveReadersStream:M,NotifyAboutNoActiveReadersStream:E,reduce:de,ReduceTransformStream:h,retry:pe,stopAfter:ce,stopOn:ue,waitAtMost:ye};var{retry:Ne}=ve,Ln=(t,e=o=>o,r={forever:!0,minTimeout:25},n=new g)=>Ne(t,We(e,n),r).readable,We=(t=r=>r,e=new g)=>(r,n)=>{let{done:o,value:a}=r;a&&e.addToBuffer(a),!(!o&&!e.hasCompleteMessage())&&_e(e,t,n)},_e=(t,e,r)=>{try{let n=t.decode();if(!n)return;let o=e(n);r.enqueue(o)}catch(n){r.error(new Error(`Decoding error: ${n?.toString()}`))}};var l=class extends Error{constructor(e){super(e)}},Se=(t,e)=>{let r=t,n=e;return $(r),$(n),Object.keys(n).every(o=>typeof n[o]=="object"?Se(r[o],n[o]):n[o]===r[o])},so=t=>{throw new l(t??"That should not ever happened, right?")},io=async(t,e)=>{try{throw await t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},mo=(t,e)=>{try{throw t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},po=async(t,e)=>{try{throw await t,new l("Function didn't throw expected error")}catch(r){if(!e)return;e instanceof Error?Ge(r,e):i(e(r))}},Te=(t,e,r)=>{if(!Se(t,e))throw new l(r??`subObj:
6
6
  ${u.stringify(e)}
7
7
  is not subset of
8
- ${u.stringify(t)}`)},_e=(t,e,r)=>{if(!p(t,e))throw new l(r??`subObj:
8
+ ${u.stringify(t)}`)},Ge=(t,e,r)=>{if(!p(t,e))throw new l(r??`subObj:
9
9
  ${u.stringify(e)}
10
10
  is not equal to
11
- ${u.stringify(t)}`)},po=(t,e,r)=>{if(p(t,e))throw new l(r??`subObj:
11
+ ${u.stringify(t)}`)},lo=(t,e,r)=>{if(p(t,e))throw new l(r??`subObj:
12
12
  ${u.stringify(e)}
13
13
  is equals to
14
- ${u.stringify(t)}`)},lo=t=>({isEqualTo:e=>i(p(t,e))});function Ge(t,e){if(t)throw new l(e??"Condition is false")}function i(t,e){if(!t)throw new l(e??"Condition is false")}function $(t,e){if(!t)throw new l(e??"Condition is not truthy")}function f(t,e,r){if(t!==e)throw new l(`${r??"Objects are not equal"}:
14
+ ${u.stringify(t)}`)},co=t=>({isEqualTo:e=>i(p(t,e))});function qe(t,e){if(t)throw new l(e??"Condition is false")}function i(t,e){if(!t)throw new l(e??"Condition is false")}function $(t,e){if(!t)throw new l(e??"Condition is not truthy")}function f(t,e,r){if(t!==e)throw new l(`${r??"Objects are not equal"}:
15
15
  Expected: ${u.stringify(t)}
16
- Actual:${u.stringify(e)}`)}function Te(t,e,r){if(t===e)throw new l(r??`Objects are equal: ${u.stringify(t)}`)}function co(t){Te(t,null),$(t)}function uo(t){f(t,null)}var fo=t=>e=>p(e,t),yo=t=>e=>t(e);function vo(t){return{calledTimes:e=>{f(t.mock?.calls?.length,e)},notCalled:()=>{f(t?.mock?.calls?.length,0)},called:()=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledOnceWith:(...e)=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length===1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledWithArgumentMatching:(...e)=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1),i(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>r.arguments&&r.arguments.length>=e.length&&e.every((n,o)=>n(r.arguments[o]))))},notCalledWithArgumentMatching:(...e)=>{Ge(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1&&t.mock.calls[0].arguments&&t.mock.calls[0].arguments.length>=e.length&&e.every((r,n)=>r(t.mock.calls[0].arguments[n])))}}}var So=t=>({isEmpty:()=>f(t.length,0),isNotEmpty:()=>Te(t.length,0),hasSize:e=>f(t.length,e),containsElements:(...e)=>{i(e.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrder:(...e)=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrderElementsOf:e=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyElementsOf:e=>{f(t.length,e.length);for(let r=0;r<t.length;r++)i(p(t[r],e[r]))},containsExactly:e=>{f(t.length,1),i(p(t[0],e))},contains:e=>{i(t.some(r=>p(r,e)))},containsOnlyOnceElementsOf:e=>{i(e.map(r=>t.filter(n=>p(n,r)).length).filter(r=>r===1).length===e.length)},containsAnyOf:(...e)=>{i(t.some(r=>e.some(n=>p(r,n))))},allMatch:e=>{i(t.every(e))},anyMatches:e=>{i(t.some(e))},allMatchAsync:async e=>{for(let r of t)i(await e(r))}});var go={for:t=>e=>({when:r=>{let n=()=>{let a=(Array.isArray(e)?e:[e]).reduce(t.evolve,t.initialState());return t.decide(r,a)};return{then:o=>{let a=n(),m=Array.isArray(a)?a:[a],d=Array.isArray(o)?o:[o];Se(m,d)},thenThrows:(...o)=>{try{throw n(),new l("Handler did not fail as expected")}catch(a){if(a instanceof l)throw a;if(o.length===0)return;if(!K(o[0])){i(o[0](a),`Error didn't match the error condition: ${a?.toString()}`);return}i(a instanceof o[0],`Caught error is not an instance of the expected type: ${a?.toString()}`),o[1]&&i(o[1](a),`Error didn't match the error condition: ${a?.toString()}`)}}}}})};var Ro=t=>{let e=new Map;return{async aggregateStream(r,n){return t.aggregateStream(r,n)},readStream(r,n){return t.readStream(r,n)},appendToStream:async(r,n,o)=>{let a=await t.appendToStream(r,n,o),m=e.get(r)??[r,[]];return e.set(r,[r,[...m[1],...n]]),a},appendedEvents:e,setup:async(r,n)=>t.appendToStream(r,n)}};export{l as AssertionError,P as BinaryJsonDecoder,G as CaughtUpTransformStream,oe as CommandHandler,ne as CommandHandlerStreamVersionConflictRetryOptions,U as CompositeDecoder,X as ConcurrencyError,Or as DeciderCommandHandler,go as DeciderSpecification,h as DefaultDecoder,j as EmmettError,E as ExpectedVersionConflictError,F as GlobalStreamCaughtUpType,Ze as IllegalStateError,g as InMemoryEventStoreDefaultStreamVersion,u as JSONParser,A as JsonDecoder,O as NO_CONCURRENCY_CHECK,re as NoRetries,et as NotFoundError,I as ObjectDecoder,q as ParseError,W as STREAM_DOES_NOT_EXIST,ge as STREAM_EXISTS,te as StreamingCoordinator,k as StringDecoder,Qe as ValidationError,Je as ValidationErrors,Ro as WrapEventStore,ut as accept,yo as argMatches,fo as argValue,_e as assertDeepEqual,f as assertEqual,_ as assertExpectedVersionMatchesCurrent,ao as assertFails,Ge as assertFalse,co as assertIsNotNull,uo as assertIsNull,Se as assertMatches,po as assertNotDeepEqual,Le as assertNotEmptyString,Te as assertNotEqual,$ as assertOk,Ye as assertPositiveNumber,mo as assertRejects,lo as assertThat,So as assertThatArray,io as assertThrows,so as assertThrowsAsync,i as assertTrue,ze as assertUnsignedBigInt,He as asyncProjections,V as asyncRetry,L as canCreateEventStoreSession,ht as caughtUpEventFrom,$r as collect,nt as command,pt as complete,B as concatUint8Arrays,p as deepEquals,ct as error,z as event,Be as formatDateToUtcYYYYMMDD,nr as getInMemoryEventStore,Ir as getInMemoryMessageBus,N as globalStreamCaughtUp,lt as ignore,Ie as inlineProjections,Ve as isEquatable,K as isErrorConstructor,Q as isGlobalStreamCaughtUp,Rt as isNotInternalEvent,Ke as isNumber,tt as isPluginConfig,Xe as isString,Ct as isSubscriptionEvent,ve as isSubset,Ue as isValidYYYYMMDD,he as matchesExpectedVersion,fr as merge,Y as nulloSessionFactory,$e as parseDateFromUtcYYYYMMDD,jr as projection,Fr as projections,mt as publish,st as reply,Xn as restream,dt as schedule,it as send,un as streamGenerators,Z as streamTrackingGlobalPosition,ye as streamTransformations,cr as sum,vo as verifyThat};
16
+ Actual:${u.stringify(e)}`)}function Ee(t,e,r){if(t===e)throw new l(r??`Objects are equal: ${u.stringify(t)}`)}function uo(t){Ee(t,null),$(t)}function fo(t){f(t,null)}var yo=t=>e=>p(e,t),vo=t=>e=>t(e);function So(t){return{calledTimes:e=>{f(t.mock?.calls?.length,e)},notCalled:()=>{f(t?.mock?.calls?.length,0)},called:()=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledOnceWith:(...e)=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length===1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledWithArgumentMatching:(...e)=>{i(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1),i(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>r.arguments&&r.arguments.length>=e.length&&e.every((n,o)=>n(r.arguments[o]))))},notCalledWithArgumentMatching:(...e)=>{qe(t.mock?.calls.length!==void 0&&t.mock.calls.length>=1&&t.mock.calls[0].arguments&&t.mock.calls[0].arguments.length>=e.length&&e.every((r,n)=>r(t.mock.calls[0].arguments[n])))}}}var To=t=>({isEmpty:()=>f(t.length,0),isNotEmpty:()=>Ee(t.length,0),hasSize:e=>f(t.length,e),containsElements:(...e)=>{i(e.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrder:(...e)=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrderElementsOf:e=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyElementsOf:e=>{f(t.length,e.length);for(let r=0;r<t.length;r++)i(p(t[r],e[r]))},containsExactly:e=>{f(t.length,1),i(p(t[0],e))},contains:e=>{i(t.some(r=>p(r,e)))},containsOnlyOnceElementsOf:e=>{i(e.map(r=>t.filter(n=>p(n,r)).length).filter(r=>r===1).length===e.length)},containsAnyOf:(...e)=>{i(t.some(r=>e.some(n=>p(r,n))))},allMatch:e=>{i(t.every(e))},anyMatches:e=>{i(t.some(e))},allMatchAsync:async e=>{for(let r of t)i(await e(r))}});var ho={for:t=>e=>({when:r=>{let n=()=>{let a=(Array.isArray(e)?e:[e]).reduce(t.evolve,t.initialState());return t.decide(r,a)};return{then:o=>{let a=n(),m=Array.isArray(a)?a:[a],d=Array.isArray(o)?o:[o];Te(m,d)},thenThrows:(...o)=>{try{throw n(),new l("Handler did not fail as expected")}catch(a){if(a instanceof l)throw a;if(o.length===0)return;if(!K(o[0])){i(o[0](a),`Error didn't match the error condition: ${a?.toString()}`);return}i(a instanceof o[0],`Caught error is not an instance of the expected type: ${a?.toString()}`),o[1]&&i(o[1](a),`Error didn't match the error condition: ${a?.toString()}`)}}}}})};var bo=t=>{let e=new Map;return{async aggregateStream(r,n){return t.aggregateStream(r,n)},readStream(r,n){return t.readStream(r,n)},appendToStream:async(r,n,o)=>{let a=await t.appendToStream(r,n,o),m=e.get(r)??[r,[]];return e.set(r,[r,[...m[1],...n]]),a},appendedEvents:e,setup:async(r,n)=>t.appendToStream(r,n)}};export{l as AssertionError,P as BinaryJsonDecoder,G as CaughtUpTransformStream,ae as CommandHandler,oe as CommandHandlerStreamVersionConflictRetryOptions,U as CompositeDecoder,X as ConcurrencyError,wr as DeciderCommandHandler,ho as DeciderSpecification,g as DefaultDecoder,j as EmmettError,D as ExpectedVersionConflictError,F as GlobalStreamCaughtUpType,et as IllegalStateError,x as InMemoryEventStoreDefaultStreamVersion,u as JSONParser,A as JsonDecoder,O as NO_CONCURRENCY_CHECK,ne as NoRetries,tt as NotFoundError,I as ObjectDecoder,q as ParseError,W as STREAM_DOES_NOT_EXIST,he as STREAM_EXISTS,re as StreamingCoordinator,k as StringDecoder,Ze as ValidationError,Ke as ValidationErrors,bo as WrapEventStore,ft as accept,vo as argMatches,yo as argValue,Ge as assertDeepEqual,f as assertEqual,_ as assertExpectedVersionMatchesCurrent,so as assertFails,qe as assertFalse,uo as assertIsNotNull,fo as assertIsNull,Te as assertMatches,lo as assertNotDeepEqual,Ye as assertNotEmptyString,Ee as assertNotEqual,$ as assertOk,ze as assertPositiveNumber,po as assertRejects,co as assertThat,To as assertThatArray,mo as assertThrows,io as assertThrowsAsync,i as assertTrue,Qe as assertUnsignedBigInt,je as asyncProjections,V as asyncRetry,L as canCreateEventStoreSession,Ct as caughtUpEventFrom,Jr as collect,ot as command,lt as complete,B as concatUint8Arrays,p as deepEquals,ut as error,z as event,Ue as formatDateToUtcYYYYMMDD,or as getInMemoryEventStore,Hr as getInMemoryMessageBus,N as globalStreamCaughtUp,ct as ignore,He as inlineProjections,Pe as isEquatable,K as isErrorConstructor,Z as isExpectedVersionConflictError,Q as isGlobalStreamCaughtUp,bt as isNotInternalEvent,Xe as isNumber,rt as isPluginConfig,Le as isString,Rt as isSubscriptionEvent,Se as isSubset,$e as isValidYYYYMMDD,Ce as matchesExpectedVersion,yr as merge,Y as nulloSessionFactory,Je as parseDateFromUtcYYYYMMDD,Fr as projection,Nr as projections,dt as publish,it as reply,Ln as restream,pt as schedule,mt as send,fn as streamGenerators,ee as streamTrackingGlobalPosition,ve as streamTransformations,ur as sum,So as verifyThat};
17
17
  //# sourceMappingURL=index.js.map