@robinmalfait/event-source 0.0.6 → 0.0.8

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.mts CHANGED
@@ -68,6 +68,7 @@ declare class EventSource {
68
68
  private constructor();
69
69
  static builder(store: EventStore): EventSourceBuilder;
70
70
  static new(store: EventStore, commandHandlers: Map<string, CommandHandler>, projectors: Projector[], eventHandlers: EventHandler[]): EventSource;
71
+ resetProjections(): Promise<void>;
71
72
  dispatch<T extends CommandType>(command: T): Promise<T>;
72
73
  loadEvents(): Promise<EventType<any, any>[]>;
73
74
  load<T extends Aggregate>(aggregate: T, aggregateId: string): Promise<T>;
@@ -81,16 +82,16 @@ declare class EventSourceBuilder {
81
82
  private eventHandlers;
82
83
  constructor(store: EventStore);
83
84
  build(): EventSource;
84
- addCommandHandler(commandType: string, handler: CommandHandler): void;
85
- addProjector(projector: Projector): void;
86
- addEventHandler(eventHandler: EventHandler): void;
85
+ addCommandHandler(commandType: string, handler: CommandHandler): this;
86
+ addProjector(projector: Projector): this;
87
+ addEventHandler(eventHandler: EventHandler): this;
87
88
  }
88
89
 
89
90
  type EventMapper$1 = Record<string, (event: EventType, es: EventSource) => void>;
90
91
  declare function createEventMapper(mapper: EventMapper$1): (event: EventType, es: EventSource) => void;
91
92
 
92
- type EventMapper<Ctx, T extends EventType> = Record<string, (event: T, ctx?: Ctx) => void>;
93
- declare function createProjector<Ctx, T extends EventType>(name: string, mapper: EventMapper<Ctx, T>, initializer?: (ctx?: Ctx) => Promise<void> | void, createContext?: () => Ctx): Projector;
93
+ type EventMapper<Ctx> = Record<string, (event: EventType, ctx?: Ctx) => void>;
94
+ declare function createProjector<Ctx>(name: string, mapper: EventMapper<Ctx>, initializer?: (ctx?: Ctx) => Promise<void> | void, createContext?: () => Ctx): Projector;
94
95
 
95
96
  declare function createTestEventStore(commandHandlers: Record<string, CommandHandler>, projectors?: Projector[]): {
96
97
  ___: any;
package/dist/index.d.ts CHANGED
@@ -68,6 +68,7 @@ declare class EventSource {
68
68
  private constructor();
69
69
  static builder(store: EventStore): EventSourceBuilder;
70
70
  static new(store: EventStore, commandHandlers: Map<string, CommandHandler>, projectors: Projector[], eventHandlers: EventHandler[]): EventSource;
71
+ resetProjections(): Promise<void>;
71
72
  dispatch<T extends CommandType>(command: T): Promise<T>;
72
73
  loadEvents(): Promise<EventType<any, any>[]>;
73
74
  load<T extends Aggregate>(aggregate: T, aggregateId: string): Promise<T>;
@@ -81,16 +82,16 @@ declare class EventSourceBuilder {
81
82
  private eventHandlers;
82
83
  constructor(store: EventStore);
83
84
  build(): EventSource;
84
- addCommandHandler(commandType: string, handler: CommandHandler): void;
85
- addProjector(projector: Projector): void;
86
- addEventHandler(eventHandler: EventHandler): void;
85
+ addCommandHandler(commandType: string, handler: CommandHandler): this;
86
+ addProjector(projector: Projector): this;
87
+ addEventHandler(eventHandler: EventHandler): this;
87
88
  }
88
89
 
89
90
  type EventMapper$1 = Record<string, (event: EventType, es: EventSource) => void>;
90
91
  declare function createEventMapper(mapper: EventMapper$1): (event: EventType, es: EventSource) => void;
91
92
 
92
- type EventMapper<Ctx, T extends EventType> = Record<string, (event: T, ctx?: Ctx) => void>;
93
- declare function createProjector<Ctx, T extends EventType>(name: string, mapper: EventMapper<Ctx, T>, initializer?: (ctx?: Ctx) => Promise<void> | void, createContext?: () => Ctx): Projector;
93
+ type EventMapper<Ctx> = Record<string, (event: EventType, ctx?: Ctx) => void>;
94
+ declare function createProjector<Ctx>(name: string, mapper: EventMapper<Ctx>, initializer?: (ctx?: Ctx) => Promise<void> | void, createContext?: () => Ctx): Projector;
94
95
 
95
96
  declare function createTestEventStore(commandHandlers: Record<string, CommandHandler>, projectors?: Projector[]): {
96
97
  ___: any;
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var L=Object.create;var y=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var F=(r,e)=>{for(var t in e)y(r,t,{get:e[t],enumerable:!0})},N=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Q(e))!q.call(r,o)&&o!==t&&y(r,o,{get:()=>e[o],enumerable:!(n=z(e,o))||n.enumerable});return r};var V=(r,e,t)=>(t=r!=null?L(R(r)):{},N(e||!r||!r.__esModule?y(t,"default",{value:r,enumerable:!0}):t,r)),Y=r=>N(y({},"__esModule",{value:!0}),r);var K={};F(K,{Aggregate:()=>j,Command:()=>U,Event:()=>W,EventSource:()=>v,abort:()=>l,createEventMapper:()=>I,createProjector:()=>$,createTestEventStore:()=>G,objectToYaml:()=>f});module.exports=Y(K);function w(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,w),t}function l(r,e){let t=w(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,l),t}function P(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&P(r[e]);return r}var J={NODE_ENV:process.env.NODE_ENV},j=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){J.NODE_ENV==="test"&&P(e);let t=this.apply[e.eventName];t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?l(`Aggregate "${this.constructor.name}" has no method:
1
+ "use strict";var L=Object.create;var y=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var F=(r,e)=>{for(var t in e)y(r,t,{get:e[t],enumerable:!0})},N=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Q(e))!q.call(r,o)&&o!==t&&y(r,o,{get:()=>e[o],enumerable:!(n=z(e,o))||n.enumerable});return r};var V=(r,e,t)=>(t=r!=null?L(R(r)):{},N(e||!r||!r.__esModule?y(t,"default",{value:r,enumerable:!0}):t,r)),Y=r=>N(y({},"__esModule",{value:!0}),r);var K={};F(K,{Aggregate:()=>j,Command:()=>U,Event:()=>W,EventSource:()=>u,abort:()=>c,createEventMapper:()=>I,createProjector:()=>$,createTestEventStore:()=>G,objectToYaml:()=>f});module.exports=Y(K);function P(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,P),t}function c(r,e){let t=P(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,c),t}function w(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&w(r[e]);return r}var J={NODE_ENV:process.env.NODE_ENV},j=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){J.NODE_ENV==="test"&&w(e);let t=this.apply[e.eventName];t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?c(`Aggregate "${this.constructor.name}" has no method:
2
2
 
3
3
  apply = {
4
4
  ${e.eventName}(event) {
5
5
  // Code goes here...
6
6
  }
7
7
  // ...
8
- }`):l(`Aggregate "${this.constructor.name}" has no method:
8
+ }`):c(`Aggregate "${this.constructor.name}" has no method:
9
9
 
10
10
  apply = {
11
11
  ['${e.eventName}'](event) {
@@ -15,16 +15,16 @@ apply = {
15
15
  }`));try{t(e)}catch(n){n instanceof Error&&console.error(`An error occurred inside your "%s" function:
16
16
  `,e.eventName,n.stack?.split(`
17
17
  `).map(o=>` ${o}`).join(`
18
- `))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function U(r,e=null){return{type:r,payload:e}}var k=require("crypto");function W(r,e,t=null){return{aggregateId:e,eventId:(0,k.randomUUID)(),eventName:r,payload:t,recordedAt:new Date,version:-1}}var M=V(require("yamlify-object")),Z={indent:" ",colors:{date:d,error:d,symbol:d,string:d,number:d,boolean:d,null:d,undefined:d}};function d(r){return r}function f(r){return r instanceof Error?f({...r}):(0,M.default)(r,Z).split(`
18
+ `))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function U(r,e=null){return{type:r,payload:e}}var M=require("crypto");function W(r,e,t=null){return{aggregateId:e,eventId:(0,M.randomUUID)(),eventName:r,payload:t,recordedAt:new Date,version:-1}}var k=V(require("yamlify-object")),Z={indent:" ",colors:{date:d,error:d,symbol:d,string:d,number:d,boolean:d,null:d,undefined:d}};function d(r){return r}function f(r){return r instanceof Error?f({...r}):(0,k.default)(r,Z).split(`
19
19
  `).slice(1).join(`
20
- `)}var v=class r{constructor(e,t,n,o){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=o}static builder(e){return new S(e)}static new(e,t,n,o){return new r(e,t,n,o)}async dispatch(e){return this.commandHandlers.has(e.type)||l(`There is no command handler for the "${e.type}" command`),await this.commandHandlers.get(e.type)(e,this),e}async loadEvents(){return this.store.loadEvents()}async load(e,t){let n=await this.store.load(t);return n.length<=0&&l(`Aggregate(${e.constructor.name}) with ID(${t}) does not exist.`,{aggregate:e.constructor.name,aggregateId:t}),e.replayEvents(n)}async persist(e){let t=e.releaseEvents();await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async o=>{try{await o.update(n)}catch(a){throw a instanceof Error&&console.error(`An error occurred in one of your projections: ${o.name}, given an event`,a.stack?.split(`
21
- `).map(p=>` ${p}`).join(`
22
- `)),a}})),await Promise.all(this.eventHandlers.map(async o=>{try{await o(n,this)}catch(a){throw a instanceof Error&&console.error(`An error occurred in one of your event handlers: ${o.name}, given an event`,a.stack?.split(`
23
- `).map(p=>` ${p}`).join(`
24
- `)),a}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},S=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];build(){return v.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers)}addCommandHandler(e,t){this.commandHandlers.has(e)&&l(`A command handler for the "${e}" command already exists`),this.commandHandlers.set(e,t)}addProjector(e){this.projectors.push(e)}addEventHandler(e){this.eventHandlers.push(e)}};function I(r){return(e,t)=>r[e.eventName]?.(e,t)}var T=new WeakMap;function h(r,e){if(T.has(r)){let t=T.get(r);for(let n in e)t[n]=e[n]}else T.set(r,e)}function g(r){return T.get(r)}var x=class{constructor(){h(this,{jobs:[],state:0})}get length(){return g(this).jobs.length}async start(){let{state:e,jobs:t}=g(this);if(!(e===1||t.length<=0)){for(h(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}h(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:o}=g(this);o.push({handle:e,resolve:t,reject:n}),setImmediate(()=>this.start())})}};function B(){}function $(r,e,t=B,n){let o=new x,a=n?.();return{name:r,async init(p){await o.push(()=>t(a));let s=await p.loadEvents();await Promise.all(s.map(i=>o.push(()=>e[i.eventName]?.(i,a))))},update(p){return o.push(()=>e[p.eventName]?.(p,a))}}}var H=Symbol("__placeholder__"),u={usedTestEventStoreInTest:!1,calledThenHandler:!1};process.env.NODE_ENV==="test"&&(beforeEach(()=>{u.usedTestEventStoreInTest=!1,u.calledThenHandler=!1}),afterEach(()=>{u.usedTestEventStoreInTest&&!u.calledThenHandler&&l("It seems like you used `createTestEventStore()`\nwithout using the `await then([expected, events, go, here, ...])`")}));function D(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var A=class{constructor(e=[],t=[]){this.db=e;this.producedEvents=t}name="test-recording-projector";init(){this.db.splice(0)}update(e){this.producedEvents.push(e)}};function G(r,e=[]){u.usedTestEventStoreInTest=!0;let t=new A,n=v.builder({load(s){return t.db.filter(i=>i.aggregateId===s)},loadEvents(){return t.db},persist(s){t.db.push(...s)}});for(let s of e)n.addProjector(s);n.addProjector(t);for(let[s,i]of Object.entries(r))n.addCommandHandler(s,i);let o=n.build(),a,p={___:H,async given(s=[]){t.db.push(...s)},async when(s){try{return await o.dispatch(typeof s=="function"?s():s)}catch(i){return i instanceof Error&&(a=i),i}},async then(s){if(u.calledThenHandler=!0,s instanceof Error){let b=s;D(()=>expect(a).toEqual(b),p.then);return}let i=s;if(a)throw Object.keys(a).length>0&&(a.message=["With properties:",`
25
- ${f(a)}
20
+ `)}var u=class r{constructor(e,t,n,o){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=o}static builder(e){return new S(e)}static new(e,t,n,o){return new r(e,t,n,o)}async resetProjections(){await Promise.all(this.projectors.map(e=>e.init(this)))}async dispatch(e){return this.commandHandlers.has(e.type)||c(`There is no command handler for the "${e.type}" command`),await this.commandHandlers.get(e.type)(e,this),e}async loadEvents(){return this.store.loadEvents()}async load(e,t){let n=await this.store.load(t);return n.length<=0&&c(`Aggregate(${e.constructor.name}) with ID(${t}) does not exist.`,{aggregate:e.constructor.name,aggregateId:t}),e.replayEvents(n)}async persist(e){let t=e.releaseEvents();await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async o=>{try{await o.update(n)}catch(s){throw s instanceof Error&&console.error(`An error occurred in one of your projections: ${o.name}, given an event`,s.stack?.split(`
21
+ `).map(i=>` ${i}`).join(`
22
+ `)),s}})),await Promise.all(this.eventHandlers.map(async o=>{try{await o(n,this)}catch(s){throw s instanceof Error&&console.error(`An error occurred in one of your event handlers: ${o.name}, given an event`,s.stack?.split(`
23
+ `).map(i=>` ${i}`).join(`
24
+ `)),s}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},S=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];build(){return u.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers)}addCommandHandler(e,t){return this.commandHandlers.has(e)&&c(`A command handler for the "${e}" command already exists`),this.commandHandlers.set(e,t),this}addProjector(e){return this.projectors.push(e),this}addEventHandler(e){return this.eventHandlers.push(e),this}};function I(r){return(e,t)=>r[e.eventName]?.(e,t)}var h=new WeakMap;function T(r,e){if(h.has(r)){let t=h.get(r);for(let n in e)t[n]=e[n]}else h.set(r,e)}function g(r){return h.get(r)}var x=class{constructor(){T(this,{jobs:[],state:0})}get length(){return g(this).jobs.length}async start(){let{state:e,jobs:t}=g(this);if(!(e===1||t.length<=0)){for(T(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}T(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:o}=g(this);o.push({handle:e,resolve:t,reject:n}),setImmediate(()=>this.start())})}};function B(){}function $(r,e,t=B,n){let o=new x,s=n?.();return{name:r,async init(i){await o.push(()=>t(s));let a=await i.loadEvents();await Promise.all(a.map(p=>this.update(p)))},update(i){return o.push(()=>e[i.eventName]?.(i,s))}}}var H=Symbol("__placeholder__"),v={usedTestEventStoreInTest:!1,calledThenHandler:!1};process.env.NODE_ENV==="test"&&(beforeEach(()=>{v.usedTestEventStoreInTest=!1,v.calledThenHandler=!1}),afterEach(()=>{v.usedTestEventStoreInTest&&!v.calledThenHandler&&c("It seems like you used `createTestEventStore()`\nwithout using the `await then([expected, events, go, here, ...])`")}));function D(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var A=class{constructor(e=[],t=[]){this.db=e;this.producedEvents=t}name="test-recording-projector";init(){this.db.splice(0)}update(e){this.producedEvents.push(e)}};function G(r,e=[]){v.usedTestEventStoreInTest=!0;let t=new A,n=u.builder({load(a){return t.db.filter(p=>p.aggregateId===a)},loadEvents(){return t.db},persist(a){t.db.push(...a)}});for(let a of e)n.addProjector(a);n.addProjector(t);for(let[a,p]of Object.entries(r))n.addCommandHandler(a,p);let o=n.build(),s,i={___:H,async given(a=[]){t.db.push(...a)},async when(a){try{return await o.dispatch(typeof a=="function"?a():a)}catch(p){return p instanceof Error&&(s=p),p}},async then(a){if(v.calledThenHandler=!0,a instanceof Error){let b=a;D(()=>expect(s).toEqual(b),i.then);return}let p=a;if(s)throw Object.keys(s).length>0&&(s.message=["With properties:",`
25
+ ${f(s)}
26
26
 
27
27
  ---
28
28
 
29
29
  `].join(`
30
- `)),a;D(()=>{expect(i).toHaveLength(t.producedEvents.length);for(let[b,c]of i.entries()){let{aggregateId:O,eventName:_,payload:m}=t.producedEvents[b];if(c.aggregateId===H)throw new Error("Expected an `aggregateId`, but got `___` instead.");expect(c.aggregateId).toEqual(O),expect(c.eventName).toEqual(_),(c.payload===null||c.payload===void 0)&&expect(c.payload).toEqual(m);for(let E in c.payload){let C=c.payload[E];C===H?(expect(m).toHaveProperty(E),expect(m[E]).toBeDefined()):expect(m[E]).toEqual(C)}}},p.then)}};return p}0&&(module.exports={Aggregate,Command,Event,EventSource,abort,createEventMapper,createProjector,createTestEventStore,objectToYaml});
30
+ `)),s;D(()=>{expect(p).toHaveLength(t.producedEvents.length);for(let[b,l]of p.entries()){let{aggregateId:O,eventName:_,payload:m}=t.producedEvents[b];if(l.aggregateId===H)throw new Error("Expected an `aggregateId`, but got `___` instead.");expect(l.aggregateId).toEqual(O),expect(l.eventName).toEqual(_),(l.payload===null||l.payload===void 0)&&expect(l.payload).toEqual(m);for(let E in l.payload){let C=l.payload[E];C===H?(expect(m).toHaveProperty(E),expect(m[E]).toBeDefined()):expect(m[E]).toEqual(C)}}},i.then)}};return i}0&&(module.exports={Aggregate,Command,Event,EventSource,abort,createEventMapper,createProjector,createTestEventStore,objectToYaml});
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- function x(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,x),t}function l(r,e){let t=x(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,l),t}function b(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&b(r[e]);return r}var M={NODE_ENV:process.env.NODE_ENV},A=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){M.NODE_ENV==="test"&&b(e);let t=this.apply[e.eventName];t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?l(`Aggregate "${this.constructor.name}" has no method:
1
+ function x(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,x),t}function c(r,e){let t=x(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,c),t}function b(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&b(r[e]);return r}var k={NODE_ENV:process.env.NODE_ENV},A=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){k.NODE_ENV==="test"&&b(e);let t=this.apply[e.eventName];t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?c(`Aggregate "${this.constructor.name}" has no method:
2
2
 
3
3
  apply = {
4
4
  ${e.eventName}(event) {
5
5
  // Code goes here...
6
6
  }
7
7
  // ...
8
- }`):l(`Aggregate "${this.constructor.name}" has no method:
8
+ }`):c(`Aggregate "${this.constructor.name}" has no method:
9
9
 
10
10
  apply = {
11
11
  ['${e.eventName}'](event) {
@@ -14,17 +14,17 @@ apply = {
14
14
  // ...
15
15
  }`));try{t(e)}catch(n){n instanceof Error&&console.error(`An error occurred inside your "%s" function:
16
16
  `,e.eventName,n.stack?.split(`
17
- `).map(o=>` ${o}`).join(`
18
- `))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function J(r,e=null){return{type:r,payload:e}}import{randomUUID as I}from"crypto";function Z(r,e,t=null){return{aggregateId:e,eventId:I(),eventName:r,payload:t,recordedAt:new Date,version:-1}}import $ from"yamlify-object";var D={indent:" ",colors:{date:d,error:d,symbol:d,string:d,number:d,boolean:d,null:d,undefined:d}};function d(r){return r}function w(r){return r instanceof Error?w({...r}):$(r,D).split(`
17
+ `).map(a=>` ${a}`).join(`
18
+ `))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function J(r,e=null){return{type:r,payload:e}}import{randomUUID as I}from"crypto";function Z(r,e,t=null){return{aggregateId:e,eventId:I(),eventName:r,payload:t,recordedAt:new Date,version:-1}}import $ from"yamlify-object";var D={indent:" ",colors:{date:d,error:d,symbol:d,string:d,number:d,boolean:d,null:d,undefined:d}};function d(r){return r}function P(r){return r instanceof Error?P({...r}):$(r,D).split(`
19
19
  `).slice(1).join(`
20
- `)}var u=class r{constructor(e,t,n,o){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=o}static builder(e){return new P(e)}static new(e,t,n,o){return new r(e,t,n,o)}async dispatch(e){return this.commandHandlers.has(e.type)||l(`There is no command handler for the "${e.type}" command`),await this.commandHandlers.get(e.type)(e,this),e}async loadEvents(){return this.store.loadEvents()}async load(e,t){let n=await this.store.load(t);return n.length<=0&&l(`Aggregate(${e.constructor.name}) with ID(${t}) does not exist.`,{aggregate:e.constructor.name,aggregateId:t}),e.replayEvents(n)}async persist(e){let t=e.releaseEvents();await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async o=>{try{await o.update(n)}catch(a){throw a instanceof Error&&console.error(`An error occurred in one of your projections: ${o.name}, given an event`,a.stack?.split(`
21
- `).map(p=>` ${p}`).join(`
22
- `)),a}})),await Promise.all(this.eventHandlers.map(async o=>{try{await o(n,this)}catch(a){throw a instanceof Error&&console.error(`An error occurred in one of your event handlers: ${o.name}, given an event`,a.stack?.split(`
23
- `).map(p=>` ${p}`).join(`
24
- `)),a}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},P=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];build(){return u.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers)}addCommandHandler(e,t){this.commandHandlers.has(e)&&l(`A command handler for the "${e}" command already exists`),this.commandHandlers.set(e,t)}addProjector(e){this.projectors.push(e)}addEventHandler(e){this.eventHandlers.push(e)}};function O(r){return(e,t)=>r[e.eventName]?.(e,t)}var y=new WeakMap;function f(r,e){if(y.has(r)){let t=y.get(r);for(let n in e)t[n]=e[n]}else y.set(r,e)}function T(r){return y.get(r)}var h=class{constructor(){f(this,{jobs:[],state:0})}get length(){return T(this).jobs.length}async start(){let{state:e,jobs:t}=T(this);if(!(e===1||t.length<=0)){for(f(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}f(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:o}=T(this);o.push({handle:e,resolve:t,reject:n}),setImmediate(()=>this.start())})}};function _(){}function L(r,e,t=_,n){let o=new h,a=n?.();return{name:r,async init(p){await o.push(()=>t(a));let s=await p.loadEvents();await Promise.all(s.map(i=>o.push(()=>e[i.eventName]?.(i,a))))},update(p){return o.push(()=>e[p.eventName]?.(p,a))}}}var j=Symbol("__placeholder__"),v={usedTestEventStoreInTest:!1,calledThenHandler:!1};process.env.NODE_ENV==="test"&&(beforeEach(()=>{v.usedTestEventStoreInTest=!1,v.calledThenHandler=!1}),afterEach(()=>{v.usedTestEventStoreInTest&&!v.calledThenHandler&&l("It seems like you used `createTestEventStore()`\nwithout using the `await then([expected, events, go, here, ...])`")}));function C(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var S=class{constructor(e=[],t=[]){this.db=e;this.producedEvents=t}name="test-recording-projector";init(){this.db.splice(0)}update(e){this.producedEvents.push(e)}};function ve(r,e=[]){v.usedTestEventStoreInTest=!0;let t=new S,n=u.builder({load(s){return t.db.filter(i=>i.aggregateId===s)},loadEvents(){return t.db},persist(s){t.db.push(...s)}});for(let s of e)n.addProjector(s);n.addProjector(t);for(let[s,i]of Object.entries(r))n.addCommandHandler(s,i);let o=n.build(),a,p={___:j,async given(s=[]){t.db.push(...s)},async when(s){try{return await o.dispatch(typeof s=="function"?s():s)}catch(i){return i instanceof Error&&(a=i),i}},async then(s){if(v.calledThenHandler=!0,s instanceof Error){let g=s;C(()=>expect(a).toEqual(g),p.then);return}let i=s;if(a)throw Object.keys(a).length>0&&(a.message=["With properties:",`
25
- ${w(a)}
20
+ `)}var v=class r{constructor(e,t,n,a){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=a}static builder(e){return new w(e)}static new(e,t,n,a){return new r(e,t,n,a)}async resetProjections(){await Promise.all(this.projectors.map(e=>e.init(this)))}async dispatch(e){return this.commandHandlers.has(e.type)||c(`There is no command handler for the "${e.type}" command`),await this.commandHandlers.get(e.type)(e,this),e}async loadEvents(){return this.store.loadEvents()}async load(e,t){let n=await this.store.load(t);return n.length<=0&&c(`Aggregate(${e.constructor.name}) with ID(${t}) does not exist.`,{aggregate:e.constructor.name,aggregateId:t}),e.replayEvents(n)}async persist(e){let t=e.releaseEvents();await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async a=>{try{await a.update(n)}catch(s){throw s instanceof Error&&console.error(`An error occurred in one of your projections: ${a.name}, given an event`,s.stack?.split(`
21
+ `).map(i=>` ${i}`).join(`
22
+ `)),s}})),await Promise.all(this.eventHandlers.map(async a=>{try{await a(n,this)}catch(s){throw s instanceof Error&&console.error(`An error occurred in one of your event handlers: ${a.name}, given an event`,s.stack?.split(`
23
+ `).map(i=>` ${i}`).join(`
24
+ `)),s}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},w=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];build(){return v.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers)}addCommandHandler(e,t){return this.commandHandlers.has(e)&&c(`A command handler for the "${e}" command already exists`),this.commandHandlers.set(e,t),this}addProjector(e){return this.projectors.push(e),this}addEventHandler(e){return this.eventHandlers.push(e),this}};function O(r){return(e,t)=>r[e.eventName]?.(e,t)}var y=new WeakMap;function f(r,e){if(y.has(r)){let t=y.get(r);for(let n in e)t[n]=e[n]}else y.set(r,e)}function h(r){return y.get(r)}var T=class{constructor(){f(this,{jobs:[],state:0})}get length(){return h(this).jobs.length}async start(){let{state:e,jobs:t}=h(this);if(!(e===1||t.length<=0)){for(f(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}f(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:a}=h(this);a.push({handle:e,resolve:t,reject:n}),setImmediate(()=>this.start())})}};function _(){}function L(r,e,t=_,n){let a=new T,s=n?.();return{name:r,async init(i){await a.push(()=>t(s));let o=await i.loadEvents();await Promise.all(o.map(p=>this.update(p)))},update(i){return a.push(()=>e[i.eventName]?.(i,s))}}}var j=Symbol("__placeholder__"),u={usedTestEventStoreInTest:!1,calledThenHandler:!1};process.env.NODE_ENV==="test"&&(beforeEach(()=>{u.usedTestEventStoreInTest=!1,u.calledThenHandler=!1}),afterEach(()=>{u.usedTestEventStoreInTest&&!u.calledThenHandler&&c("It seems like you used `createTestEventStore()`\nwithout using the `await then([expected, events, go, here, ...])`")}));function C(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var S=class{constructor(e=[],t=[]){this.db=e;this.producedEvents=t}name="test-recording-projector";init(){this.db.splice(0)}update(e){this.producedEvents.push(e)}};function ue(r,e=[]){u.usedTestEventStoreInTest=!0;let t=new S,n=v.builder({load(o){return t.db.filter(p=>p.aggregateId===o)},loadEvents(){return t.db},persist(o){t.db.push(...o)}});for(let o of e)n.addProjector(o);n.addProjector(t);for(let[o,p]of Object.entries(r))n.addCommandHandler(o,p);let a=n.build(),s,i={___:j,async given(o=[]){t.db.push(...o)},async when(o){try{return await a.dispatch(typeof o=="function"?o():o)}catch(p){return p instanceof Error&&(s=p),p}},async then(o){if(u.calledThenHandler=!0,o instanceof Error){let g=o;C(()=>expect(s).toEqual(g),i.then);return}let p=o;if(s)throw Object.keys(s).length>0&&(s.message=["With properties:",`
25
+ ${P(s)}
26
26
 
27
27
  ---
28
28
 
29
29
  `].join(`
30
- `)),a;C(()=>{expect(i).toHaveLength(t.producedEvents.length);for(let[g,c]of i.entries()){let{aggregateId:N,eventName:k,payload:m}=t.producedEvents[g];if(c.aggregateId===j)throw new Error("Expected an `aggregateId`, but got `___` instead.");expect(c.aggregateId).toEqual(N),expect(c.eventName).toEqual(k),(c.payload===null||c.payload===void 0)&&expect(c.payload).toEqual(m);for(let E in c.payload){let H=c.payload[E];H===j?(expect(m).toHaveProperty(E),expect(m[E]).toBeDefined()):expect(m[E]).toEqual(H)}}},p.then)}};return p}export{A as Aggregate,J as Command,Z as Event,u as EventSource,l as abort,O as createEventMapper,L as createProjector,ve as createTestEventStore,w as objectToYaml};
30
+ `)),s;C(()=>{expect(p).toHaveLength(t.producedEvents.length);for(let[g,l]of p.entries()){let{aggregateId:N,eventName:M,payload:m}=t.producedEvents[g];if(l.aggregateId===j)throw new Error("Expected an `aggregateId`, but got `___` instead.");expect(l.aggregateId).toEqual(N),expect(l.eventName).toEqual(M),(l.payload===null||l.payload===void 0)&&expect(l.payload).toEqual(m);for(let E in l.payload){let H=l.payload[E];H===j?(expect(m).toHaveProperty(E),expect(m[E]).toBeDefined()):expect(m[E]).toEqual(H)}}},i.then)}};return i}export{A as Aggregate,J as Command,Z as Event,v as EventSource,c as abort,O as createEventMapper,L as createProjector,ue as createTestEventStore,P as objectToYaml};
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.6",
2
+ "version": "0.0.8",
3
3
  "name": "@robinmalfait/event-source",
4
4
  "publishConfig": {
5
5
  "access": "public"