@sincpro/client-framework 1.2.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.
Files changed (55) hide show
  1. package/AGENTS.md +57 -27
  2. package/MANIFESTO.md +5 -4
  3. package/README.md +225 -157
  4. package/dist/client/services/propagation.js +4 -3
  5. package/dist/codegen/services/scaffold.d.ts +12 -10
  6. package/dist/codegen/services/scaffold.js +23 -40
  7. package/dist/core/domain/bus.d.ts +5 -3
  8. package/dist/core/domain/bus.js +8 -1
  9. package/dist/core/domain/consumers.d.ts +19 -0
  10. package/dist/core/domain/consumers.js +1 -0
  11. package/dist/core/domain/dto.d.ts +68 -6
  12. package/dist/core/domain/dto.js +22 -2
  13. package/dist/core/domain/pipeline.d.ts +7 -3
  14. package/dist/core/domain/services.d.ts +97 -14
  15. package/dist/core/domain/services.js +65 -6
  16. package/dist/core/entrypoint/bounded-context.d.ts +86 -35
  17. package/dist/core/entrypoint/bounded-context.js +224 -71
  18. package/dist/core/entrypoint/screens.js +0 -5
  19. package/dist/core/index.d.ts +6 -3
  20. package/dist/core/index.js +4 -3
  21. package/dist/core/infrastructure/listeners.d.ts +5 -4
  22. package/dist/core/infrastructure/listeners.js +1 -1
  23. package/dist/core/services/dto-keys.d.ts +44 -0
  24. package/dist/core/services/dto-keys.js +97 -0
  25. package/dist/core/services/event-handlers.d.ts +57 -0
  26. package/dist/core/services/event-handlers.js +114 -0
  27. package/dist/core/services/execution.d.ts +15 -21
  28. package/dist/core/services/execution.js +38 -32
  29. package/dist/core/services/interceptors.d.ts +2 -2
  30. package/dist/core/services/interceptors.js +5 -5
  31. package/dist/core/services/listening.d.ts +6 -8
  32. package/dist/core/services/listening.js +3 -2
  33. package/dist/event_driven/adapters/stored-queue.d.ts +5 -5
  34. package/dist/event_driven/adapters/stored-queue.js +5 -10
  35. package/dist/event_driven/domain/envelope.d.ts +2 -2
  36. package/dist/event_driven/domain/envelope.js +7 -1
  37. package/dist/event_driven/domain/messages.d.ts +34 -0
  38. package/dist/event_driven/domain/messages.js +1 -0
  39. package/dist/event_driven/domain/queue.d.ts +9 -5
  40. package/dist/event_driven/entrypoint/publisher.d.ts +2 -2
  41. package/dist/event_driven/entrypoint/publisher.js +4 -0
  42. package/dist/event_driven/entrypoint/subscriber.d.ts +122 -29
  43. package/dist/event_driven/entrypoint/subscriber.js +277 -33
  44. package/dist/event_driven/index.d.ts +11 -10
  45. package/dist/event_driven/index.js +9 -9
  46. package/dist/event_driven/services/messages.d.ts +41 -0
  47. package/dist/event_driven/services/messages.js +147 -0
  48. package/dist/observability/domain/logging.d.ts +4 -8
  49. package/dist/observability/services/logging.d.ts +3 -3
  50. package/dist/observability/services/logging.js +1 -1
  51. package/dist/observability/services/trace-context.d.ts +10 -0
  52. package/dist/observability/services/trace-context.js +29 -0
  53. package/package.json +2 -2
  54. package/dist/event_driven/entrypoint/subscriptions.d.ts +0 -110
  55. package/dist/event_driven/entrypoint/subscriptions.js +0 -184
@@ -2,20 +2,19 @@ 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 Answer, type AnyCommand, Command, type CommandClass, DomainEvent, type EventClass, type Executable, type ResponseClass } from "../domain/dto.js";
5
+ import type { EventConsumer, EventKey } from "../domain/consumers.js";
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";
8
- import { type ExecutableClass } from "../services/listening.js";
9
+ import { type HandledEvent } from "../domain/services.js";
10
+ import { type HandlerRegistrar } from "../services/event-handlers.js";
9
11
  import type { LayerLogger } from "../../observability/domain/logging.js";
10
12
  interface Executor<C extends Executable, R> {
11
13
  execute(executable: C): R | Promise<R>;
12
14
  }
13
- type ServiceClass<C extends Executable, R> = {
14
- new (): Executor<C, R>;
15
- readonly serviceName: string;
16
- };
17
- /** What a service is registered for: a Command's class or a domain event's. */
18
- type DtoClass = ExecutableClass;
15
+ type ServiceClass<C extends Executable, R> = new () => Executor<C, R>;
16
+ /** What a registration is for when it names none: everything; else the DTOs it names. */
17
+ type Of<K> = [K] extends [never] ? Executable : ExecutableOf<K>;
19
18
  /** The service a registration takes the place of, as the backend's `replaces=`. */
20
19
  export type RegistrationOptions = {
21
20
  replaces?: abstract new (...args: never[]) => object;
@@ -39,10 +38,9 @@ export type Registrar<T extends Executable> = <S extends ServiceClass<NoInfer<T>
39
38
  *
40
39
  * Context: registrations, dependencies, handlers and expected errors are snapshotted per
41
40
  * generation; a call keeps the generation it started with, and what is added later answers from
42
- * the next call — as the backend's `build_root_bus`. A domain event may be the input of a use
43
- * case, executed as a Command is: one per bounded context, through the same pipeline. Carrying
44
- * it to whoever hears it (a queue, an outbox) is the platform's; an entrypoint that hears it and
45
- * calls use cases is an `EventSubscriber`. Injected into another run — an `EventSubscriber`, a
41
+ * the next call — as the backend's `build_root_bus`. A service takes one DTO or N — Commands,
42
+ * domain events, generated ones —; registering it for an event is the subscription, and the
43
+ * queue's `Subscriber` executes the event here when it arrives. Injected into another run — a
46
44
  * Feature of another bounded context — it is bound to that run (`BIND`).
47
45
  */
48
46
  export declare class BoundedContext<D extends object = Record<never, never>, C extends object = ContextValues> {
@@ -52,6 +50,7 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
52
50
  /** Its own logger, named after it: for what it does outside a use case. */
53
51
  readonly logger: LayerLogger;
54
52
  private readonly registrations;
53
+ private readonly eventHandlers;
55
54
  private readonly dependencyValues;
56
55
  private readonly handlers;
57
56
  private readonly expected;
@@ -66,36 +65,75 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
66
65
  replaces: D[K];
67
66
  }): this;
68
67
  /**
69
- * Registers the Feature that executes a Command — or that subscribes to a domain event. With
70
- * `replaces`, it takes the place of the service registered now for it.
68
+ * Registers the Feature that executes a DTO — or each DTO listed, as the backend's
69
+ * `feature([CommandX, EventY])`: a Command's class, a domain event's (the use case of the event:
70
+ * registering it is the subscription), or a generated one's entry (`operations.X`, `events.X`).
71
+ * With `replaces`, it takes the place of the service registered now for each.
72
+ *
73
+ * @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid])
74
+ * class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
71
75
  */
76
+ feature<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
72
77
  feature<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
73
78
  feature<E extends DomainEvent>(event: EventClass<E>, options?: RegistrationOptions): Registrar<E>;
74
- /** Registers the ApplicationService of a Command or a domain event; `replaces` as `feature`. */
79
+ feature<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
80
+ feature<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: RegistrationOptions): Registrar<E>;
81
+ /** Registers the ApplicationService of a DTO or of each DTO listed; as `feature`. */
82
+ appService<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
75
83
  appService<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
76
84
  appService<E extends DomainEvent>(event: EventClass<E>, options?: RegistrationOptions): Registrar<E>;
77
- /** The service registered now for a Command or an event class — what a `replaces` names. */
78
- handlerOf(dto: DtoClass): (abstract new (...args: never[]) => object) | undefined;
85
+ appService<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
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>;
104
+ /** The service registered now for a DTO — what a `replaces` names. */
105
+ handlerOf(dto: DtoKey): (abstract new (...args: never[]) => object) | undefined;
106
+ /**
107
+ * What an event of that wire name is rebuilt as here — its class, or the generated entry it
108
+ * was registered with —, or `undefined` when nothing here hears it: the backend's
109
+ * `event_type(name)`.
110
+ */
111
+ eventTypeOf(name: string): EventClass<DomainEvent> | EventDescriptor | undefined;
79
112
  /**
80
- * The event class registered here under a wire name, or `undefined` when nothing here hears it
81
- * — what a platform's queue rebuilds a stored event as, as the backend's `event_type(name)`.
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>`).
82
115
  */
83
- eventTypeOf(name: string): EventClass<DomainEvent> | undefined;
116
+ consumersOf(event: DomainEvent | RemoteEvent): readonly EventConsumer[];
117
+ /**
118
+ * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
119
+ * the generated entry it was registered with —, or `undefined` when nothing here executes it.
120
+ */
121
+ commandTypeOf(identity: string): CommandClass<AnyCommand> | CommandDescriptor | undefined;
84
122
  /**
85
123
  * Runs `interceptor` around every execution of these classes — of every one when none is
86
124
  * named —, outermost first in the order registered. It may look, veto (throw), adjust what it
87
125
  * passes on (of the same class) or answer by itself. Registered after a call, it wraps from
88
126
  * the next one.
89
127
  */
90
- interceptor<T extends Executable = Executable>(...dtos: (abstract new (...args: never[]) => T)[]): <F extends Interceptor<T>>(interceptor: F) => F;
128
+ interceptor<K extends DtoKey = never>(...dtos: K[]): <F extends Interceptor<Of<K>>>(interceptor: F) => F;
91
129
  /** Stops `interceptor` wherever it was registered; from the next call. */
92
130
  withoutInterceptor(interceptor: (...args: never[]) => unknown): this;
93
131
  /** Hears every run of these classes (every one when none is named) begin. Answers how to stop. */
94
- onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoClass[]): () => void;
132
+ onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoKey[]): () => void;
95
133
  /** Hears every run of these classes whose service answered — not an answer a handler gave. */
96
- onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoClass[]): () => void;
134
+ onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoKey[]): () => void;
97
135
  /** Hears every failure that escapes a call — after every handler —, once, where it failed. */
98
- onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoClass[]): () => void;
136
+ onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoKey[]): () => void;
99
137
  /**
100
138
  * Wires a component into this bounded context — its dependencies, services, interceptors,
101
139
  * listeners, handlers — in one place: a module of an application, a plugin. `fresh()` copies
@@ -114,18 +152,20 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
114
152
  */
115
153
  expectErrors(...types: ErrorClass[]): this;
116
154
  /**
117
- * Executes a Command — its Response, inferred —, or a domain event — its subscriber's answer.
118
- * `{ signal }` cancels the run (it ends `aborted`); a delivered event's envelope continues its
119
- * flow (`execute(event, envelope)`).
155
+ * Executes a Command — its Response, inferred —, a domain event — what its use case answers —,
156
+ * or a generated one (`commandOf(operations.X, input)`, an event's data). `{ signal }` cancels
157
+ * the run (it ends `aborted`); a delivered message's cause continues its flow
158
+ * (`execute(event, envelope)`).
120
159
  */
121
160
  execute<R>(command: Command<R>, returnType?: ResponseClass<NoInfer<R>>): Promise<R>;
122
161
  execute<R>(command: Command<R>, options: ExecuteOptions): Promise<R>;
123
- execute(event: DomainEvent, options?: ExecuteOptions | Cause): Promise<unknown>;
162
+ execute<I, R>(command: RemoteCommand<I, R>, options?: ExecuteOptions): Promise<R>;
163
+ execute(event: DomainEvent | RemoteEvent, options?: ExecuteOptions | Cause): Promise<unknown>;
124
164
  scoped(context: Partial<C>): CommandBus;
125
165
  /**
126
- * This bounded context as `execution` calls it — what it is as a dependency of another run (an
127
- * `EventSubscriber`, a Feature of another bounded context): what it executes is a child of
128
- * that run — its span under the caller's, the same flow (`correlationId`), caused by it,
166
+ * This bounded context as `execution` calls it — what it is as a dependency of another run (a
167
+ * Feature of another bounded context, as `common_mcp` is in the backend's helpdesk): what it
168
+ * executes is a child of that run — its span under the caller's, the same flow (`correlationId`), caused by it,
129
169
  * cancelled with it, its errors reported once along it. It still runs with its own
130
170
  * dependencies, context, interceptors and handlers.
131
171
  */
@@ -137,13 +177,24 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
137
177
  private addErrorHandler;
138
178
  private registrar;
139
179
  /**
140
- * 1. The service is of the layer it is registered in, for a Command or a domain event class.
141
- * 2. The class has no service yet — or, with `replaces`, the one it has is that one.
142
- * 3. Its `serviceName` is given and no other service has it; an event's `eventName` is given
143
- * and no other event class here has it — the name means one event.
180
+ * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
181
+ * class, or a generated one's entry.
182
+ * 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
183
+ * 3. Its name is the framework's to take, at registration: the class's name as the code wrote it
184
+ * (a standard decorator's `context.name`, which a minifier does not touch), else the class's
185
+ * `name` — a production build keeps class names (`keep_classnames`, `keepNames`). No other
186
+ * service here has it; the same service may take N DTOs.
187
+ * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
188
+ * it declares one, likewise: a name or an identity means one DTO.
144
189
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
145
190
  */
146
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;
147
198
  private generation;
148
199
  private buildGeneration;
149
200
  }
@@ -2,10 +2,13 @@ import { BIND } from "../../context/domain/execution.js";
2
2
  import { contextAt, } from "../../context/entrypoint/context.js";
3
3
  import { processContext, processStore, } from "../../context/infrastructure/process.js";
4
4
  import { FeatureBus, optionsOf, } from "../domain/bus.js";
5
- import { Command, DomainEvent, } from "../domain/dto.js";
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";
9
+ import { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
8
10
  import { handled } from "../services/error-handlers.js";
11
+ import { eventKeysOf, handlerRegistrar, handles, runHandler, } from "../services/event-handlers.js";
9
12
  import { executeService, failedAt } from "../services/execution.js";
10
13
  import { announceTo, concerns, listenIn, } from "../services/listening.js";
11
14
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
@@ -16,12 +19,9 @@ function isExecutor(value) {
16
19
  "execute" in value &&
17
20
  typeof value.execute === "function");
18
21
  }
19
- function isEventClass(dto) {
20
- return dto.prototype instanceof DomainEvent;
21
- }
22
22
  function nameOf(Service) {
23
23
  const named = Service;
24
- return String(named?.serviceName ?? named?.name ?? Service);
24
+ return String(named?.name ?? Service);
25
25
  }
26
26
  /**
27
27
  * A bounded context: the bus of its Commands and domain events, as sincpro_framework's
@@ -40,10 +40,9 @@ function nameOf(Service) {
40
40
  *
41
41
  * Context: registrations, dependencies, handlers and expected errors are snapshotted per
42
42
  * generation; a call keeps the generation it started with, and what is added later answers from
43
- * the next call — as the backend's `build_root_bus`. A domain event may be the input of a use
44
- * case, executed as a Command is: one per bounded context, through the same pipeline. Carrying
45
- * it to whoever hears it (a queue, an outbox) is the platform's; an entrypoint that hears it and
46
- * calls use cases is an `EventSubscriber`. Injected into another run — an `EventSubscriber`, a
43
+ * the next call — as the backend's `build_root_bus`. A service takes one DTO or N — Commands,
44
+ * domain events, generated ones —; registering it for an event is the subscription, and the
45
+ * queue's `Subscriber` executes the event here when it arrives. Injected into another run — a
47
46
  * Feature of another bounded context — it is bound to that run (`BIND`).
48
47
  */
49
48
  export class BoundedContext {
@@ -53,6 +52,7 @@ export class BoundedContext {
53
52
  /** Its own logger, named after it: for what it does outside a use case. */
54
53
  logger;
55
54
  registrations = new Map();
55
+ eventHandlers = [];
56
56
  dependencyValues = new Map();
57
57
  handlers = {
58
58
  global: [],
@@ -121,17 +121,48 @@ export class BoundedContext {
121
121
  appService(dto, options) {
122
122
  return this.registrar(dto, "application_service", options);
123
123
  }
124
- /** The service registered now for a Command or an event class — what a `replaces` names. */
124
+ handler(events) {
125
+ const keys = eventKeysOf(events);
126
+ return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys));
127
+ }
128
+ /** The service registered now for a DTO — what a `replaces` names. */
125
129
  handlerOf(dto) {
126
130
  return this.registrations.get(dto)?.Service;
127
131
  }
128
132
  /**
129
- * The event class registered here under a wire name, or `undefined` when nothing here hears it
130
- * — what a platform's queue rebuilds a stored event as, as the backend's `event_type(name)`.
133
+ * What an event of that wire name is rebuilt as here — its class, or the generated entry it
134
+ * was registered with —, or `undefined` when nothing here hears it: the backend's
135
+ * `event_type(name)`.
131
136
  */
132
137
  eventTypeOf(name) {
133
138
  for (const dto of this.registrations.keys()) {
134
- if (isEventClass(dto) && dto.eventName === name)
139
+ const known = keyIdentity(dto);
140
+ if (known.kind === "event" && known.wire === name)
141
+ return dto;
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
+ }
149
+ return undefined;
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
+ }
158
+ /**
159
+ * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
160
+ * the generated entry it was registered with —, or `undefined` when nothing here executes it.
161
+ */
162
+ commandTypeOf(identity) {
163
+ for (const dto of this.registrations.keys()) {
164
+ const known = keyIdentity(dto);
165
+ if (known.kind === "command" && known.wire === identity)
135
166
  return dto;
136
167
  }
137
168
  return undefined;
@@ -215,9 +246,9 @@ export class BoundedContext {
215
246
  return new FeatureBus((executable, options) => this.generation().root(executable, scope, options));
216
247
  }
217
248
  /**
218
- * This bounded context as `execution` calls it — what it is as a dependency of another run (an
219
- * `EventSubscriber`, a Feature of another bounded context): what it executes is a child of
220
- * that run — its span under the caller's, the same flow (`correlationId`), caused by it,
249
+ * This bounded context as `execution` calls it — what it is as a dependency of another run (a
250
+ * Feature of another bounded context, as `common_mcp` is in the backend's helpdesk): what it
251
+ * executes is a child of that run — its span under the caller's, the same flow (`correlationId`), caused by it,
221
252
  * cancelled with it, its errors reported once along it. It still runs with its own
222
253
  * dependencies, context, interceptors and handlers.
223
254
  */
@@ -250,6 +281,7 @@ export class BoundedContext {
250
281
  for (const [name, dependency] of this.dependencyValues) {
251
282
  fresh.dependencyValues.set(name, dependency);
252
283
  }
284
+ fresh.eventHandlers.push(...this.eventHandlers);
253
285
  for (const where of ["global", "feature", "application_service"]) {
254
286
  fresh.handlers[where].push(...this.handlers[where]);
255
287
  }
@@ -276,8 +308,7 @@ export class BoundedContext {
276
308
  const heard = {
277
309
  executable: at?.executable ?? executable,
278
310
  execution: at?.execution,
279
- // Listeners hear use cases: a failure an entrypoint's run started says no layer.
280
- layer: at?.layer === "entrypoint" ? undefined : at?.layer,
311
+ layer: at?.layer,
281
312
  error,
282
313
  outcome,
283
314
  };
@@ -292,8 +323,26 @@ export class BoundedContext {
292
323
  return this;
293
324
  }
294
325
  registrar(dto, layer, options = {}) {
326
+ const dtos = Array.isArray(dto) ? dto : [dto];
327
+ if (dtos.length === 0)
328
+ throw new TypeError("A service is registered for one DTO at least");
295
329
  return (Service, decorator) => {
296
- const register = () => this.registerService(dto, Service, layer, options.replaces);
330
+ // All the DTOs listed, or none: a refused one leaves the registrations as they were.
331
+ const register = () => {
332
+ const before = [...this.registrations];
333
+ const revision = this.revision;
334
+ try {
335
+ for (const one of dtos)
336
+ this.registerService(one, Service, layer, options.replaces, decorator?.name);
337
+ }
338
+ catch (error) {
339
+ this.registrations.clear();
340
+ for (const [dto, registration] of before)
341
+ this.registrations.set(dto, registration);
342
+ this.revision = revision;
343
+ throw error;
344
+ }
345
+ };
297
346
  // Standard decorators run before static fields have initialized.
298
347
  if (decorator)
299
348
  decorator.addInitializer(register);
@@ -303,21 +352,47 @@ export class BoundedContext {
303
352
  };
304
353
  }
305
354
  /**
306
- * 1. The service is of the layer it is registered in, for a Command or a domain event class.
307
- * 2. The class has no service yet — or, with `replaces`, the one it has is that one.
308
- * 3. Its `serviceName` is given and no other service has it; an event's `eventName` is given
309
- * and no other event class here has it — the name means one event.
355
+ * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
356
+ * class, or a generated one's entry.
357
+ * 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
358
+ * 3. Its name is the framework's to take, at registration: the class's name as the code wrote it
359
+ * (a standard decorator's `context.name`, which a minifier does not touch), else the class's
360
+ * `name` — a production build keeps class names (`keep_classnames`, `keepNames`). No other
361
+ * service here has it; the same service may take N DTOs.
362
+ * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
363
+ * it declares one, likewise: a name or an identity means one DTO.
310
364
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
311
365
  */
312
- registerService(dto, Service, layer, replaces) {
366
+ registerService(dto, Service, layer, replaces, written) {
313
367
  const Base = layer === "feature" ? Feature : ApplicationService;
314
368
  if (!(Service.prototype instanceof Base) ||
315
369
  (layer === "feature" && Service.prototype instanceof ApplicationService)) {
316
370
  throw new TypeError(`The service is not an ${layer}`);
317
371
  }
318
- const event = isEventClass(dto);
319
- if (!event && !(dto.prototype instanceof Command)) {
320
- throw new TypeError("A service is registered for a Command or a DomainEvent class");
372
+ if (!isDtoKey(dto)) {
373
+ throw new TypeError("A service is registered for a Command or a DomainEvent: its class, or a generated one's entry");
374
+ }
375
+ // A Command's identity is the framework's, as the backend's `registered_name`:
376
+ // `<context>.<Command>` — the key a generated contract's `operations` carry too.
377
+ if (isCommandClass(dto) && !Object.hasOwn(dto, "commandName") && dto.name !== "") {
378
+ Object.defineProperty(dto, "commandName", {
379
+ value: `${this.name}.${dto.name}`,
380
+ configurable: true,
381
+ });
382
+ }
383
+ const known = keyIdentity(dto);
384
+ if (known.kind === "event" &&
385
+ (typeof known.wire !== "string" || known.wire.trim() === "")) {
386
+ throw new Error("A domain event needs a nonempty eventName");
387
+ }
388
+ if (known.kind === "event" && !EVENT_NAME.test(known.wire ?? "")) {
389
+ throw new Error(`${known.wire} is not an event's name: <context>.<aggregate>.vN.<fact>`);
390
+ }
391
+ if (isCommandDescriptor(dto) && dto.identity.trim() === "") {
392
+ throw new Error("A generated Command needs its identity");
393
+ }
394
+ if (isCommandClass(dto) && known.wire !== undefined && known.wire.trim() === "") {
395
+ throw new Error("A Command's commandName, when declared, is nonempty");
321
396
  }
322
397
  const current = this.registrations.get(dto);
323
398
  if (replaces !== undefined && current?.Service !== replaces) {
@@ -326,24 +401,28 @@ export class BoundedContext {
326
401
  if (replaces === undefined && current) {
327
402
  throw new Error("Command already registered: one executor across both layers");
328
403
  }
329
- const name = Service.serviceName;
404
+ const name = written ?? Service.name;
330
405
  if (typeof name !== "string" || name.trim() === "") {
331
- throw new Error("A service needs a nonempty registered name");
406
+ throw new Error("A service is a named class: its name is its use case in spans and logs");
407
+ }
408
+ if (this.eventHandlers.some((one) => one.name === name)) {
409
+ throw new Error(`Service name already registered: ${name}`);
332
410
  }
333
411
  for (const [other, registration] of this.registrations) {
334
- if (registration !== current && registration.name === name) {
412
+ if (registration !== current &&
413
+ registration.Service !== Service &&
414
+ registration.name === name) {
335
415
  throw new Error(`Service name already registered: ${name}`);
336
416
  }
337
- if (event &&
338
- other !== dto &&
339
- isEventClass(other) &&
340
- other.eventName === dto.eventName) {
341
- throw new Error(`Event name already registered: ${dto.eventName}`);
417
+ if (other === dto || known.wire === undefined)
418
+ continue;
419
+ const theirs = keyIdentity(other);
420
+ if (theirs.kind === known.kind && theirs.wire === known.wire) {
421
+ throw new Error(known.kind === "event"
422
+ ? `Event name already registered: ${known.wire}`
423
+ : `Command identity already registered: ${known.wire}`);
342
424
  }
343
425
  }
344
- if (event && (typeof dto.eventName !== "string" || dto.eventName.trim() === "")) {
345
- throw new Error("A domain event needs a nonempty eventName");
346
- }
347
426
  this.registrations.set(dto, {
348
427
  name,
349
428
  layer,
@@ -352,6 +431,22 @@ export class BoundedContext {
352
431
  });
353
432
  this.revision++;
354
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
+ }
355
450
  generation() {
356
451
  if (this.built && this.builtRevision === this.revision)
357
452
  return this.built;
@@ -383,28 +478,43 @@ export class BoundedContext {
383
478
  announceTo(everyContext.completed, heard);
384
479
  },
385
480
  };
481
+ // One instance per service, whatever number of DTOs it takes: a singleton of its generation.
386
482
  const instances = new Map();
387
- for (const registration of registrations.values()) {
388
- const instance = new registration.Service();
389
- if (!isExecutor(instance)) {
390
- throw new Error(`Registered service is unavailable: ${registration.name}`);
483
+ // A generated DTO has no class: it is found by its kind and wire identity.
484
+ const generated = new Map();
485
+ for (const [dto, registration] of registrations) {
486
+ if (!instances.has(registration.Service)) {
487
+ const instance = new registration.Service();
488
+ if (!isExecutor(instance)) {
489
+ throw new Error(`Registered service is unavailable: ${registration.name}`);
490
+ }
491
+ instances.set(registration.Service, instance);
391
492
  }
392
- instances.set(registration, instance);
493
+ const known = keyIdentity(dto);
494
+ if (known.type === undefined)
495
+ generated.set(`${known.kind}:${known.wire}`, registration);
393
496
  }
394
497
  const dispatch = async (executable, parent, featureOnly = false, scope = {}, options = {}) => {
395
- // Exact constructor identity: a subclass of a registered class is another one.
396
- const target = registrations.get(Object.getPrototypeOf(executable)?.constructor);
498
+ // Exact constructor identity — a subclass of a registered class is another one —; a
499
+ // generated DTO, by its kind and wire identity.
500
+ const known = identityOf(executable);
501
+ const target = known === undefined
502
+ ? undefined
503
+ : known.type !== undefined
504
+ ? registrations.get(known.type)
505
+ : generated.get(`${known.kind}:${known.wire}`);
397
506
  if (!target)
398
- throw new Error("No executor registered for this command class");
507
+ throw new Error(`No executor registered for ${describeDto(executable)}`);
399
508
  if (featureOnly && target.layer !== "feature") {
400
509
  throw new Error("An ApplicationService may compose only Features");
401
510
  }
402
- const service = instances.get(target);
511
+ const service = instances.get(target.Service);
403
512
  if (!service) {
404
513
  throw new Error(`Registered service is unavailable: ${target.name}`);
405
514
  }
406
515
  const attributes = {
407
- ...(executable instanceof DomainEvent ? { "sincpro.event": executable.name } : {}),
516
+ ...(known?.kind === "event" && known.wire ? { "sincpro.event": known.wire } : {}),
517
+ ...(known?.kind === "command" && known.wire ? { "sincpro.command": known.wire } : {}),
408
518
  ...(target.replaces ? { "sincpro.replaces": target.replaces } : {}),
409
519
  };
410
520
  return executeService(service, executable, {
@@ -417,10 +527,8 @@ export class BoundedContext {
417
527
  ...(parent ? { parent } : {}),
418
528
  // A root called from another run continues it; a child continues its parent.
419
529
  ...(options.caller && !parent ? { caller: options.caller } : {}),
420
- // Only an event comes from outside with a cause.
421
- ...(options.cause && executable instanceof DomainEvent && !parent
422
- ? { cause: options.cause }
423
- : {}),
530
+ // A delivered message — an event, a Command — continues the flow of what caused it.
531
+ ...(options.cause && !parent ? { cause: options.cause } : {}),
424
532
  ...(options.signal ? { signal: options.signal } : {}),
425
533
  featureBus: (execution) => new FeatureBus((child, options) => dispatch(child, execution, true, {}, options)),
426
534
  expected,
@@ -431,27 +539,72 @@ export class BoundedContext {
431
539
  announce,
432
540
  });
433
541
  };
434
- return {
435
- root: async (executable, scope, options) => {
436
- try {
437
- return await dispatch(executable, undefined, false, scope, options);
438
- }
439
- catch (error) {
440
- let escaping = error;
441
- if (handlers.global.length > 0) {
442
- try {
443
- const answer = await handled(handlers.global, error);
444
- logHandled("bounded_context", { boundedContext: this.name });
445
- return answer;
446
- }
447
- catch (thrown) {
448
- escaping = thrown;
449
- }
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;
450
556
  }
451
- this.escaped(executable, escaping, expected);
452
- throw escaping;
453
557
  }
454
- },
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;
455
607
  };
608
+ return { root, consumersOf };
456
609
  }
457
610
  }