@celljs/cqrs 0.0.0-stage → 4.4.0

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.
Files changed (160) hide show
  1. package/README.md +193 -2
  2. package/esm/node/aggregate/aggregate-root.d.ts +24 -0
  3. package/esm/node/aggregate/aggregate-root.js +69 -0
  4. package/esm/node/aggregate/aggregate-root.js.map +1 -0
  5. package/esm/node/aggregate/event-publisher.d.ts +16 -0
  6. package/esm/node/aggregate/event-publisher.js +42 -0
  7. package/esm/node/aggregate/event-publisher.js.map +1 -0
  8. package/esm/node/aggregate/index.d.ts +2 -0
  9. package/esm/node/aggregate/index.js +3 -0
  10. package/esm/node/aggregate/index.js.map +1 -0
  11. package/esm/node/command/command-bus.d.ts +11 -0
  12. package/esm/node/command/command-bus.js +36 -0
  13. package/esm/node/command/command-bus.js.map +1 -0
  14. package/esm/node/command/command-protocol.d.ts +30 -0
  15. package/esm/node/command/command-protocol.js +17 -0
  16. package/esm/node/command/command-protocol.js.map +1 -0
  17. package/esm/node/command/index.d.ts +2 -0
  18. package/esm/node/command/index.js +3 -0
  19. package/esm/node/command/index.js.map +1 -0
  20. package/esm/node/error/cqrs-error.d.ts +18 -0
  21. package/esm/node/error/cqrs-error.js +19 -0
  22. package/esm/node/error/cqrs-error.js.map +1 -0
  23. package/esm/node/error/index.d.ts +1 -0
  24. package/esm/node/error/index.js +2 -0
  25. package/esm/node/error/index.js.map +1 -0
  26. package/esm/node/event/event-bus.d.ts +17 -0
  27. package/esm/node/event/event-bus.js +81 -0
  28. package/esm/node/event/event-bus.js.map +1 -0
  29. package/esm/node/event/event-protocol.d.ts +42 -0
  30. package/esm/node/event/event-protocol.js +17 -0
  31. package/esm/node/event/event-protocol.js.map +1 -0
  32. package/esm/node/event/index.d.ts +3 -0
  33. package/esm/node/event/index.js +4 -0
  34. package/esm/node/event/index.js.map +1 -0
  35. package/esm/node/event/unhandled-exception-bus.d.ts +8 -0
  36. package/esm/node/event/unhandled-exception-bus.js +35 -0
  37. package/esm/node/event/unhandled-exception-bus.js.map +1 -0
  38. package/esm/node/index.d.ts +6 -0
  39. package/esm/node/index.js +7 -0
  40. package/esm/node/index.js.map +1 -0
  41. package/esm/node/module.d.ts +3 -0
  42. package/esm/node/module.js +4 -0
  43. package/esm/node/module.js.map +1 -0
  44. package/esm/node/query/index.d.ts +2 -0
  45. package/esm/node/query/index.js +3 -0
  46. package/esm/node/query/index.js.map +1 -0
  47. package/esm/node/query/query-bus.d.ts +11 -0
  48. package/esm/node/query/query-bus.js +36 -0
  49. package/esm/node/query/query-bus.js.map +1 -0
  50. package/esm/node/query/query-protocol.d.ts +31 -0
  51. package/esm/node/query/query-protocol.js +18 -0
  52. package/esm/node/query/query-protocol.js.map +1 -0
  53. package/esm/node/utils/cqrs-util.d.ts +25 -0
  54. package/esm/node/utils/cqrs-util.js +85 -0
  55. package/esm/node/utils/cqrs-util.js.map +1 -0
  56. package/esm/node/utils/index.d.ts +1 -0
  57. package/esm/node/utils/index.js +2 -0
  58. package/esm/node/utils/index.js.map +1 -0
  59. package/esm/package.json +3 -0
  60. package/lib/node/aggregate/aggregate-root.d.ts +25 -0
  61. package/lib/node/aggregate/aggregate-root.d.ts.map +1 -0
  62. package/lib/node/aggregate/aggregate-root.js +73 -0
  63. package/lib/node/aggregate/aggregate-root.js.map +1 -0
  64. package/lib/node/aggregate/event-publisher.d.ts +17 -0
  65. package/lib/node/aggregate/event-publisher.d.ts.map +1 -0
  66. package/lib/node/aggregate/event-publisher.js +45 -0
  67. package/lib/node/aggregate/event-publisher.js.map +1 -0
  68. package/lib/node/aggregate/index.d.ts +3 -0
  69. package/lib/node/aggregate/index.d.ts.map +1 -0
  70. package/lib/node/aggregate/index.js +19 -0
  71. package/lib/node/aggregate/index.js.map +1 -0
  72. package/lib/node/command/command-bus.d.ts +12 -0
  73. package/lib/node/command/command-bus.d.ts.map +1 -0
  74. package/lib/node/command/command-bus.js +39 -0
  75. package/lib/node/command/command-bus.js.map +1 -0
  76. package/lib/node/command/command-protocol.d.ts +31 -0
  77. package/lib/node/command/command-protocol.d.ts.map +1 -0
  78. package/lib/node/command/command-protocol.js +22 -0
  79. package/lib/node/command/command-protocol.js.map +1 -0
  80. package/lib/node/command/index.d.ts +3 -0
  81. package/lib/node/command/index.d.ts.map +1 -0
  82. package/lib/node/command/index.js +19 -0
  83. package/lib/node/command/index.js.map +1 -0
  84. package/lib/node/cqrs.spec.d.ts +76 -0
  85. package/lib/node/cqrs.spec.d.ts.map +1 -0
  86. package/lib/node/cqrs.spec.js +319 -0
  87. package/lib/node/cqrs.spec.js.map +1 -0
  88. package/lib/node/error/cqrs-error.d.ts +19 -0
  89. package/lib/node/error/cqrs-error.d.ts.map +1 -0
  90. package/lib/node/error/cqrs-error.js +23 -0
  91. package/lib/node/error/cqrs-error.js.map +1 -0
  92. package/lib/node/error/index.d.ts +2 -0
  93. package/lib/node/error/index.d.ts.map +1 -0
  94. package/lib/node/error/index.js +18 -0
  95. package/lib/node/error/index.js.map +1 -0
  96. package/lib/node/event/event-bus.d.ts +18 -0
  97. package/lib/node/event/event-bus.d.ts.map +1 -0
  98. package/lib/node/event/event-bus.js +84 -0
  99. package/lib/node/event/event-bus.js.map +1 -0
  100. package/lib/node/event/event-protocol.d.ts +43 -0
  101. package/lib/node/event/event-protocol.d.ts.map +1 -0
  102. package/lib/node/event/event-protocol.js +22 -0
  103. package/lib/node/event/event-protocol.js.map +1 -0
  104. package/lib/node/event/index.d.ts +4 -0
  105. package/lib/node/event/index.d.ts.map +1 -0
  106. package/lib/node/event/index.js +20 -0
  107. package/lib/node/event/index.js.map +1 -0
  108. package/lib/node/event/unhandled-exception-bus.d.ts +9 -0
  109. package/lib/node/event/unhandled-exception-bus.d.ts.map +1 -0
  110. package/lib/node/event/unhandled-exception-bus.js +38 -0
  111. package/lib/node/event/unhandled-exception-bus.js.map +1 -0
  112. package/lib/node/index.d.ts +7 -0
  113. package/lib/node/index.d.ts.map +1 -0
  114. package/lib/node/index.js +23 -0
  115. package/lib/node/index.js.map +1 -0
  116. package/lib/node/module.d.ts +4 -0
  117. package/lib/node/module.d.ts.map +1 -0
  118. package/lib/node/module.js +6 -0
  119. package/lib/node/module.js.map +1 -0
  120. package/lib/node/query/index.d.ts +3 -0
  121. package/lib/node/query/index.d.ts.map +1 -0
  122. package/lib/node/query/index.js +19 -0
  123. package/lib/node/query/index.js.map +1 -0
  124. package/lib/node/query/query-bus.d.ts +12 -0
  125. package/lib/node/query/query-bus.d.ts.map +1 -0
  126. package/lib/node/query/query-bus.js +39 -0
  127. package/lib/node/query/query-bus.js.map +1 -0
  128. package/lib/node/query/query-protocol.d.ts +32 -0
  129. package/lib/node/query/query-protocol.d.ts.map +1 -0
  130. package/lib/node/query/query-protocol.js +23 -0
  131. package/lib/node/query/query-protocol.js.map +1 -0
  132. package/lib/node/utils/cqrs-util.d.ts +26 -0
  133. package/lib/node/utils/cqrs-util.d.ts.map +1 -0
  134. package/lib/node/utils/cqrs-util.js +88 -0
  135. package/lib/node/utils/cqrs-util.js.map +1 -0
  136. package/lib/node/utils/index.d.ts +2 -0
  137. package/lib/node/utils/index.d.ts.map +1 -0
  138. package/lib/node/utils/index.js +18 -0
  139. package/lib/node/utils/index.js.map +1 -0
  140. package/package.json +88 -4
  141. package/src/node/aggregate/aggregate-root.ts +78 -0
  142. package/src/node/aggregate/event-publisher.ts +43 -0
  143. package/src/node/aggregate/index.ts +2 -0
  144. package/src/node/command/command-bus.ts +28 -0
  145. package/src/node/command/command-protocol.ts +39 -0
  146. package/src/node/command/index.ts +2 -0
  147. package/src/node/cqrs.spec.ts +316 -0
  148. package/src/node/error/cqrs-error.ts +23 -0
  149. package/src/node/error/index.ts +1 -0
  150. package/src/node/event/event-bus.ts +70 -0
  151. package/src/node/event/event-protocol.ts +60 -0
  152. package/src/node/event/index.ts +3 -0
  153. package/src/node/event/unhandled-exception-bus.ts +21 -0
  154. package/src/node/index.ts +6 -0
  155. package/src/node/module.ts +4 -0
  156. package/src/node/query/index.ts +2 -0
  157. package/src/node/query/query-bus.ts +28 -0
  158. package/src/node/query/query-protocol.ts +40 -0
  159. package/src/node/utils/cqrs-util.ts +90 -0
  160. package/src/node/utils/index.ts +1 -0
package/README.md CHANGED
@@ -1,3 +1,194 @@
1
- # Temporary Holding Version
1
+ # Cell - CQRS Component
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@celljs/cqrs` separates the code that changes state (commands) from the code that reads it (queries), and lets the rest of the application react to what happened (events), in the way of [`@nestjs/cqrs`](https://docs.nestjs.com/recipes/cqrs). Handlers are Cell components: they are found by their decorators, get injections like any other component, and are created when the first message of their kind is dispatched. No dependencies besides `@celljs/core`; backend only.
4
+
5
+ ```bash
6
+ npm install @celljs/cqrs
7
+ ```
8
+
9
+ ## Commands and queries
10
+
11
+ A command or query is an instance of a class; its class selects its one handler. Extend `CommandMessage<R>` / `QueryMessage<R>` to give `execute` the result type (optional: without it, `execute<R>()` takes the type).
12
+
13
+ ```ts
14
+ import { Autowired } from '@celljs/core';
15
+ import { Body, Controller, Get, Param, Post } from '@celljs/mvc/lib/node';
16
+ import { CommandBus, CommandHandler, CommandMessage, QueryBus, QueryHandler, QueryMessage } from '@celljs/cqrs';
17
+
18
+ export class CreateUser extends CommandMessage<string> {
19
+ constructor(readonly name: string) {
20
+ super();
21
+ }
22
+ }
23
+
24
+ export class GetUser extends QueryMessage<User | undefined> {
25
+ constructor(readonly id: string) {
26
+ super();
27
+ }
28
+ }
29
+
30
+ @CommandHandler(CreateUser)
31
+ export class CreateUserHandler implements CommandHandler<CreateUser> {
32
+ @Autowired(UserRepository)
33
+ protected readonly users: UserRepository;
34
+
35
+ execute(command: CreateUser): Promise<string> {
36
+ return this.users.insert(command.name);
37
+ }
38
+ }
39
+
40
+ @QueryHandler(GetUser)
41
+ export class GetUserHandler implements QueryHandler<GetUser> {
42
+ @Autowired(UserRepository)
43
+ protected readonly users: UserRepository;
44
+
45
+ execute(query: GetUser): Promise<User | undefined> {
46
+ return this.users.findById(query.id);
47
+ }
48
+ }
49
+
50
+ @Controller('users')
51
+ export class UserController {
52
+ @Autowired(CommandBus)
53
+ protected readonly commandBus: CommandBus;
54
+
55
+ @Autowired(QueryBus)
56
+ protected readonly queryBus: QueryBus;
57
+
58
+ @Post()
59
+ create(@Body() body: { name: string }): Promise<string> {
60
+ return this.commandBus.execute(new CreateUser(body.name));
61
+ }
62
+
63
+ @Get(':id')
64
+ get(@Param('id') id: string): Promise<User | undefined> {
65
+ return this.queryBus.execute(new GetUser(id));
66
+ }
67
+ }
68
+ ```
69
+
70
+ `execute` resolves to what the handler returns and rejects with what it throws. The decorators take the options of `@Component` as second argument (`scope`, `proxy` for AOP...).
71
+
72
+ ## Events and sagas
73
+
74
+ An event class can have any number of `@EventHandler`s and `@Saga`s. A saga turns an event into the commands that follow from it: the event bus runs what it returns (a command, an array of commands or nothing) with the command bus, in order.
75
+
76
+ ```ts
77
+ import { EventBus, EventHandler, Saga } from '@celljs/cqrs';
78
+
79
+ export class UserCreated {
80
+ constructor(readonly id: string, readonly name: string) { }
81
+ }
82
+
83
+ @EventHandler(UserCreated) // or @EventHandler([UserCreated, UserRenamed])
84
+ export class UserProjection implements EventHandler<UserCreated> {
85
+ async handle(event: UserCreated): Promise<void> { ... }
86
+ }
87
+
88
+ @Saga(UserCreated)
89
+ export class WelcomeSaga implements Saga<UserCreated> {
90
+ handle(event: UserCreated): SendWelcomeMail {
91
+ return new SendWelcomeMail(event.id);
92
+ }
93
+ }
94
+
95
+ await eventBus.publish(new UserCreated(id, name));
96
+ ```
97
+
98
+ `publish(event)` runs the handlers and sagas of the event concurrently and resolves when they are all done, so a serverless function does not return before them; `publishAll(events)` publishes one event after the other. What a handler or saga throws does not reject `publish` nor stop the other handlers: it is logged and handed to the `UnhandledExceptionBus`:
99
+
100
+ ```ts
101
+ @Component(ApplicationLifecycle)
102
+ export class CqrsAlerts implements ApplicationLifecycle<Application> {
103
+ @Autowired(UnhandledExceptionBus)
104
+ protected readonly exceptions: UnhandledExceptionBus;
105
+
106
+ initialize(): void {
107
+ this.exceptions.onException(({ error, event, handler }) => { ... });
108
+ }
109
+ }
110
+ ```
111
+
112
+ ## Aggregates
113
+
114
+ An `AggregateRoot` records its changes as events: `apply(event)` records the event and calls the method `on<EventClassName>` of the aggregate, if there is one, to change the state; `commit()` publishes the recorded events with the event bus. Connect the aggregate to the event bus with `EventPublisher` first.
115
+
116
+ ```ts
117
+ import { AggregateRoot, EventPublisher } from '@celljs/cqrs';
118
+
119
+ export class User extends AggregateRoot {
120
+ name: string;
121
+
122
+ constructor(readonly id: string) {
123
+ super();
124
+ }
125
+
126
+ rename(name: string): void {
127
+ this.apply(new UserRenamed(this.id, name));
128
+ }
129
+
130
+ onUserRenamed(event: UserRenamed): void {
131
+ this.name = event.name;
132
+ }
133
+ }
134
+
135
+ @CommandHandler(RenameUser)
136
+ export class RenameUserHandler implements CommandHandler<RenameUser> {
137
+ @Autowired(EventPublisher)
138
+ protected readonly publisher: EventPublisher;
139
+
140
+ @Autowired(UserRepository)
141
+ protected readonly users: UserRepository;
142
+
143
+ async execute(command: RenameUser): Promise<void> {
144
+ const user = this.publisher.mergeObjectContext(await this.users.load(command.id));
145
+ user.rename(command.name);
146
+ await this.users.save(user);
147
+ await user.commit();
148
+ }
149
+ }
150
+ ```
151
+
152
+ - `loadFromHistory(events)` rebuilds the state from stored events without recording them again.
153
+ - `getUncommittedEvents()` returns the recorded events; `uncommit()` forgets them.
154
+ - `eventPublisher.mergeClassContext(User)` returns a subclass whose instances are connected when created.
155
+ - The recorded events are not properties of the aggregate: `JSON.stringify(user)` gives its state only.
156
+
157
+ ## Errors
158
+
159
+ The buses and `commit()` reject with a `CqrsError` whose `code` is stable and whose `hint` says how to fix it:
160
+
161
+ | Code | When |
162
+ | --- | --- |
163
+ | `CELL_CQRS_NO_HANDLER` | No `@CommandHandler` / `@QueryHandler` for the class of the command or query |
164
+ | `CELL_CQRS_DUPLICATE_HANDLER` | Two handlers for one command or query class |
165
+ | `CELL_CQRS_NOT_AN_INSTANCE` | The message is a plain object, `null` or a primitive instead of an instance of a class |
166
+ | `CELL_CQRS_AGGREGATE_NOT_MERGED` | `commit()` on an aggregate that `EventPublisher` did not connect; the events stay recorded |
167
+
168
+ ## Customizing
169
+
170
+ `CommandBus`, `QueryBus`, `EventBus`, `EventPublisher` and `UnhandledExceptionBus` are components: replace one with `rebind: true`, for example to also send the events to a message broker:
171
+
172
+ ```ts
173
+ @Component({ id: EventBus, rebind: true })
174
+ export class BrokerEventBus extends EventBusImpl {
175
+ override async publish(event: object): Promise<void> {
176
+ await super.publish(event);
177
+ await this.broker.send(event);
178
+ }
179
+ }
180
+ ```
181
+
182
+ ## Coming from @nestjs/cqrs
183
+
184
+ | @nestjs/cqrs | @celljs/cqrs |
185
+ | --- | --- |
186
+ | `CqrsModule.forRoot()` | Add the dependency; the module is loaded with the backend |
187
+ | `ICommandHandler`, `IQueryHandler`, `IEventHandler` | `CommandHandler`, `QueryHandler`, `EventHandler`: one name for the decorator and the interface |
188
+ | `@EventsHandler(A, B)` | `@EventHandler([A, B])` |
189
+ | `Command<R>`, `Query<R>` | `CommandMessage<R>`, `QueryMessage<R>` (`@celljs/mvc` has a `@Query` decorator) |
190
+ | `@Saga()` with RxJS streams | `@Saga(Event)` class whose `handle(event)` returns the commands; no RxJS |
191
+ | `eventBus.publish()` returns at once | `await eventBus.publish()` waits for the handlers and sagas |
192
+ | `aggregate.commit()` | `await aggregate.commit()`; rejects when the aggregate is not connected instead of doing nothing |
193
+ | `autoCommit` | Not supported: call `commit()` |
194
+ | `UnhandledExceptionBus` (RxJS subject) | `UnhandledExceptionBus.onException` (a Cell `Event`) |
@@ -0,0 +1,24 @@
1
+ import { CqrsError } from '../error/index.js';
2
+ /**
3
+ * An entity whose changes are events: `apply(event)` records the event and calls the method `on<EventClassName>`
4
+ * of the aggregate, if there is one, to change its state; `commit()` publishes the recorded events.
5
+ * Before `commit()`, connect the aggregate to the event bus with `EventPublisher.mergeObjectContext`
6
+ * (or create it from a class given by `EventPublisher.mergeClassContext`).
7
+ */
8
+ export declare abstract class AggregateRoot<E extends object = object> {
9
+ /** Records the event, unless it is replayed from history, and applies it to the state with `on<EventClassName>`. */
10
+ apply(event: E, fromHistory?: boolean): void;
11
+ /** Publishes the recorded events, in order, and forgets them. */
12
+ commit(): Promise<void>;
13
+ /** Forgets the recorded events without publishing them. */
14
+ uncommit(): void;
15
+ getUncommittedEvents(): E[];
16
+ /** Rebuilds the state from past events; they are not recorded again. */
17
+ loadFromHistory(history: E[]): void;
18
+ /** Replaced by `EventPublisher`, which publishes with the `EventBus`. */
19
+ publish(event: E): Promise<void>;
20
+ /** Replaced by `EventPublisher`, which publishes with the `EventBus`. */
21
+ publishAll(events: E[]): Promise<void>;
22
+ protected getEventHandler(event: E): ((event: E) => void) | undefined;
23
+ protected notMerged(events: E[]): CqrsError;
24
+ }
@@ -0,0 +1,69 @@
1
+ import { CqrsError } from '../error/index.js';
2
+ const uncommitted = new WeakMap();
3
+ function eventsOf(aggregate) {
4
+ let events = uncommitted.get(aggregate);
5
+ if (!events) {
6
+ events = [];
7
+ uncommitted.set(aggregate, events);
8
+ }
9
+ return events;
10
+ }
11
+ /**
12
+ * An entity whose changes are events: `apply(event)` records the event and calls the method `on<EventClassName>`
13
+ * of the aggregate, if there is one, to change its state; `commit()` publishes the recorded events.
14
+ * Before `commit()`, connect the aggregate to the event bus with `EventPublisher.mergeObjectContext`
15
+ * (or create it from a class given by `EventPublisher.mergeClassContext`).
16
+ */
17
+ export class AggregateRoot {
18
+ /** Records the event, unless it is replayed from history, and applies it to the state with `on<EventClassName>`. */
19
+ apply(event, fromHistory = false) {
20
+ var _a;
21
+ if (!fromHistory) {
22
+ eventsOf(this).push(event);
23
+ }
24
+ (_a = this.getEventHandler(event)) === null || _a === void 0 ? void 0 : _a.call(this, event);
25
+ }
26
+ /** Publishes the recorded events, in order, and forgets them. */
27
+ async commit() {
28
+ const events = eventsOf(this);
29
+ if (events.length === 0) {
30
+ return;
31
+ }
32
+ const committing = events.slice();
33
+ await this.publishAll(committing);
34
+ events.splice(0, committing.length);
35
+ }
36
+ /** Forgets the recorded events without publishing them. */
37
+ uncommit() {
38
+ eventsOf(this).length = 0;
39
+ }
40
+ getUncommittedEvents() {
41
+ return eventsOf(this).slice();
42
+ }
43
+ /** Rebuilds the state from past events; they are not recorded again. */
44
+ loadFromHistory(history) {
45
+ for (const event of history) {
46
+ this.apply(event, true);
47
+ }
48
+ }
49
+ /** Replaced by `EventPublisher`, which publishes with the `EventBus`. */
50
+ publish(event) {
51
+ return this.publishAll([event]);
52
+ }
53
+ /** Replaced by `EventPublisher`, which publishes with the `EventBus`. */
54
+ publishAll(events) {
55
+ return Promise.reject(this.notMerged(events));
56
+ }
57
+ getEventHandler(event) {
58
+ const handler = this[`on${event.constructor.name}`];
59
+ return typeof handler === 'function' ? handler : undefined;
60
+ }
61
+ notMerged(events) {
62
+ return new CqrsError({
63
+ code: 'CELL_CQRS_AGGREGATE_NOT_MERGED',
64
+ message: `${this.constructor.name} cannot publish ${events.map(e => e.constructor.name).join(', ')}: it is not connected to the event bus.`,
65
+ hint: 'Inject EventPublisher and pass the aggregate to eventPublisher.mergeObjectContext(aggregate) before commit().',
66
+ });
67
+ }
68
+ }
69
+ //# sourceMappingURL=aggregate-root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate-root.js","sourceRoot":"","sources":["../../../src/node/aggregate/aggregate-root.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,MAAM,WAAW,GAAG,IAAI,OAAO,EAAgC,CAAC;AAEhE,SAAS,QAAQ,CAAC,SAA6B;IAC3C,IAAI,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,IAAI,CAAC,MAAM,EAAE,CAAC;QACV,MAAM,GAAG,EAAE,CAAC;QACZ,WAAW,CAAC,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAgB,aAAa;IAC/B,oHAAoH;IACpH,KAAK,CAAC,KAAQ,EAAE,WAAW,GAAG,KAAK;;QAC/B,IAAI,CAAC,WAAW,EAAE,CAAC;YACf,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,MAAA,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,0CAAE,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACnD,CAAC;IAED,iEAAiE;IACjE,KAAK,CAAC,MAAM;QACR,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO;QACX,CAAC;QACD,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,EAAS,CAAC;QACzC,MAAM,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAClC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC;IACxC,CAAC;IAED,2DAA2D;IAC3D,QAAQ;QACJ,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9B,CAAC;IAED,oBAAoB;QAChB,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,EAAS,CAAC;IACzC,CAAC;IAED,wEAAwE;IACxE,eAAe,CAAC,OAAY;QACxB,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAC5B,CAAC;IACL,CAAC;IAED,yEAAyE;IACzE,OAAO,CAAC,KAAQ;QACZ,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IACpC,CAAC;IAED,yEAAyE;IACzE,UAAU,CAAC,MAAW;QAClB,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAClD,CAAC;IAES,eAAe,CAAC,KAAQ;QAC9B,MAAM,OAAO,GAAI,IAAY,CAAC,KAAK,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC;QAC7D,OAAO,OAAO,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;IAC/D,CAAC;IAES,SAAS,CAAC,MAAW;QAC3B,OAAO,IAAI,SAAS,CAAC;YACjB,IAAI,EAAE,gCAAgC;YACtC,OAAO,EAAE,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,mBAAmB,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,yCAAyC;YAC3I,IAAI,EAAE,+GAA+G;SACxH,CAAC,CAAC;IACP,CAAC;CACJ"}
@@ -0,0 +1,16 @@
1
+ import { EventBus } from '../event/event-protocol.js';
2
+ import type { AggregateRoot } from './aggregate-root.js';
3
+ export declare const EventPublisher: unique symbol;
4
+ export type AggregateClass<T extends AggregateRoot<any>> = new (...args: any[]) => T;
5
+ /** Connects aggregates to the `EventBus`, so that their `commit()` publishes their events. */
6
+ export interface EventPublisher {
7
+ /** Connects the aggregate and returns it. */
8
+ mergeObjectContext<T extends AggregateRoot<any>>(aggregate: T): T;
9
+ /** A subclass of the aggregate class whose instances are connected. */
10
+ mergeClassContext<T extends AggregateClass<AggregateRoot<any>>>(type: T): T;
11
+ }
12
+ export declare class EventPublisherImpl implements EventPublisher {
13
+ protected readonly eventBus: EventBus;
14
+ mergeObjectContext<T extends AggregateRoot<any>>(aggregate: T): T;
15
+ mergeClassContext<T extends AggregateClass<AggregateRoot<any>>>(type: T): T;
16
+ }
@@ -0,0 +1,42 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Autowired, Component } from '@celljs/core';
11
+ import { EventBus } from '../event/event-protocol.js';
12
+ export const EventPublisher = Symbol('EventPublisher');
13
+ let EventPublisherImpl = class EventPublisherImpl {
14
+ mergeObjectContext(aggregate) {
15
+ const eventBus = this.eventBus;
16
+ aggregate.publish = event => eventBus.publish(event);
17
+ aggregate.publishAll = events => eventBus.publishAll(events);
18
+ return aggregate;
19
+ }
20
+ mergeClassContext(type) {
21
+ const eventBus = this.eventBus;
22
+ const merged = class extends type {
23
+ publish(event) {
24
+ return eventBus.publish(event);
25
+ }
26
+ publishAll(events) {
27
+ return eventBus.publishAll(events);
28
+ }
29
+ };
30
+ Object.defineProperty(merged, 'name', { value: type.name });
31
+ return merged;
32
+ }
33
+ };
34
+ __decorate([
35
+ Autowired(EventBus),
36
+ __metadata("design:type", Object)
37
+ ], EventPublisherImpl.prototype, "eventBus", void 0);
38
+ EventPublisherImpl = __decorate([
39
+ Component(EventPublisher)
40
+ ], EventPublisherImpl);
41
+ export { EventPublisherImpl };
42
+ //# sourceMappingURL=event-publisher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-publisher.js","sourceRoot":"","sources":["../../../src/node/aggregate/event-publisher.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAGnD,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAahD,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAI3B,kBAAkB,CAA+B,SAAY;QACzD,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,SAAS,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACrD,SAAS,CAAC,UAAU,GAAG,MAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QAC7D,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,iBAAiB,CAA+C,IAAO;QACnE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,MAAM,GAAG,KAAM,SAAQ,IAAI;YACpB,OAAO,CAAC,KAAa;gBAC1B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACnC,CAAC;YAEQ,UAAU,CAAC,MAAgB;gBAChC,OAAO,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YACvC,CAAC;SACJ,CAAC;QACF,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAC5D,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ,CAAA;AAvBsB;IADlB,SAAS,CAAC,QAAQ,CAAC;;oDACkB;AAF7B,kBAAkB;IAD9B,SAAS,CAAC,cAAc,CAAC;GACb,kBAAkB,CAyB9B"}
@@ -0,0 +1,2 @@
1
+ export * from './aggregate-root.js';
2
+ export * from './event-publisher.js';
@@ -0,0 +1,3 @@
1
+ export * from './aggregate-root.js';
2
+ export * from './event-publisher.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/node/aggregate/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { type Provider } from '@celljs/core';
2
+ import { type MessageType } from '../utils/index.js';
3
+ import { CommandBus, type CommandHandler, type CommandMessage } from './command-protocol.js';
4
+ export declare class CommandBusImpl implements CommandBus {
5
+ /** A provider: the handlers are created when the first command runs, so they can inject the buses. */
6
+ protected readonly handlerProvider: Provider<CommandHandler>;
7
+ protected handlers?: Map<MessageType, CommandHandler>;
8
+ execute<R>(command: CommandMessage<R>): Promise<R>;
9
+ execute<R = any>(command: object): Promise<R>;
10
+ protected getHandler(command: object): CommandHandler;
11
+ }
@@ -0,0 +1,36 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { AutowiredProvider, Component } from '@celljs/core';
11
+ import { CqrsUtil, METADATA_KEY } from '../utils/index.js';
12
+ import { COMMAND_HANDLER, CommandBus } from './command-protocol.js';
13
+ let CommandBusImpl = class CommandBusImpl {
14
+ async execute(command) {
15
+ return this.getHandler(command).execute(command);
16
+ }
17
+ getHandler(command) {
18
+ var _a;
19
+ const type = CqrsUtil.typeOf(command, 'command');
20
+ (_a = this.handlers) !== null && _a !== void 0 ? _a : (this.handlers = CqrsUtil.single(this.handlerProvider.get(), METADATA_KEY.commandHandler, 'command'));
21
+ const handler = this.handlers.get(type);
22
+ if (!handler) {
23
+ throw CqrsUtil.noHandler(type, 'command');
24
+ }
25
+ return handler;
26
+ }
27
+ };
28
+ __decorate([
29
+ AutowiredProvider(COMMAND_HANDLER),
30
+ __metadata("design:type", Object)
31
+ ], CommandBusImpl.prototype, "handlerProvider", void 0);
32
+ CommandBusImpl = __decorate([
33
+ Component(CommandBus)
34
+ ], CommandBusImpl);
35
+ export { CommandBusImpl };
36
+ //# sourceMappingURL=command-bus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-bus.js","sourceRoot":"","sources":["../../../src/node/command/command-bus.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAiB,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAoB,MAAM,UAAU,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,UAAU,EAA4C,MAAM,oBAAoB,CAAC;AAGpG,IAAM,cAAc,GAApB,MAAM,cAAc;IASvB,KAAK,CAAC,OAAO,CAAC,OAAe;QACzB,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC;IAES,UAAU,CAAC,OAAe;;QAChC,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QACjD,MAAA,IAAI,CAAC,QAAQ,oCAAb,IAAI,CAAC,QAAQ,GAAK,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,EAAE,YAAY,CAAC,cAAc,EAAE,SAAS,CAAC,EAAC;QACtG,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxC,IAAI,CAAC,OAAO,EAAE,CAAC;YACX,MAAM,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,OAAO,CAAC;IACnB,CAAC;CACJ,CAAA;AAnBsB;IADlB,iBAAiB,CAAC,eAAe,CAAC;;uDAC0B;AAHpD,cAAc;IAD1B,SAAS,CAAC,UAAU,CAAC;GACT,cAAc,CAsB1B"}
@@ -0,0 +1,30 @@
1
+ import type { ComponentOption, MaybePromise, Newable } from '@celljs/core';
2
+ export declare const CommandBus: unique symbol;
3
+ export declare const COMMAND_HANDLER: unique symbol;
4
+ /**
5
+ * Optional base class of a command that gives `CommandBus.execute` its result type:
6
+ * `class CreateUser extends CommandMessage<string> { ... }` makes `execute(new CreateUser(...))` a `Promise<string>`.
7
+ */
8
+ export declare abstract class CommandMessage<R = void> {
9
+ /** Carries the result type only; never set. */
10
+ readonly __result: R;
11
+ }
12
+ export type CommandResult<C> = C extends CommandMessage<infer R> ? R : any;
13
+ /** Changes the state of the application; the one handler of a command class is selected by the class of the command. */
14
+ export interface CommandHandler<C extends object = any, R = CommandResult<C>> {
15
+ execute(command: C): MaybePromise<R>;
16
+ }
17
+ /**
18
+ * Makes the class a component that handles the commands of the given class.
19
+ * Each command class has exactly one handler.
20
+ */
21
+ export declare function CommandHandler(command: Newable<object>, option?: ComponentOption): ClassDecorator;
22
+ /** Runs a command with its handler. */
23
+ export interface CommandBus {
24
+ /**
25
+ * Runs the handler of the command and resolves to what it returns.
26
+ * Rejects with what the handler throws, or a `CqrsError` when no handler handles the command.
27
+ */
28
+ execute<R>(command: CommandMessage<R>): Promise<R>;
29
+ execute<R = any>(command: object): Promise<R>;
30
+ }
@@ -0,0 +1,17 @@
1
+ import { CqrsUtil, METADATA_KEY } from '../utils/index.js';
2
+ export const CommandBus = Symbol('CommandBus');
3
+ export const COMMAND_HANDLER = Symbol('CommandHandler');
4
+ /**
5
+ * Optional base class of a command that gives `CommandBus.execute` its result type:
6
+ * `class CreateUser extends CommandMessage<string> { ... }` makes `execute(new CreateUser(...))` a `Promise<string>`.
7
+ */
8
+ export class CommandMessage {
9
+ }
10
+ /**
11
+ * Makes the class a component that handles the commands of the given class.
12
+ * Each command class has exactly one handler.
13
+ */
14
+ export function CommandHandler(command, option) {
15
+ return target => CqrsUtil.applyHandlerDecorator(target, COMMAND_HANDLER, METADATA_KEY.commandHandler, [command], option);
16
+ }
17
+ //# sourceMappingURL=command-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-protocol.js","sourceRoot":"","sources":["../../../src/node/command/command-protocol.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAElD,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,OAAgB,cAAc;CAGnC;AASD;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,OAAwB,EAAE,MAAwB;IAC7E,OAAO,MAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,qBAAqB,CAAC,MAAM,EAAE,eAAe,EAAE,YAAY,CAAC,cAAc,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC;AAC7H,CAAC"}
@@ -0,0 +1,2 @@
1
+ export * from './command-bus.js';
2
+ export * from './command-protocol.js';
@@ -0,0 +1,3 @@
1
+ export * from './command-bus.js';
2
+ export * from './command-protocol.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/node/command/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * A command, query or event that cannot be dispatched. `code` is stable and `hint` says how to fix it
3
+ * in one sentence (docs/design/agent-first.md R5).
4
+ */
5
+ export declare class CqrsError extends Error {
6
+ readonly name = "CqrsError";
7
+ readonly code: CqrsError.Code;
8
+ readonly hint: string;
9
+ constructor(options: {
10
+ code: CqrsError.Code;
11
+ message: string;
12
+ hint: string;
13
+ });
14
+ }
15
+ export declare namespace CqrsError {
16
+ type Code = 'CELL_CQRS_NOT_AN_INSTANCE' | 'CELL_CQRS_NO_HANDLER' | 'CELL_CQRS_DUPLICATE_HANDLER' | 'CELL_CQRS_AGGREGATE_NOT_MERGED';
17
+ function is(error: unknown, code?: Code): error is CqrsError;
18
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A command, query or event that cannot be dispatched. `code` is stable and `hint` says how to fix it
3
+ * in one sentence (docs/design/agent-first.md R5).
4
+ */
5
+ export class CqrsError extends Error {
6
+ constructor(options) {
7
+ super(options.message);
8
+ this.name = 'CqrsError';
9
+ this.code = options.code;
10
+ this.hint = options.hint;
11
+ }
12
+ }
13
+ (function (CqrsError) {
14
+ function is(error, code) {
15
+ return error instanceof CqrsError && (code === undefined || error.code === code);
16
+ }
17
+ CqrsError.is = is;
18
+ })(CqrsError || (CqrsError = {}));
19
+ //# sourceMappingURL=cqrs-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cqrs-error.js","sourceRoot":"","sources":["../../../src/node/error/cqrs-error.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAKhC,YAAY,OAAgE;QACxE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QALT,SAAI,GAAG,WAAW,CAAC;QAMjC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAC7B,CAAC;CACJ;AAED,WAAiB,SAAS;IAGtB,SAAgB,EAAE,CAAC,KAAc,EAAE,IAAW;QAC1C,OAAO,KAAK,YAAY,SAAS,IAAI,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;IACrF,CAAC;IAFe,UAAA,EAAE,KAEjB,CAAA;AACL,CAAC,EANgB,SAAS,KAAT,SAAS,QAMzB"}
@@ -0,0 +1 @@
1
+ export * from './cqrs-error.js';
@@ -0,0 +1,2 @@
1
+ export * from './cqrs-error.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/node/error/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { type Provider } from '@celljs/core';
2
+ import { CommandBus } from '../command/command-protocol.js';
3
+ import { type MessageType } from '../utils/index.js';
4
+ import { EventBus, type EventHandler, type Saga, UnhandledExceptionBus } from './event-protocol.js';
5
+ export declare class EventBusImpl implements EventBus {
6
+ /** Providers: the handlers and sagas are created when the first event is published, so they can inject the buses. */
7
+ protected readonly handlerProvider: Provider<EventHandler>;
8
+ protected readonly sagaProvider: Provider<Saga>;
9
+ protected readonly commandBus: CommandBus;
10
+ protected readonly unhandledExceptionBus: UnhandledExceptionBus;
11
+ protected handlers?: Map<MessageType, EventHandler[]>;
12
+ protected sagas?: Map<MessageType, Saga[]>;
13
+ publish(event: object): Promise<void>;
14
+ publishAll(events: object[]): Promise<void>;
15
+ protected handle(handler: EventHandler, event: object): Promise<void>;
16
+ protected runSaga(saga: Saga, event: object): Promise<void>;
17
+ }
@@ -0,0 +1,81 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Autowired, AutowiredProvider, Component } from '@celljs/core';
11
+ import { CommandBus } from '../command/command-protocol.js';
12
+ import { CqrsUtil, METADATA_KEY } from '../utils/index.js';
13
+ import { EVENT_HANDLER, EventBus, SAGA, UnhandledExceptionBus } from './event-protocol.js';
14
+ const NONE = [];
15
+ let EventBusImpl = class EventBusImpl {
16
+ async publish(event) {
17
+ var _a, _b, _c, _d;
18
+ const type = CqrsUtil.typeOf(event, 'event');
19
+ (_a = this.handlers) !== null && _a !== void 0 ? _a : (this.handlers = CqrsUtil.index(this.handlerProvider.get(), METADATA_KEY.eventHandler));
20
+ (_b = this.sagas) !== null && _b !== void 0 ? _b : (this.sagas = CqrsUtil.index(this.sagaProvider.get(), METADATA_KEY.saga));
21
+ const handlers = (_c = this.handlers.get(type)) !== null && _c !== void 0 ? _c : NONE;
22
+ const sagas = (_d = this.sagas.get(type)) !== null && _d !== void 0 ? _d : NONE;
23
+ if (handlers.length === 1 && sagas.length === 0) {
24
+ return this.handle(handlers[0], event);
25
+ }
26
+ const tasks = [];
27
+ for (const handler of handlers) {
28
+ tasks.push(this.handle(handler, event));
29
+ }
30
+ for (const saga of sagas) {
31
+ tasks.push(this.runSaga(saga, event));
32
+ }
33
+ await Promise.all(tasks);
34
+ }
35
+ async publishAll(events) {
36
+ for (const event of events) {
37
+ await this.publish(event);
38
+ }
39
+ }
40
+ async handle(handler, event) {
41
+ try {
42
+ await handler.handle(event);
43
+ }
44
+ catch (error) {
45
+ this.unhandledExceptionBus.publish({ error, event, handler });
46
+ }
47
+ }
48
+ async runSaga(saga, event) {
49
+ try {
50
+ const result = await saga.handle(event);
51
+ const commands = result === undefined || result === null ? NONE : Array.isArray(result) ? result : [result];
52
+ for (const command of commands) {
53
+ await this.commandBus.execute(command);
54
+ }
55
+ }
56
+ catch (error) {
57
+ this.unhandledExceptionBus.publish({ error, event, handler: saga });
58
+ }
59
+ }
60
+ };
61
+ __decorate([
62
+ AutowiredProvider(EVENT_HANDLER),
63
+ __metadata("design:type", Object)
64
+ ], EventBusImpl.prototype, "handlerProvider", void 0);
65
+ __decorate([
66
+ AutowiredProvider(SAGA),
67
+ __metadata("design:type", Object)
68
+ ], EventBusImpl.prototype, "sagaProvider", void 0);
69
+ __decorate([
70
+ Autowired(CommandBus),
71
+ __metadata("design:type", Object)
72
+ ], EventBusImpl.prototype, "commandBus", void 0);
73
+ __decorate([
74
+ Autowired(UnhandledExceptionBus),
75
+ __metadata("design:type", Object)
76
+ ], EventBusImpl.prototype, "unhandledExceptionBus", void 0);
77
+ EventBusImpl = __decorate([
78
+ Component(EventBus)
79
+ ], EventBusImpl);
80
+ export { EventBusImpl };
81
+ //# sourceMappingURL=event-bus.js.map