@sincpro/client-framework 1.3.0 → 1.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.
package/AGENTS.md CHANGED
@@ -89,17 +89,29 @@ module has only the layers it needs, and says what it offers in its own `index.t
89
89
  dependency typed — the backend's `class Feature(_Feature, DependencyContextType)` —; a service
90
90
  never declares one. A scaffold writes `dependencies.ts` and `framework.ts`; the instance lives in
91
91
  `framework.ts` because ES modules run their imports first.
92
- - **How events are carried is here; where they are kept is the platform's.** One use case of an
93
- event per bounded context; the queue's one `Subscriber` executes an event in each. `storedQueue` holds the rules — store first, deliver in order,
94
- retry what may succeed, set aside what never will, never run one who heard it twice — over an
95
- `EventStore` the platform plugs (SQLite, IndexedDB, memory). A store only keeps records; it
96
- never decides.
97
- - **The Subscriber is the queue's only entrypoint.** It hears a list of events or every event its
98
- bounded contexts registered, recognizes a message (an event by name, a Command by identity),
99
- rebuilds and executes it — as the backend's `Subscriber(*buses)` / `QueueGateway`. Nobody
100
- writes a subscriber per event: registering a use case for the event is the subscription. A
101
- Command from a queue runs only when declared (`commands`), in the one bus that registered it;
102
- `CommandNotConsumed` otherwise. Two bounded contexts never share a name.
92
+ - **How events are carried is here; where they are kept is the platform's.** An event's
93
+ consumers are acknowledged apart: a bounded context's use case for it (one per bounded context,
94
+ keyed by its name), its event handlers and a subscriber's (`<owner>/<Handler>`). `storedQueue`
95
+ holds the rules — store first, deliver in order, retry what may succeed, set aside what never
96
+ will, never run one consumer twice — over an `EventStore` the platform plugs (SQLite,
97
+ IndexedDB, memory). A store only keeps records; it never decides.
98
+ - **The Subscriber is the queue's entrypoint, and it is composite.** One per queue — never one
99
+ per handler —, created once like a bounded context (`new Subscriber<D>("app")`,
100
+ `handlersWith<D>()`). It pulls what the queue delivers, rebuilds it (an event by name, a Command
101
+ by identity) and hands it to every consumer subscribed to it: its own event handlers, and the
102
+ buses added to it — each with its use case for the event and its own handlers. Two levels, never
103
+ mixed: `addDependency("x", value)` is what its handlers find on `this` (a bus they call is a
104
+ dependency); `addBus(bus)` — no name, the bus's namespace — is a bus it delivers to. The same
105
+ bus added again changes nothing; another bus of the same name is delivered to as well
106
+ (`sales#2`). A Command from a queue runs only when declared (`commands`), in the one bus that
107
+ registered it; `CommandNotConsumed` otherwise.
108
+ - **An event has three kinds of consumers, one API.** Its use case on a bus
109
+ (`@bus.feature([CommandX, Event])`, the event is its input); an event handler of a bus
110
+ (`@bus.handler([EventA, EventB])`, a layer above its use cases: the bus's dependencies and
111
+ `this.boundedContext`); an event handler of a subscriber (`@subscriber.handler([...])`, its
112
+ explicit dependencies). A handler decides nothing — it executes Commands —; it runs in the
113
+ pipeline of a use case, in its own layer (`event_handler`), and is registered with or without a
114
+ decorator.
103
115
  - **Messages are the backend's: CloudEvents 1.0.** One shape for Commands and events — `type` is
104
116
  the event's name or the Command's identity —; the route differs (N buses, or the one that
105
117
  registered it, when declared). `readMessage` reads structured and binary mode (`ce_` headers),
@@ -213,5 +225,6 @@ make test
213
225
  make build
214
226
  ```
215
227
 
216
- Never bump `version` in `package.json` — the release pipeline does. Never commit; a person
217
- does.
228
+ Never bump `version` in `package.json` — the release pipeline does. Commit on a working branch,
229
+ never on `main`: a change reaches `main` through a pull request, and further changes of the same
230
+ work go into that one pull request.
package/MANIFESTO.md CHANGED
@@ -75,7 +75,8 @@ server-side render, in a script and in a test, unchanged.**
75
75
  subscribes to them the same way: the envelope that travels beside an event (its flow and
76
76
  its cause), how a Command and an event are written and read (each its own way), the
77
77
  `EventQueue` and `Subscribes` ports, a `Publisher` a Feature holds, the `Subscriber` — the
78
- queue's only entrypoint: events heard, Commands consumed only when declared —, the queue that
78
+ queue's composite entrypoint: its event handlers and the buses added to it, Commands
79
+ consumed only when declared —, the queue that
79
80
  delivers in the call, and the stored queue's rules over an `EventStore` the platform plugs.
80
81
  The guidelines, the rules and the contracts are here; where events are kept is the
81
82
  platform's.
package/README.md CHANGED
@@ -187,8 +187,10 @@ await projectBoundedContext.execute(commandOf(operations.CommandArchiveIssue, {
187
187
 
188
188
  ## Domain events
189
189
 
190
- Registering a use case for an event **is** the subscription — the backend's
191
- `@accounting.feature(InvoiceIssued)`. Several bounded contexts may register it; each hears it once.
190
+ An event reaches a use case registered for it — the backend's `@accounting.feature(InvoiceIssued)`,
191
+ when the event is that use case's input — or an event handler, the entrypoint that translates it
192
+ into Commands (see the Subscriber below). Several bounded contexts may register it; each consumer
193
+ gets it once.
192
194
 
193
195
  ```ts
194
196
  @accountingBoundedContext.feature(InvoiceIssued)
@@ -202,31 +204,70 @@ A use case of an event runs through the same pipeline (span `<context>/<Service>
202
204
  `sincpro.event`, log lines, error handlers, report). An ApplicationService may take the event and
203
205
  compose Features; `execute(event)` answers whatever its use case returns (`unknown`).
204
206
 
205
- ### The Subscriber: the queue's only entrypoint
207
+ ### The Subscriber: the queue's entrypoint, composite
206
208
 
207
- One per queue — the backend's `Subscriber(*buses)` and `QueueGateway`. What arrives is
208
- recognized (an event by its name, a Command by its identity), rebuilt and executed on the bus
209
- that registered it. Nobody writes a subscriber per event.
209
+ One per queue — the backend's `Subscriber(*buses)` and `QueueGateway`, never one per handler.
210
+ It pulls what the queue delivers, rebuilds it (an event by its name, a Command by its identity)
211
+ and hands it to every consumer subscribed to it. An event has three kinds of consumers, all
212
+ registered the same way, with or without a decorator:
210
213
 
211
- ```ts
212
- new Subscriber(accountingBoundedContext, billingBoundedContext); // every event they registered
214
+ | Consumer | Registered with | It finds on `this` | Acknowledged as |
215
+ | -------------------------------- | -------------------------------------------- | ------------------------------------------------ | --------------------- |
216
+ | a use case of a bus | `@salesBoundedContext.feature([Cmd, Evt])` | the bus's dependencies | `sales` |
217
+ | an event handler of a bus | `@salesBoundedContext.handler([EvtA, EvtB])` | the bus's dependencies and `this.boundedContext` | `sales/OnSaleChanged` |
218
+ | an event handler of a subscriber | `@appSubscriber.handler([EvtA])` | the subscriber's dependencies | `app/NotifySalePaid` |
213
219
 
214
- new Subscriber({
215
- boundedContexts: [accountingBoundedContext, billingBoundedContext],
216
- events: [InvoiceIssued, events.IssueClosed], // only these
220
+ ```ts
221
+ // entrypoints/queue/framework.ts — once, like a bounded context's framework.ts
222
+ export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
223
+ export const appSubscriber = new Subscriber<AppSubscriberDependencies>("app", {
217
224
  commands: [CommandIssueInvoice], // consumed from the queue: only when declared
218
225
  });
226
+ appSubscriber.addDependency("invoicingBoundedContext", invoicingBoundedContext); // to call it
227
+ appSubscriber.addDependency("notifier", notifier);
228
+ appSubscriber.addBus(salesBoundedContext); // to deliver to its use cases and handlers
229
+
230
+ // entrypoints/queue/sale_paid.handler.ts — events → handler; it decides nothing
231
+ @appSubscriber.handler([SalePaid, SaleCancelled])
232
+ export class NotifySaleChanged extends EventHandler<SalePaid | SaleCancelled> {
233
+ async handle(event: SalePaid | SaleCancelled) {
234
+ await this.invoicingBoundedContext.execute(new CommandIssueInvoice(event.saleId));
235
+ }
236
+ }
237
+ appSubscriber.handler([InvoiceVoided])(OnInvoiceVoided); // the same, without a decorator
238
+
239
+ // entrypoints/queue/sale_paid.handler.ts of the sales context — a handler of the bus, an entrypoint
240
+ export const { Feature, ApplicationService, EventHandler } =
241
+ servicesWith<SalesDependencies>();
242
+ @salesBoundedContext.handler([SalePaid])
243
+ export class OnSalePaid extends EventHandler<SalePaid> {
244
+ async handle(event: SalePaid) {
245
+ await this.boundedContext.execute(new CommandCloseSale(event.saleId)); // its own bus
246
+ }
247
+ }
219
248
 
220
- await subscriber.receive(message); // CloudEvents, structured or { headers, body }: what each answered
249
+ const queue = storedQueue({ store, subscriber: appSubscriber });
250
+ await appSubscriber.receive(message); // CloudEvents, structured or { headers, body }
221
251
  ```
222
252
 
223
- - **An event** is handed to every bounded context that registered it, in the order named; one
224
- that fails does not stop the others, and each is said under its name — which a stored queue
225
- keeps, so a redelivery never runs one again. Two bounded contexts never share a name.
253
+ - **Two levels, never mixed.** `addDependency("x", value)` is what its handlers find on `this` —
254
+ a bus they call is a dependency like any other —; `addBus(bus)`, with no name to write (the
255
+ bus's own namespace), is a bus it delivers to. The same bus added again changes nothing;
256
+ another bus of the same name is delivered to as well, under its own key (`sales#2`).
257
+ - **An event** reaches every consumer subscribed to it — the subscriber's handlers, then each bus
258
+ in the order added (its use case, then its handlers); one that fails does not stop the others,
259
+ and each is acknowledged under its key — which a stored queue keeps, so a redelivery runs only
260
+ the ones that do not have it yet.
261
+ - **A handler** runs in the pipeline of a use case, in its own layer (`event_handler`): its span
262
+ `<owner>/<Handler>`, `this.logger`, `this.execution.causationId` (the message's id), and what it
263
+ executes is its child. A handler takes N events: its type is their union, and TypeScript checks
264
+ it accepts every event listed.
226
265
  - **A Command** is executed by the one bounded context that registered it, continuing the
227
266
  message's flow — **only when declared** (`commands`). A bus never hands all its Commands to
228
267
  whoever can publish on a queue: an undeclared one fails `CommandNotConsumed`
229
268
  (`permission_denied`).
269
+ - `new Subscriber(...boundedContexts)` and `new Subscriber({ boundedContexts, events, commands })`
270
+ still build one that delivers to those buses only.
230
271
 
231
272
  ### Publishing
232
273
 
@@ -256,7 +297,7 @@ What is defined here, and what each platform plugs behind the ports:
256
297
  | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
257
298
  | `EventQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
258
299
  | `EventStore` port | `memoryEventStore()` | mobile: a SQLite table; web: IndexedDB |
259
- | `Subscriber` | recognize, rebuild, execute; events heard, Commands declared | where messages come from (a socket) |
300
+ | `Subscriber` | pull, rebuild, deliver to every consumer; Commands declared | where messages come from (a socket) |
260
301
 
261
302
  ### Stored events: one way to carry them, any store
262
303
 
@@ -701,7 +742,8 @@ bus runs the use cases, the use cases use the adapters:
701
742
 
702
743
  ```text
703
744
  src/
704
- entrypoints/main.ts(x) configureProcess, the stored queue and its Subscriber
745
+ entrypoints/main.ts(x) configureProcess, the stored queue
746
+ entrypoints/queue/ the Subscriber (framework.ts) and its event handlers
705
747
  domains/
706
748
  common/infrastructure/operations.ts export const operations — the wire every client uses
707
749
  <bounded context>/
@@ -719,6 +761,7 @@ src/
719
761
  dependencies.ts <Context>Dependencies and registerDependencies
720
762
  framework.ts servicesWith<…>() bases, and <context>BoundedContext
721
763
  entrypoints/ the doors: they translate, they decide nothing
764
+ queue/ the bus's event handlers: event → Command → bus
722
765
  cron/ mobile only — its scheduler: tick → Command → bus
723
766
  index.ts <context>BoundedContext, ready to execute
724
767
  ```
@@ -776,7 +819,7 @@ src/
776
819
  Subscribes and EventStore ports
777
820
  services/ writing and reading messages
778
821
  adapters/ syncQueue, storedQueue, memoryEventStore
779
- entrypoint/ Publisher, Subscriber (the queue's only entrypoint)
822
+ entrypoint/ Publisher, Subscriber (the queue's composite entrypoint)
780
823
  codegen/ the generator and its CLI — the only place Node is allowed
781
824
  testing/ memoryTracer, memoryReporter, memoryLogger
782
825
  ```
@@ -0,0 +1,19 @@
1
+ import type { DomainEvent, EventClass, EventDescriptor, RemoteEvent } from "./dto.js";
2
+ import type { Cause } from "./pipeline.js";
3
+ /** What an event handler is registered for: an event's class, or a generated event's entry. */
4
+ export type EventKey = EventClass<DomainEvent> | EventDescriptor;
5
+ /**
6
+ * One consumer of an event — what a `Subscriber` delivers it to and acknowledges apart: the use
7
+ * case a bounded context registered for it, or an event handler.
8
+ *
9
+ * sales the use case of the bounded context "sales"
10
+ * sales/OnSalePaid an event handler of that bounded context
11
+ * app/NotifySalePaid an event handler of the subscriber "app"
12
+ *
13
+ * Context: the key is what a stored queue keeps of who already has a message (`reached`), so a
14
+ * redelivery never runs one again; it is stable across restarts because it is made of names.
15
+ */
16
+ export type EventConsumer = {
17
+ readonly key: string;
18
+ consume(event: DomainEvent | RemoteEvent, cause?: Cause): Promise<unknown>;
19
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -20,7 +20,8 @@ import type { Outcome } from "../../observability/domain/tracing.js";
20
20
  * the error handlers like any other. A listener that fails is ignored: hearing never changes
21
21
  * the answer.
22
22
  */
23
- export type PipelineLayer = "feature" | "application_service";
23
+ /** Where a run sits: a Feature, an ApplicationService, or an event handler above them. */
24
+ export type PipelineLayer = "feature" | "application_service" | "event_handler";
24
25
  /** What caused a run from outside: an event delivered with its envelope continues its chain. */
25
26
  export type Cause = {
26
27
  /** The id of what caused it — a delivered message's. */
@@ -1,6 +1,6 @@
1
1
  import type { Execution } from "../../context/domain/execution.js";
2
2
  import type { ContextValues } from "../../context/domain/store.js";
3
- import type { FeatureBus } from "./bus.js";
3
+ import type { CommandBus, FeatureBus } from "./bus.js";
4
4
  import type { Command, DomainEvent, RemoteCommand, RemoteEvent } from "./dto.js";
5
5
  import type { LayerLogger } from "../../observability/domain/logging.js";
6
6
  import type { Span } from "../../observability/domain/tracing.js";
@@ -20,7 +20,8 @@ export type ServiceInput<R> = Command<R> | DomainEvent | RemoteEvent | RemoteCom
20
20
  * }
21
21
  *
22
22
  * Context: while a method runs, `this.context`, `this.span`, `this.logger`, `this.featureBus` and
23
- * every dependency are that run's (`executeService`). Its name — its use case in spans and
23
+ * every dependency are that run's (`executeService`). An event's use case is one way to handle it;
24
+ * an `EventHandler`, a layer above, is the other. Its name — its use case in spans and
24
25
  * logs — is the framework's to take when it is registered: nothing on the class declares it.
25
26
  */
26
27
  export declare abstract class Feature<C extends ServiceInput<R>, R, Context extends object = ContextValues> {
@@ -43,6 +44,50 @@ export declare abstract class ApplicationService<C extends ServiceInput<R>, R, C
43
44
  /** The context's Features, run as children of this execution. */
44
45
  protected readonly featureBus: FeatureBus;
45
46
  }
47
+ /** What an event handler handles: a domain event, or a generated one's data. */
48
+ export type HandledEvent = DomainEvent | RemoteEvent;
49
+ /**
50
+ * An event handler: the entrypoint an event reaches — it decides nothing, it executes Commands
51
+ * on the buses it reaches —, registered for one event or N, on a bounded context or on a
52
+ * `Subscriber`:
53
+ *
54
+ * @salesBoundedContext.handler([SalePaid, SaleCancelled])
55
+ * export class OnSaleChanged extends EventHandler<SalePaid | SaleCancelled> {
56
+ * async handle(event: SalePaid | SaleCancelled) {
57
+ * await this.boundedContext.execute(new CommandCloseSale(event.saleId));
58
+ * }
59
+ * }
60
+ *
61
+ * Context: a handler runs in the same pipeline as a Feature — its span
62
+ * (`<owner>/<Handler>`), `this.logger`, `this.execution` (its `causationId` is the message's id)
63
+ * and `this.signal` —, a layer above the use cases (`event_handler`). On a bounded context it
64
+ * finds that context's dependencies and the context itself (`this.boundedContext`), bound to the
65
+ * run; on a `Subscriber`, the dependencies the subscriber was given. Its name is its class's,
66
+ * taken at registration.
67
+ */
68
+ export declare abstract class EventHandler<E extends HandledEvent, Context extends object = ContextValues> {
69
+ /** What this run reads: the process's context, and its bounded context's when it has one. */
70
+ readonly context: Readonly<Partial<Context>>;
71
+ /** This run's span. */
72
+ readonly span: Span;
73
+ /** This run's logger: every line carries its handler, execution and trace. */
74
+ readonly logger: LayerLogger;
75
+ /** What cancels this run, when it has one. */
76
+ readonly signal: AbortSignal | undefined;
77
+ /** This run: its `causationId` is the id of the message it handles. */
78
+ readonly execution: Execution;
79
+ abstract handle(event: E): void | Promise<void>;
80
+ }
81
+ /** An event handler base of a `Subscriber`: every dependency of `D` on `this`, typed. */
82
+ export type EventHandlerWith<D extends object, Context extends object = ContextValues> = abstract new <E extends HandledEvent>() => EventHandler<E, Context> & Readonly<D>;
83
+ /**
84
+ * An event handler base of a bounded context: its dependencies, and the context itself
85
+ * (`this.boundedContext`) — its Features and ApplicationServices, executed as children of the
86
+ * handler's run.
87
+ */
88
+ export type BoundedContextHandlerWith<D extends object, Context extends object = ContextValues> = abstract new <E extends HandledEvent>() => EventHandler<E, Context> & Readonly<D> & {
89
+ readonly boundedContext: CommandBus;
90
+ };
46
91
  /** A Feature base whose instances find every dependency of `D` on `this`, typed. */
47
92
  export type FeatureWith<D extends object, Context extends object = ContextValues> = abstract new <C extends ServiceInput<R>, R>() => Feature<C, R, Context> & Readonly<D>;
48
93
  /** An ApplicationService base whose instances find every dependency of `D` on `this`, typed. */
@@ -69,6 +114,18 @@ export type ApplicationServiceWith<D extends object, Context extends object = Co
69
114
  export declare function servicesWith<D extends object, Context extends object = ContextValues>(): {
70
115
  Feature: FeatureWith<D, Context>;
71
116
  ApplicationService: ApplicationServiceWith<D, Context>;
117
+ EventHandler: BoundedContextHandlerWith<D, Context>;
118
+ };
119
+ /**
120
+ * The event handler base of a `Subscriber`, typed with what it was given (`addDependency`):
121
+ *
122
+ * // entrypoints/queue/framework.ts
123
+ * export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
124
+ *
125
+ * The same class, typed — no other runtime behaviour.
126
+ */
127
+ export declare function handlersWith<D extends object, Context extends object = ContextValues>(): {
128
+ EventHandler: EventHandlerWith<D, Context>;
72
129
  };
73
130
  /** @internal — what a run finds on `this` that no dependency may take. */
74
131
  export declare const RESERVED_MEMBERS: ReadonlySet<string>;
@@ -12,13 +12,35 @@
12
12
  * }
13
13
  *
14
14
  * Context: while a method runs, `this.context`, `this.span`, `this.logger`, `this.featureBus` and
15
- * every dependency are that run's (`executeService`). Its name — its use case in spans and
15
+ * every dependency are that run's (`executeService`). An event's use case is one way to handle it;
16
+ * an `EventHandler`, a layer above, is the other. Its name — its use case in spans and
16
17
  * logs — is the framework's to take when it is registered: nothing on the class declares it.
17
18
  */
18
19
  export class Feature {
19
20
  }
20
21
  export class ApplicationService extends Feature {
21
22
  }
23
+ /**
24
+ * An event handler: the entrypoint an event reaches — it decides nothing, it executes Commands
25
+ * on the buses it reaches —, registered for one event or N, on a bounded context or on a
26
+ * `Subscriber`:
27
+ *
28
+ * @salesBoundedContext.handler([SalePaid, SaleCancelled])
29
+ * export class OnSaleChanged extends EventHandler<SalePaid | SaleCancelled> {
30
+ * async handle(event: SalePaid | SaleCancelled) {
31
+ * await this.boundedContext.execute(new CommandCloseSale(event.saleId));
32
+ * }
33
+ * }
34
+ *
35
+ * Context: a handler runs in the same pipeline as a Feature — its span
36
+ * (`<owner>/<Handler>`), `this.logger`, `this.execution` (its `causationId` is the message's id)
37
+ * and `this.signal` —, a layer above the use cases (`event_handler`). On a bounded context it
38
+ * finds that context's dependencies and the context itself (`this.boundedContext`), bound to the
39
+ * run; on a `Subscriber`, the dependencies the subscriber was given. Its name is its class's,
40
+ * taken at registration.
41
+ */
42
+ export class EventHandler {
43
+ }
22
44
  /**
23
45
  * The Feature and ApplicationService of a bounded context, typed with its dependencies — the
24
46
  * backend's `class Feature(_Feature, DependencyContextType)`, in its `infrastructure/framework.py`:
@@ -42,11 +64,24 @@ export function servicesWith() {
42
64
  return {
43
65
  Feature: Feature,
44
66
  ApplicationService: ApplicationService,
67
+ EventHandler: EventHandler,
45
68
  };
46
69
  }
70
+ /**
71
+ * The event handler base of a `Subscriber`, typed with what it was given (`addDependency`):
72
+ *
73
+ * // entrypoints/queue/framework.ts
74
+ * export const { EventHandler } = handlersWith<AppSubscriberDependencies>();
75
+ *
76
+ * The same class, typed — no other runtime behaviour.
77
+ */
78
+ export function handlersWith() {
79
+ return { EventHandler: EventHandler };
80
+ }
47
81
  /** @internal — what a run finds on `this` that no dependency may take. */
48
82
  export const RESERVED_MEMBERS = new Set([
49
83
  "featureBus",
84
+ "boundedContext",
50
85
  "context",
51
86
  "span",
52
87
  "logger",
@@ -2,9 +2,12 @@ import { BIND, type Execution } from "../../context/domain/execution.js";
2
2
  import type { ContextValues } from "../../context/domain/store.js";
3
3
  import { type Context } from "../../context/entrypoint/context.js";
4
4
  import { type CommandBus } from "../domain/bus.js";
5
+ import type { EventConsumer, EventKey } from "../domain/consumers.js";
5
6
  import { type Answer, type AnyCommand, type Command, type CommandClass, type CommandDescriptor, type DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable, type ExecutableOf, type RemoteCommand, type RemoteEvent, type ResponseClass } from "../domain/dto.js";
6
7
  import type { ErrorClass, ErrorHandler } from "../domain/errors.js";
7
8
  import type { Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, Interceptor, Listener } from "../domain/pipeline.js";
9
+ import { type HandledEvent } from "../domain/services.js";
10
+ import { type HandlerRegistrar } from "../services/event-handlers.js";
8
11
  import type { LayerLogger } from "../../observability/domain/logging.js";
9
12
  interface Executor<C extends Executable, R> {
10
13
  execute(executable: C): R | Promise<R>;
@@ -47,6 +50,7 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
47
50
  /** Its own logger, named after it: for what it does outside a use case. */
48
51
  readonly logger: LayerLogger;
49
52
  private readonly registrations;
53
+ private readonly eventHandlers;
50
54
  private readonly dependencyValues;
51
55
  private readonly handlers;
52
56
  private readonly expected;
@@ -80,6 +84,23 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
80
84
  appService<E extends DomainEvent>(event: EventClass<E>, options?: RegistrationOptions): Registrar<E>;
81
85
  appService<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
82
86
  appService<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: RegistrationOptions): Registrar<E>;
87
+ /**
88
+ * Registers an event handler of this bounded context for one event or N — the layer above its
89
+ * use cases: it finds this context's dependencies and the context itself
90
+ * (`this.boundedContext`), whose Features and ApplicationServices it executes as children of
91
+ * its run. As a decorator, or called with the class:
92
+ *
93
+ * @salesBoundedContext.handler([SalePaid, SaleCancelled])
94
+ * export class OnSaleChanged extends EventHandler<SalePaid | SaleCancelled> { … }
95
+ *
96
+ * salesBoundedContext.handler([SalePaid, SaleCancelled])(OnSaleChanged);
97
+ *
98
+ * An event may have its use case and N handlers here; each is its own consumer
99
+ * (`sales/OnSaleChanged`), acknowledged apart by the queue.
100
+ */
101
+ handler<const K extends readonly EventKey[]>(events: K): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
102
+ handler<E extends DomainEvent>(event: EventClass<E>): HandlerRegistrar<E>;
103
+ handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor): HandlerRegistrar<E>;
83
104
  /** The service registered now for a DTO — what a `replaces` names. */
84
105
  handlerOf(dto: DtoKey): (abstract new (...args: never[]) => object) | undefined;
85
106
  /**
@@ -88,6 +109,11 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
88
109
  * `event_type(name)`.
89
110
  */
90
111
  eventTypeOf(name: string): EventClass<DomainEvent> | EventDescriptor | undefined;
112
+ /**
113
+ * @internal — who consumes `event` here, for the `Subscriber` that delivers it: its use case
114
+ * (keyed by this context's name) and each of its event handlers (`<context>/<Handler>`).
115
+ */
116
+ consumersOf(event: DomainEvent | RemoteEvent): readonly EventConsumer[];
91
117
  /**
92
118
  * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
93
119
  * the generated entry it was registered with —, or `undefined` when nothing here executes it.
@@ -163,6 +189,12 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
163
189
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
164
190
  */
165
191
  private registerService;
192
+ /**
193
+ * 1. A class registered once, for the events listed: register it for N in one call.
194
+ * 2. Its name is no other handler's or service's here: both are said `<context>/<Name>`.
195
+ * Final: registered; the next delivery reaches it.
196
+ */
197
+ private registerHandler;
166
198
  private generation;
167
199
  private buildGeneration;
168
200
  }
@@ -5,8 +5,10 @@ import { FeatureBus, optionsOf, } from "../domain/bus.js";
5
5
  import { EVENT_NAME, } from "../domain/dto.js";
6
6
  import { ApplicationService, Feature, RESERVED_MEMBERS, } from "../domain/services.js";
7
7
  import { processHearing } from "../infrastructure/listeners.js";
8
+ import { bindDependency } from "../services/binding.js";
8
9
  import { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
9
10
  import { handled } from "../services/error-handlers.js";
11
+ import { eventKeysOf, handlerRegistrar, handles, runHandler, } from "../services/event-handlers.js";
10
12
  import { executeService, failedAt } from "../services/execution.js";
11
13
  import { announceTo, concerns, listenIn, } from "../services/listening.js";
12
14
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
@@ -50,6 +52,7 @@ export class BoundedContext {
50
52
  /** Its own logger, named after it: for what it does outside a use case. */
51
53
  logger;
52
54
  registrations = new Map();
55
+ eventHandlers = [];
53
56
  dependencyValues = new Map();
54
57
  handlers = {
55
58
  global: [],
@@ -118,6 +121,10 @@ export class BoundedContext {
118
121
  appService(dto, options) {
119
122
  return this.registrar(dto, "application_service", options);
120
123
  }
124
+ handler(events) {
125
+ const keys = eventKeysOf(events);
126
+ return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys));
127
+ }
121
128
  /** The service registered now for a DTO — what a `replaces` names. */
122
129
  handlerOf(dto) {
123
130
  return this.registrations.get(dto)?.Service;
@@ -133,8 +140,21 @@ export class BoundedContext {
133
140
  if (known.kind === "event" && known.wire === name)
134
141
  return dto;
135
142
  }
143
+ for (const registration of this.eventHandlers) {
144
+ for (const key of registration.events) {
145
+ if (keyIdentity(key).wire === name)
146
+ return key;
147
+ }
148
+ }
136
149
  return undefined;
137
150
  }
151
+ /**
152
+ * @internal — who consumes `event` here, for the `Subscriber` that delivers it: its use case
153
+ * (keyed by this context's name) and each of its event handlers (`<context>/<Handler>`).
154
+ */
155
+ consumersOf(event) {
156
+ return this.generation().consumersOf(event);
157
+ }
138
158
  /**
139
159
  * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
140
160
  * the generated entry it was registered with —, or `undefined` when nothing here executes it.
@@ -261,6 +281,7 @@ export class BoundedContext {
261
281
  for (const [name, dependency] of this.dependencyValues) {
262
282
  fresh.dependencyValues.set(name, dependency);
263
283
  }
284
+ fresh.eventHandlers.push(...this.eventHandlers);
264
285
  for (const where of ["global", "feature", "application_service"]) {
265
286
  fresh.handlers[where].push(...this.handlers[where]);
266
287
  }
@@ -384,6 +405,9 @@ export class BoundedContext {
384
405
  if (typeof name !== "string" || name.trim() === "") {
385
406
  throw new Error("A service is a named class: its name is its use case in spans and logs");
386
407
  }
408
+ if (this.eventHandlers.some((one) => one.name === name)) {
409
+ throw new Error(`Service name already registered: ${name}`);
410
+ }
387
411
  for (const [other, registration] of this.registrations) {
388
412
  if (registration !== current &&
389
413
  registration.Service !== Service &&
@@ -407,6 +431,22 @@ export class BoundedContext {
407
431
  });
408
432
  this.revision++;
409
433
  }
434
+ /**
435
+ * 1. A class registered once, for the events listed: register it for N in one call.
436
+ * 2. Its name is no other handler's or service's here: both are said `<context>/<Name>`.
437
+ * Final: registered; the next delivery reaches it.
438
+ */
439
+ registerHandler(Handler, name, events) {
440
+ if (this.eventHandlers.some((one) => one.Handler === Handler)) {
441
+ throw new Error(`Event handler already registered: ${name} — list all its events once`);
442
+ }
443
+ const taken = this.eventHandlers.some((one) => one.name === name) ||
444
+ [...this.registrations.values()].some((one) => one.name === name);
445
+ if (taken)
446
+ throw new Error(`Service name already registered: ${name}`);
447
+ this.eventHandlers.push({ name, Handler, events });
448
+ this.revision++;
449
+ }
410
450
  generation() {
411
451
  if (this.built && this.builtRevision === this.revision)
412
452
  return this.built;
@@ -499,27 +539,72 @@ export class BoundedContext {
499
539
  announce,
500
540
  });
501
541
  };
502
- return {
503
- root: async (executable, scope, options) => {
504
- try {
505
- return await dispatch(executable, undefined, false, scope, options);
506
- }
507
- catch (error) {
508
- let escaping = error;
509
- if (handlers.global.length > 0) {
510
- try {
511
- const answer = await handled(handlers.global, error);
512
- logHandled("bounded_context", { boundedContext: this.name });
513
- return answer;
514
- }
515
- catch (thrown) {
516
- escaping = thrown;
517
- }
542
+ const root = async (executable, scope, options) => {
543
+ try {
544
+ return await dispatch(executable, undefined, false, scope, options);
545
+ }
546
+ catch (error) {
547
+ let escaping = error;
548
+ if (handlers.global.length > 0) {
549
+ try {
550
+ const answer = await handled(handlers.global, error);
551
+ logHandled("bounded_context", { boundedContext: this.name });
552
+ return answer;
553
+ }
554
+ catch (thrown) {
555
+ escaping = thrown;
518
556
  }
519
- this.escaped(executable, escaping, expected);
520
- throw escaping;
521
557
  }
522
- },
558
+ this.escaped(executable, escaping, expected);
559
+ throw escaping;
560
+ }
561
+ };
562
+ // The event handlers of this generation: one instance each, a singleton like a service.
563
+ const eventHandlers = this.eventHandlers.map((registration) => ({
564
+ registration,
565
+ instance: new registration.Handler(),
566
+ }));
567
+ const context = () => ({ ...processContext.values, ...this.context.values });
568
+ const consumersOf = (event) => {
569
+ const known = identityOf(event);
570
+ if (known?.kind !== "event")
571
+ return [];
572
+ const consumers = [];
573
+ const useCase = known.type !== undefined
574
+ ? registrations.get(known.type)
575
+ : generated.get(`event:${known.wire}`);
576
+ if (useCase) {
577
+ consumers.push({
578
+ key: this.name,
579
+ consume: (heard, cause) => root(heard, {}, cause ? { cause } : {}),
580
+ });
581
+ }
582
+ for (const { registration, instance } of eventHandlers) {
583
+ if (!registration.events.some((key) => handles(key, known)))
584
+ continue;
585
+ consumers.push({
586
+ key: `${this.name}/${registration.name}`,
587
+ consume: (heard, cause) => runHandler(instance, heard, {
588
+ owner: this.name,
589
+ name: registration.name,
590
+ dependencies,
591
+ context,
592
+ ...(cause ? { cause } : {}),
593
+ boundedContextOf: (execution) => bindDependency(this, execution),
594
+ expected,
595
+ interceptors: interceptors
596
+ .filter((one) => concerns(one.dtos, heard))
597
+ .map((one) => one.what),
598
+ announce,
599
+ failed: (failure) => {
600
+ announceTo(this.listeners.failed, failure);
601
+ announceTo(everyContext.failed, failure);
602
+ },
603
+ }),
604
+ });
605
+ }
606
+ return consumers;
523
607
  };
608
+ return { root, consumersOf };
524
609
  }
525
610
  }