@robinmalfait/event-source 0.0.16 → 0.0.18
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/README.md +278 -21
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +21 -15
- package/dist/index.d.ts +21 -15
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,34 +1,291 @@
|
|
|
1
1
|
# Event Source
|
|
2
2
|
|
|
3
|
-
A
|
|
3
|
+
A TypeScript library for building event-sourced applications in Node.js. This library provides the foundational building blocks for implementing CQRS (Command Query Responsibility Segregation) and Event Sourcing patterns.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Installation
|
|
6
6
|
|
|
7
|
-
```
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
Event,
|
|
12
|
-
abort,
|
|
13
|
-
createEventMapper,
|
|
14
|
-
createEventSource,
|
|
15
|
-
createProjector,
|
|
16
|
-
createTestEventStore,
|
|
17
|
-
} from '@robinmalfait/event-source'
|
|
7
|
+
```bash
|
|
8
|
+
npm install @robinmalfait/event-source
|
|
9
|
+
# or
|
|
10
|
+
pnpm add @robinmalfait/event-source
|
|
18
11
|
```
|
|
19
12
|
|
|
20
|
-
##
|
|
13
|
+
## Core Concepts
|
|
14
|
+
|
|
15
|
+
### Events
|
|
16
|
+
|
|
17
|
+
Events are immutable records of something that happened in your domain. They contain an aggregate ID, payload, metadata, and version information.
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { Event } from '@robinmalfait/event-source'
|
|
21
|
+
|
|
22
|
+
function accountOpened(id: string, owner: string) {
|
|
23
|
+
return Event('ACCOUNT_OPENED', id, { owner })
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function moneyDeposited(id: string, amount: number) {
|
|
27
|
+
return Event('MONEY_DEPOSITED', id, { amount })
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Commands
|
|
32
|
+
|
|
33
|
+
Commands represent an intent to perform an action. They carry a type and payload.
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { Command } from '@robinmalfait/event-source'
|
|
37
|
+
|
|
38
|
+
function openAccount(id: string, owner: string) {
|
|
39
|
+
return Command('OPEN_ACCOUNT', { id, owner })
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function depositMoney(accountId: string, amount: number) {
|
|
43
|
+
return Command('DEPOSIT_MONEY', { accountId, amount })
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Aggregates
|
|
48
|
+
|
|
49
|
+
Aggregates are domain entities that emit events and rebuild their state from event history. They extend the base `Aggregate` class and define `apply` handlers for each event type.
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { Aggregate, type ApplyEvents, abort } from '@robinmalfait/event-source'
|
|
53
|
+
|
|
54
|
+
class Account extends Aggregate {
|
|
55
|
+
private owner: string = ''
|
|
56
|
+
private balance: number = 0
|
|
57
|
+
private closed: boolean = false
|
|
58
|
+
|
|
59
|
+
// Static factory methods for creating new aggregates
|
|
60
|
+
static open(id: string, owner: string) {
|
|
61
|
+
return new Account().recordThat(accountOpened(id, owner))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Instance methods for operations on existing aggregates
|
|
65
|
+
deposit(amount: number) {
|
|
66
|
+
if (this.closed) {
|
|
67
|
+
abort('Cannot deposit to a closed account')
|
|
68
|
+
}
|
|
69
|
+
return this.recordThat(moneyDeposited(this.aggregateId, amount))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Apply handlers rebuild state from events
|
|
73
|
+
apply: ApplyEvents<
|
|
74
|
+
typeof accountOpened | typeof moneyDeposited | typeof accountClosed
|
|
75
|
+
> = {
|
|
76
|
+
ACCOUNT_OPENED: (event) => {
|
|
77
|
+
this.owner = event.payload.owner
|
|
78
|
+
},
|
|
79
|
+
MONEY_DEPOSITED: (event) => {
|
|
80
|
+
this.balance += event.payload.amount
|
|
81
|
+
},
|
|
82
|
+
ACCOUNT_CLOSED: () => {
|
|
83
|
+
this.closed = true
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Setting Up EventSource
|
|
90
|
+
|
|
91
|
+
The `EventSource` class is the central coordinator that connects everything together. Use the builder pattern to configure it:
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
import { EventSource } from '@robinmalfait/event-source'
|
|
95
|
+
|
|
96
|
+
const eventSource = EventSource.builder(myEventStore)
|
|
97
|
+
.addCommandHandler('OPEN_ACCOUNT', openAccountHandler)
|
|
98
|
+
.addCommandHandler('DEPOSIT_MONEY', depositMoneyHandler)
|
|
99
|
+
.addProjector(new BalanceProjector())
|
|
100
|
+
.addEventHandler(sendNotificationHandler)
|
|
101
|
+
.metadata(() => ({ userId: getCurrentUserId() }))
|
|
102
|
+
.build()
|
|
103
|
+
|
|
104
|
+
// Dispatch commands
|
|
105
|
+
await eventSource.dispatch(openAccount('acc-123', 'John Doe'))
|
|
106
|
+
await eventSource.dispatch(depositMoney('acc-123', 1000))
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Command Handlers
|
|
110
|
+
|
|
111
|
+
Command handlers receive a command and the event source instance, and return an aggregate to persist:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import type { CommandHandler } from '@robinmalfait/event-source'
|
|
115
|
+
|
|
116
|
+
const openAccountHandler: CommandHandler<
|
|
117
|
+
ReturnType<typeof openAccount>
|
|
118
|
+
> = async (command, es) => {
|
|
119
|
+
return es.persist(Account.open(command.payload.id, command.payload.owner))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const depositMoneyHandler: CommandHandler<
|
|
123
|
+
ReturnType<typeof depositMoney>
|
|
124
|
+
> = async (command, es) => {
|
|
125
|
+
let account = await es.load(Account, command.payload.accountId)
|
|
126
|
+
return es.persist(account.deposit(command.payload.amount))
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### EventStore Interface
|
|
131
|
+
|
|
132
|
+
To use the library, implement the `EventStore` interface with your preferred storage:
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
import type { EventStore, EventType } from '@robinmalfait/event-source'
|
|
136
|
+
|
|
137
|
+
class MyEventStore implements EventStore {
|
|
138
|
+
async persist(events: EventType[]): Promise<void> {
|
|
139
|
+
// Store events in your database
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async load(aggregateId: string): Promise<EventType[]> {
|
|
143
|
+
// Load all events for an aggregate
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async loadEvents(): Promise<EventType[]> {
|
|
147
|
+
// Load all events (for rebuilding projections)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
See the [`examples/mysql-event-store`](./examples/mysql-event-store) directory for a MySQL implementation using Knex.js.
|
|
21
153
|
|
|
22
|
-
|
|
154
|
+
### Projectors
|
|
155
|
+
|
|
156
|
+
Projectors build read models from events. They process events sequentially and maintain derived state.
|
|
157
|
+
|
|
158
|
+
**Lifecycle:**
|
|
159
|
+
|
|
160
|
+
- **Normal operation:** When events are persisted via `es.persist()`, each projector's `apply` handlers are called for the new events only.
|
|
161
|
+
- **Full rebuild:** When `es.resetProjections()` is called, `reset()` is called first (to clear existing state), then all events are replayed through `apply`.
|
|
162
|
+
|
|
163
|
+
This means projectors work well in serverless environments - projections are persisted to your database and don't need rebuilding on every cold start.
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
import { Projector, type ApplyEvents } from '@robinmalfait/event-source'
|
|
167
|
+
|
|
168
|
+
class BalanceProjector extends Projector {
|
|
169
|
+
name = 'balance-projector'
|
|
170
|
+
private balances = new Map<string, number>()
|
|
171
|
+
|
|
172
|
+
async reset() {
|
|
173
|
+
// Called only during resetProjections() - clear state before full rebuild
|
|
174
|
+
this.balances.clear()
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
apply: ApplyEvents<typeof accountOpened | typeof moneyDeposited> = {
|
|
178
|
+
ACCOUNT_OPENED: (event) => {
|
|
179
|
+
this.balances.set(event.aggregateId, 0)
|
|
180
|
+
},
|
|
181
|
+
MONEY_DEPOSITED: (event) => {
|
|
182
|
+
let current = this.balances.get(event.aggregateId) ?? 0
|
|
183
|
+
this.balances.set(event.aggregateId, current + event.payload.amount)
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
getBalance(accountId: string) {
|
|
188
|
+
return this.balances.get(accountId) ?? 0
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Testing
|
|
194
|
+
|
|
195
|
+
The library provides BDD-style testing utilities with a `given/when/then` pattern:
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
import { createTestEventStore } from '@robinmalfait/event-source'
|
|
199
|
+
|
|
200
|
+
describe('deposit money', () => {
|
|
201
|
+
let { given, when, then, ___ } = createTestEventStore({
|
|
202
|
+
DEPOSIT_MONEY: depositMoneyHandler,
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
it('should deposit money to an open account', async () => {
|
|
206
|
+
await given([accountOpened('acc-123', 'John Doe')])
|
|
207
|
+
|
|
208
|
+
await when(depositMoney('acc-123', 500))
|
|
209
|
+
|
|
210
|
+
await then([moneyDeposited('acc-123', 500)])
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
it('should fail when depositing to a closed account', async () => {
|
|
214
|
+
await given([
|
|
215
|
+
accountOpened('acc-123', 'John Doe'),
|
|
216
|
+
accountClosed('acc-123'),
|
|
217
|
+
])
|
|
218
|
+
|
|
219
|
+
await when(depositMoney('acc-123', 500))
|
|
220
|
+
|
|
221
|
+
await then(new Error('Cannot deposit to a closed account'))
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
it('should use placeholders for values we do not care about', async () => {
|
|
225
|
+
await given([accountOpened('acc-123', 'John Doe')])
|
|
226
|
+
|
|
227
|
+
await when(depositMoney('acc-123', 500))
|
|
228
|
+
|
|
229
|
+
// Use ___ as a placeholder for any value
|
|
230
|
+
await then([Event('MONEY_DEPOSITED', ___, { amount: 500 })])
|
|
231
|
+
})
|
|
232
|
+
})
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## Utilities
|
|
236
|
+
|
|
237
|
+
### abort
|
|
238
|
+
|
|
239
|
+
Throw errors with clean stack traces and custom attributes:
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { abort } from '@robinmalfait/event-source'
|
|
243
|
+
|
|
244
|
+
if (balance < amount) {
|
|
245
|
+
abort('Insufficient funds', { balance, requested: amount })
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
### Type Utilities
|
|
250
|
+
|
|
251
|
+
Extract types from events and commands:
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
import type { PayloadOf, TypeOf } from '@robinmalfait/event-source'
|
|
255
|
+
|
|
256
|
+
type AccountOpenedPayload = PayloadOf<ReturnType<typeof accountOpened>>
|
|
257
|
+
// { owner: string }
|
|
258
|
+
|
|
259
|
+
type AccountOpenedType = TypeOf<ReturnType<typeof accountOpened>>
|
|
260
|
+
// 'ACCOUNT_OPENED'
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Examples
|
|
264
|
+
|
|
265
|
+
See the [`examples/bank`](./examples/bank) directory for a complete bank account domain implementation demonstrating:
|
|
266
|
+
|
|
267
|
+
- Domain events and commands
|
|
268
|
+
- Account aggregate with business rules
|
|
269
|
+
- Command handlers
|
|
270
|
+
- Test cases using the given/when/then pattern
|
|
271
|
+
|
|
272
|
+
## Local Development
|
|
23
273
|
|
|
24
|
-
###
|
|
274
|
+
### Prerequisites
|
|
25
275
|
|
|
26
|
-
|
|
276
|
+
- Node.js 24+ (see `.nvmrc`)
|
|
277
|
+
- pnpm
|
|
27
278
|
|
|
28
|
-
###
|
|
279
|
+
### Commands
|
|
29
280
|
|
|
30
|
-
|
|
281
|
+
| Command | Description |
|
|
282
|
+
| ------------- | ----------------------------------------------------- |
|
|
283
|
+
| `pnpm start` | Build in watch mode for development |
|
|
284
|
+
| `pnpm build` | Production build (ESM + CJS + TypeScript definitions) |
|
|
285
|
+
| `pnpm test` | Run all tests |
|
|
286
|
+
| `pnpm tdd` | Run tests in watch mode |
|
|
287
|
+
| `pnpm format` | Format code with Prettier |
|
|
31
288
|
|
|
32
|
-
|
|
289
|
+
## License
|
|
33
290
|
|
|
34
|
-
|
|
291
|
+
MIT
|
package/dist/index.cjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var z=Object.create;var h=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty;var R=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},H=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of I(e))!J.call(r,a)&&a!==t&&h(r,a,{get:()=>e[a],enumerable:!(n=D(e,a))||n.enumerable});return r};var B=(r,e,t)=>(t=r!=null?z(_(r)):{},H(e||!r||!r.__esModule?h(t,"default",{value:r,enumerable:!0}):t,r)),Q=r=>H(h({},"__esModule",{value:!0}),r);var W={};R(W,{Aggregate:()=>A,Command:()=>V,Event:()=>Y,EventSource:()=>E,Projector:()=>m,abort:()=>c,createEventMapper:()=>C,createTestEventStore:()=>U,objectToYaml:()=>f});module.exports=Q(W);function M(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,M),t}function c(r,e){let t=M(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,c),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 F={NODE_ENV:typeof process<"u"?process.env?.NODE_ENV:void 0},A=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){F.NODE_ENV==="test"&&P(e);let t=this.apply[e.eventName];return 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
|
-
}`):
|
|
8
|
+
}`):c(`Aggregate "${this.constructor.name}" has no method:
|
|
9
9
|
|
|
10
10
|
apply = {
|
|
11
11
|
['${e.eventName}'](event) {
|
|
12
12
|
// Code goes here...
|
|
13
13
|
}
|
|
14
14
|
// ...
|
|
15
|
-
}`)),t(e),this.#e++,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
|
|
15
|
+
}`)),t(e),this.#e++,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 V(r,e=null){return{type:r,payload:e}}function Y(r,e,t=null,n=null){return{aggregateId:e,eventId:globalThis.crypto.randomUUID(),eventName:r,payload:t,metadata:n,recordedAt:new Date,version:-1}}var k=B(require("yamlify-object"),1),q={indent:" ",colors:{date:v,error:v,symbol:v,string:v,number:v,boolean:v,null:v,undefined:v}};function v(r){return r}function f(r){return r instanceof Error?f({...r}):(0,k.default)(r,q).split(`
|
|
16
16
|
`).slice(1).join(`
|
|
17
|
-
`)}var T=new WeakMap;function g(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
|
|
17
|
+
`)}var T=new WeakMap;function g(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 x(r){return T.get(r)}var b=class{constructor(){g(this,{jobs:[],state:0})}get length(){return x(this).jobs.length}async start(){let{state:e,jobs:t}=x(this);if(!(e===1||t.length<=0)){for(g(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}g(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:a}=x(this);a.push({handle:e,resolve:t,reject:n}),queueMicrotask(()=>this.start())})}};var m=class{apply;reset(){}#e=new b;async init(e){this.reset&&await this.#e.push(()=>this.reset?.());for(let t of e)await this.applyEvent(t)}async applyEvent(e){await this.#e.push(()=>this.apply?.[e.eventName]?.(e)),await this.#e.push(()=>this.project(e))}project(e){}},E=class r{constructor(e,t,n,a,o){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=a;this.eventMetadataEnhancers=o}static builder(e){return new j(e)}static new(e,t,n,a,o){return new r(e,t,n,a,o)}async resetProjections(){let e=await this.store.loadEvents();await Promise.all(this.projectors.map(t=>t.init(e)))}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();if(this.eventMetadataEnhancers.length>0){let n={};for(let a of this.eventMetadataEnhancers)Object.assign(n,await a());for(let a of t){let o=a.metadata??{};a.metadata=Object.assign({},n,o)}}await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async a=>{try{await a.applyEvent(n)}catch(o){throw o instanceof Error&&console.error(`An error occurred in one of your projections: ${a.name}, given an event`,o.stack?.split(`
|
|
18
18
|
`).map(y=>` ${y}`).join(`
|
|
19
19
|
`)),o}})),await Promise.all(this.eventHandlers.map(async a=>{try{await a(n,this)}catch(o){throw o instanceof Error&&console.error(`An error occurred in one of your event handlers: ${a.name}, given an event`,o.stack?.split(`
|
|
20
20
|
`).map(y=>` ${y}`).join(`
|
|
21
|
-
`)),o}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},
|
|
21
|
+
`)),o}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},j=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];eventMetadataEnhancers=[];build(){return E.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers,this.eventMetadataEnhancers)}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}metadata(e){return this.eventMetadataEnhancers.push(e),this}};function C(r){return(e,t)=>r[e.eventName]?.(e,t)}var S=Symbol("__placeholder__");function L(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var N=class extends m{constructor(t=[],n=[]){super();this.db=t;this.producedEvents=n}apply={};name="test-recording-projector";reset(){this.db.splice(0)}project(t){this.producedEvents.push(t)}};function U(r,e=[]){let t=new N,n=E.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 a=n.build(),o,y={___:S,async given(s=[]){t.db.push(...s)},async when(s){try{return await a.dispatch(typeof s=="function"?s():s)}catch(i){return i instanceof Error&&(o=i),i}},async then(s){if(s instanceof Error){let u=s;L(()=>{if(o?.message!==u?.message)throw new Error(`Expected error message to be:
|
|
22
22
|
|
|
23
23
|
${u.message}
|
|
24
24
|
|
|
@@ -30,4 +30,4 @@ ${f(o)}
|
|
|
30
30
|
---
|
|
31
31
|
|
|
32
32
|
`].join(`
|
|
33
|
-
`)),o;L(()=>{if(i.length!==t.producedEvents.length)throw new Error(`Expected ${i.length} events, but got ${t.producedEvents.length} events.`);for(let[u,p]of i.entries()){let{aggregateId:$,eventName:
|
|
33
|
+
`)),o;L(()=>{if(i.length!==t.producedEvents.length)throw new Error(`Expected ${i.length} events, but got ${t.producedEvents.length} events.`);for(let[u,p]of i.entries()){let{aggregateId:$,eventName:O,payload:l}=t.producedEvents[u];if(p.aggregateId===S)throw new Error("Expected an `aggregateId`, but got `___` instead.");if(p.aggregateId!==$)throw new Error(`Expected aggregateId to be ${p.aggregateId}, but got ${$}.`);if(p.eventName!==O)throw new Error(`Expected eventName to be ${p.eventName}, but got ${O}.`);if((p.payload===null||p.payload===void 0)&&JSON.stringify(p.payload)!==JSON.stringify(l))throw new Error(`Expected payload to be ${JSON.stringify(p.payload)}, but got ${JSON.stringify(l)}.`);for(let d in p.payload){let w=p.payload[d];if(w===S){if(!(d in l))throw new Error(`Expected payload to have property ${d}, but it does not.`);if(l[d]===null||l[d]===void 0)throw new Error(`Expected payload to have property ${d}, but it is ${l[d]}.`)}else if(l[d]!==w)throw new Error(`Expected payload.${d} to be ${w}, but got ${l[d]}.`)}}},y.then)}};return y}0&&(module.exports={Aggregate,Command,Event,EventSource,Projector,abort,createEventMapper,createTestEventStore,objectToYaml});
|
package/dist/index.d.cts
CHANGED
|
@@ -9,18 +9,21 @@ interface EventType<T extends string = any, P = any, M = any> {
|
|
|
9
9
|
}
|
|
10
10
|
declare function Event<const T extends string, P = null, M = null>(eventName: T, aggregateId: string, payload?: P, metadata?: M): EventType<T, P, M>;
|
|
11
11
|
|
|
12
|
-
type
|
|
13
|
-
|
|
12
|
+
type Merge$1<A, B> = B extends Record<string, any> ? A extends Record<string, any> ? Omit<A, keyof B> & B : B : A;
|
|
13
|
+
type ApplyConcreteEvents<Events extends EventType, M = unknown> = Events extends EventType<infer EventName, any, any> ? {
|
|
14
|
+
[T in EventName]: (event: EventType<T, Extract<Events, {
|
|
14
15
|
eventName: T;
|
|
15
|
-
}>
|
|
16
|
+
}>['payload'], Merge$1<M, Extract<Events, {
|
|
17
|
+
eventName: T;
|
|
18
|
+
}>['metadata']>>) => void;
|
|
16
19
|
} : never;
|
|
17
20
|
type Lazy$1<T> = (...args: any[]) => T;
|
|
18
|
-
type ApplyLazyEvents<Events extends Lazy$1<EventType
|
|
21
|
+
type ApplyLazyEvents<Events extends Lazy$1<EventType>, M = unknown> = ApplyConcreteEvents<ReturnType<Events>, M>;
|
|
19
22
|
type MaybeLazy$1<T> = T | Lazy$1<T>;
|
|
20
|
-
type ApplyEvents<Events extends MaybeLazy$1<EventType> = any> = Events extends Lazy$1<EventType> ? ApplyLazyEvents<Events> : Events extends EventType ? ApplyConcreteEvents<Events> : never;
|
|
23
|
+
type ApplyEvents<Events extends MaybeLazy$1<EventType> = any, M = unknown> = Events extends Lazy$1<EventType> ? ApplyLazyEvents<Events, M> : Events extends EventType ? ApplyConcreteEvents<Events, M> : never;
|
|
21
24
|
declare abstract class Aggregate {
|
|
22
25
|
#private;
|
|
23
|
-
abstract apply:
|
|
26
|
+
abstract apply: Record<string, (event: any) => void>;
|
|
24
27
|
replayEvents(events?: EventType[]): this;
|
|
25
28
|
private applyAnEvent;
|
|
26
29
|
protected recordThat<T extends EventType>(event: T): this;
|
|
@@ -61,15 +64,18 @@ interface EventHandler {
|
|
|
61
64
|
interface MetadataEnhancer {
|
|
62
65
|
(): MaybePromise<JSON>;
|
|
63
66
|
}
|
|
64
|
-
type
|
|
65
|
-
|
|
67
|
+
type Merge<A, B> = B extends Record<string, any> ? A extends Record<string, any> ? Omit<A, keyof B> & B : B : A;
|
|
68
|
+
type ApplyConcreteProjectorEvents<Events extends EventType, M = unknown> = Events extends EventType<infer EventName, any, any> ? {
|
|
69
|
+
[T in EventName]: (event: EventType<T, Extract<Events, {
|
|
70
|
+
eventName: T;
|
|
71
|
+
}>['payload'], Merge<M, Extract<Events, {
|
|
66
72
|
eventName: T;
|
|
67
|
-
}>) => Promise<void
|
|
73
|
+
}>['metadata']>>) => Promise<void> | void;
|
|
68
74
|
} : never;
|
|
69
75
|
type Lazy<T> = (...args: any[]) => T;
|
|
70
|
-
type ApplyLazyProjectorEvents<Events extends Lazy<EventType
|
|
76
|
+
type ApplyLazyProjectorEvents<Events extends Lazy<EventType>, M = unknown> = ApplyConcreteProjectorEvents<ReturnType<Events>, M>;
|
|
71
77
|
type MaybeLazy<T> = T | Lazy<T>;
|
|
72
|
-
type ApplyProjectorEvents<Events extends MaybeLazy<EventType> = any> = Events extends Lazy<EventType> ? ApplyLazyProjectorEvents<Events> : Events extends EventType ? ApplyConcreteProjectorEvents<Events> : never;
|
|
78
|
+
type ApplyProjectorEvents<Events extends MaybeLazy<EventType> = any, M = unknown> = Events extends Lazy<EventType> ? ApplyLazyProjectorEvents<Events, M> : Events extends EventType ? ApplyConcreteProjectorEvents<Events, M> : never;
|
|
73
79
|
declare abstract class Projector<T extends ApplyProjectorEvents<any> = any> {
|
|
74
80
|
#private;
|
|
75
81
|
/**
|
|
@@ -81,12 +87,12 @@ declare abstract class Projector<T extends ApplyProjectorEvents<any> = any> {
|
|
|
81
87
|
*/
|
|
82
88
|
apply?: T;
|
|
83
89
|
/**
|
|
84
|
-
*
|
|
90
|
+
* Reset the projector state.
|
|
85
91
|
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
92
|
+
* Called before replaying all events during a full rebuild. Use this to
|
|
93
|
+
* clear any existing projection data (e.g., truncate tables).
|
|
88
94
|
*/
|
|
89
|
-
|
|
95
|
+
reset?(): void | Promise<void>;
|
|
90
96
|
init(events: EventType[]): Promise<void>;
|
|
91
97
|
applyEvent(event: EventType): Promise<void>;
|
|
92
98
|
project(event: EventType): void | Promise<void>;
|
package/dist/index.d.ts
CHANGED
|
@@ -9,18 +9,21 @@ interface EventType<T extends string = any, P = any, M = any> {
|
|
|
9
9
|
}
|
|
10
10
|
declare function Event<const T extends string, P = null, M = null>(eventName: T, aggregateId: string, payload?: P, metadata?: M): EventType<T, P, M>;
|
|
11
11
|
|
|
12
|
-
type
|
|
13
|
-
|
|
12
|
+
type Merge$1<A, B> = B extends Record<string, any> ? A extends Record<string, any> ? Omit<A, keyof B> & B : B : A;
|
|
13
|
+
type ApplyConcreteEvents<Events extends EventType, M = unknown> = Events extends EventType<infer EventName, any, any> ? {
|
|
14
|
+
[T in EventName]: (event: EventType<T, Extract<Events, {
|
|
14
15
|
eventName: T;
|
|
15
|
-
}>
|
|
16
|
+
}>['payload'], Merge$1<M, Extract<Events, {
|
|
17
|
+
eventName: T;
|
|
18
|
+
}>['metadata']>>) => void;
|
|
16
19
|
} : never;
|
|
17
20
|
type Lazy$1<T> = (...args: any[]) => T;
|
|
18
|
-
type ApplyLazyEvents<Events extends Lazy$1<EventType
|
|
21
|
+
type ApplyLazyEvents<Events extends Lazy$1<EventType>, M = unknown> = ApplyConcreteEvents<ReturnType<Events>, M>;
|
|
19
22
|
type MaybeLazy$1<T> = T | Lazy$1<T>;
|
|
20
|
-
type ApplyEvents<Events extends MaybeLazy$1<EventType> = any> = Events extends Lazy$1<EventType> ? ApplyLazyEvents<Events> : Events extends EventType ? ApplyConcreteEvents<Events> : never;
|
|
23
|
+
type ApplyEvents<Events extends MaybeLazy$1<EventType> = any, M = unknown> = Events extends Lazy$1<EventType> ? ApplyLazyEvents<Events, M> : Events extends EventType ? ApplyConcreteEvents<Events, M> : never;
|
|
21
24
|
declare abstract class Aggregate {
|
|
22
25
|
#private;
|
|
23
|
-
abstract apply:
|
|
26
|
+
abstract apply: Record<string, (event: any) => void>;
|
|
24
27
|
replayEvents(events?: EventType[]): this;
|
|
25
28
|
private applyAnEvent;
|
|
26
29
|
protected recordThat<T extends EventType>(event: T): this;
|
|
@@ -61,15 +64,18 @@ interface EventHandler {
|
|
|
61
64
|
interface MetadataEnhancer {
|
|
62
65
|
(): MaybePromise<JSON>;
|
|
63
66
|
}
|
|
64
|
-
type
|
|
65
|
-
|
|
67
|
+
type Merge<A, B> = B extends Record<string, any> ? A extends Record<string, any> ? Omit<A, keyof B> & B : B : A;
|
|
68
|
+
type ApplyConcreteProjectorEvents<Events extends EventType, M = unknown> = Events extends EventType<infer EventName, any, any> ? {
|
|
69
|
+
[T in EventName]: (event: EventType<T, Extract<Events, {
|
|
70
|
+
eventName: T;
|
|
71
|
+
}>['payload'], Merge<M, Extract<Events, {
|
|
66
72
|
eventName: T;
|
|
67
|
-
}>) => Promise<void
|
|
73
|
+
}>['metadata']>>) => Promise<void> | void;
|
|
68
74
|
} : never;
|
|
69
75
|
type Lazy<T> = (...args: any[]) => T;
|
|
70
|
-
type ApplyLazyProjectorEvents<Events extends Lazy<EventType
|
|
76
|
+
type ApplyLazyProjectorEvents<Events extends Lazy<EventType>, M = unknown> = ApplyConcreteProjectorEvents<ReturnType<Events>, M>;
|
|
71
77
|
type MaybeLazy<T> = T | Lazy<T>;
|
|
72
|
-
type ApplyProjectorEvents<Events extends MaybeLazy<EventType> = any> = Events extends Lazy<EventType> ? ApplyLazyProjectorEvents<Events> : Events extends EventType ? ApplyConcreteProjectorEvents<Events> : never;
|
|
78
|
+
type ApplyProjectorEvents<Events extends MaybeLazy<EventType> = any, M = unknown> = Events extends Lazy<EventType> ? ApplyLazyProjectorEvents<Events, M> : Events extends EventType ? ApplyConcreteProjectorEvents<Events, M> : never;
|
|
73
79
|
declare abstract class Projector<T extends ApplyProjectorEvents<any> = any> {
|
|
74
80
|
#private;
|
|
75
81
|
/**
|
|
@@ -81,12 +87,12 @@ declare abstract class Projector<T extends ApplyProjectorEvents<any> = any> {
|
|
|
81
87
|
*/
|
|
82
88
|
apply?: T;
|
|
83
89
|
/**
|
|
84
|
-
*
|
|
90
|
+
* Reset the projector state.
|
|
85
91
|
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
92
|
+
* Called before replaying all events during a full rebuild. Use this to
|
|
93
|
+
* clear any existing projection data (e.g., truncate tables).
|
|
88
94
|
*/
|
|
89
|
-
|
|
95
|
+
reset?(): void | Promise<void>;
|
|
90
96
|
init(events: EventType[]): Promise<void>;
|
|
91
97
|
applyEvent(event: EventType): Promise<void>;
|
|
92
98
|
project(event: EventType): void | Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
function
|
|
1
|
+
function b(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,b),t}function l(r,e){let t=b(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,l),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 H={NODE_ENV:typeof process<"u"?process.env?.NODE_ENV:void 0},$=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){H.NODE_ENV==="test"&&w(e);let t=this.apply[e.eventName];return t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?l(`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
|
-
}`):
|
|
8
|
+
}`):l(`Aggregate "${this.constructor.name}" has no method:
|
|
9
9
|
|
|
10
10
|
apply = {
|
|
11
11
|
['${e.eventName}'](event) {
|
|
12
12
|
// Code goes here...
|
|
13
13
|
}
|
|
14
14
|
// ...
|
|
15
|
-
}`)),t(e),this.#e++,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
|
|
15
|
+
}`)),t(e),this.#e++,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 Q(r,e=null){return{type:r,payload:e}}function V(r,e,t=null,n=null){return{aggregateId:e,eventId:globalThis.crypto.randomUUID(),eventName:r,payload:t,metadata:n,recordedAt:new Date,version:-1}}import k from"yamlify-object";var C={indent:" ",colors:{date:v,error:v,symbol:v,string:v,number:v,boolean:v,null:v,undefined:v}};function v(r){return r}function M(r){return r instanceof Error?M({...r}):k(r,C).split(`
|
|
16
16
|
`).slice(1).join(`
|
|
17
|
-
`)}var u=new WeakMap;function h(r,e){if(u.has(r)){let t=u.get(r);for(let n in e)t[n]=e[n]}else u.set(r,e)}function f(r){return u.get(r)}var T=class{constructor(){h(this,{jobs:[],state:0})}get length(){return f(this).jobs.length}async start(){let{state:e,jobs:t}=f(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}=f(this);o.push({handle:e,resolve:t,reject:n}),queueMicrotask(()=>this.start())})}};var g=class{apply;
|
|
17
|
+
`)}var u=new WeakMap;function h(r,e){if(u.has(r)){let t=u.get(r);for(let n in e)t[n]=e[n]}else u.set(r,e)}function f(r){return u.get(r)}var T=class{constructor(){h(this,{jobs:[],state:0})}get length(){return f(this).jobs.length}async start(){let{state:e,jobs:t}=f(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}=f(this);o.push({handle:e,resolve:t,reject:n}),queueMicrotask(()=>this.start())})}};var g=class{apply;reset(){}#e=new T;async init(e){this.reset&&await this.#e.push(()=>this.reset?.());for(let t of e)await this.applyEvent(t)}async applyEvent(e){await this.#e.push(()=>this.apply?.[e.eventName]?.(e)),await this.#e.push(()=>this.project(e))}project(e){}},E=class r{constructor(e,t,n,o,a){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=o;this.eventMetadataEnhancers=a}static builder(e){return new P(e)}static new(e,t,n,o,a){return new r(e,t,n,o,a)}async resetProjections(){let e=await this.store.loadEvents();await Promise.all(this.projectors.map(t=>t.init(e)))}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();if(this.eventMetadataEnhancers.length>0){let n={};for(let o of this.eventMetadataEnhancers)Object.assign(n,await o());for(let o of t){let a=o.metadata??{};o.metadata=Object.assign({},n,a)}}await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async o=>{try{await o.applyEvent(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(`
|
|
18
18
|
`).map(y=>` ${y}`).join(`
|
|
19
19
|
`)),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(`
|
|
20
20
|
`).map(y=>` ${y}`).join(`
|
|
21
|
-
`)),a}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},
|
|
21
|
+
`)),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=[];eventMetadataEnhancers=[];build(){return E.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers,this.eventMetadataEnhancers)}addCommandHandler(e,t){return this.commandHandlers.has(e)&&l(`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}metadata(e){return this.eventMetadataEnhancers.push(e),this}};function L(r){return(e,t)=>r[e.eventName]?.(e,t)}var A=Symbol("__placeholder__");function O(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var j=class extends g{constructor(t=[],n=[]){super();this.db=t;this.producedEvents=n}apply={};name="test-recording-projector";reset(){this.db.splice(0)}project(t){this.producedEvents.push(t)}};function oe(r,e=[]){let t=new j,n=E.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,y={___:A,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(s instanceof Error){let m=s;O(()=>{if(a?.message!==m?.message)throw new Error(`Expected error message to be:
|
|
22
22
|
|
|
23
23
|
${m.message}
|
|
24
24
|
|
|
25
25
|
But got:
|
|
26
26
|
|
|
27
27
|
${a?.message}`)},y.then);return}let i=s;if(a)throw Object.keys(a).length>0&&(a.message=["With properties:",`
|
|
28
|
-
${
|
|
28
|
+
${M(a)}
|
|
29
29
|
|
|
30
30
|
---
|
|
31
31
|
|
|
32
32
|
`].join(`
|
|
33
|
-
`)),a;
|
|
33
|
+
`)),a;O(()=>{if(i.length!==t.producedEvents.length)throw new Error(`Expected ${i.length} events, but got ${t.producedEvents.length} events.`);for(let[m,p]of i.entries()){let{aggregateId:S,eventName:N,payload:c}=t.producedEvents[m];if(p.aggregateId===A)throw new Error("Expected an `aggregateId`, but got `___` instead.");if(p.aggregateId!==S)throw new Error(`Expected aggregateId to be ${p.aggregateId}, but got ${S}.`);if(p.eventName!==N)throw new Error(`Expected eventName to be ${p.eventName}, but got ${N}.`);if((p.payload===null||p.payload===void 0)&&JSON.stringify(p.payload)!==JSON.stringify(c))throw new Error(`Expected payload to be ${JSON.stringify(p.payload)}, but got ${JSON.stringify(c)}.`);for(let d in p.payload){let x=p.payload[d];if(x===A){if(!(d in c))throw new Error(`Expected payload to have property ${d}, but it does not.`);if(c[d]===null||c[d]===void 0)throw new Error(`Expected payload to have property ${d}, but it is ${c[d]}.`)}else if(c[d]!==x)throw new Error(`Expected payload.${d} to be ${x}, but got ${c[d]}.`)}}},y.then)}};return y}export{$ as Aggregate,Q as Command,V as Event,E as EventSource,g as Projector,l as abort,L as createEventMapper,oe as createTestEventStore,M as objectToYaml};
|
package/package.json
CHANGED