@sincpro/client-framework 1.2.0 → 1.3.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 (51) hide show
  1. package/AGENTS.md +38 -21
  2. package/MANIFESTO.md +4 -4
  3. package/README.md +183 -158
  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/dto.d.ts +68 -6
  10. package/dist/core/domain/dto.js +22 -2
  11. package/dist/core/domain/pipeline.d.ts +5 -2
  12. package/dist/core/domain/services.d.ts +39 -13
  13. package/dist/core/domain/services.js +30 -6
  14. package/dist/core/entrypoint/bounded-context.d.ts +54 -35
  15. package/dist/core/entrypoint/bounded-context.js +120 -52
  16. package/dist/core/entrypoint/screens.js +0 -5
  17. package/dist/core/index.d.ts +4 -3
  18. package/dist/core/index.js +4 -3
  19. package/dist/core/infrastructure/listeners.d.ts +5 -4
  20. package/dist/core/infrastructure/listeners.js +1 -1
  21. package/dist/core/services/dto-keys.d.ts +44 -0
  22. package/dist/core/services/dto-keys.js +97 -0
  23. package/dist/core/services/execution.d.ts +10 -21
  24. package/dist/core/services/execution.js +29 -32
  25. package/dist/core/services/interceptors.d.ts +2 -2
  26. package/dist/core/services/interceptors.js +5 -5
  27. package/dist/core/services/listening.d.ts +6 -8
  28. package/dist/core/services/listening.js +3 -2
  29. package/dist/event_driven/adapters/stored-queue.d.ts +5 -5
  30. package/dist/event_driven/adapters/stored-queue.js +5 -10
  31. package/dist/event_driven/domain/envelope.d.ts +2 -2
  32. package/dist/event_driven/domain/envelope.js +7 -1
  33. package/dist/event_driven/domain/messages.d.ts +34 -0
  34. package/dist/event_driven/domain/messages.js +1 -0
  35. package/dist/event_driven/domain/queue.d.ts +9 -5
  36. package/dist/event_driven/entrypoint/publisher.d.ts +2 -2
  37. package/dist/event_driven/entrypoint/publisher.js +4 -0
  38. package/dist/event_driven/entrypoint/subscriber.d.ts +66 -27
  39. package/dist/event_driven/entrypoint/subscriber.js +117 -21
  40. package/dist/event_driven/index.d.ts +11 -10
  41. package/dist/event_driven/index.js +9 -9
  42. package/dist/event_driven/services/messages.d.ts +41 -0
  43. package/dist/event_driven/services/messages.js +147 -0
  44. package/dist/observability/domain/logging.d.ts +4 -8
  45. package/dist/observability/services/logging.d.ts +3 -3
  46. package/dist/observability/services/logging.js +1 -1
  47. package/dist/observability/services/trace-context.d.ts +10 -0
  48. package/dist/observability/services/trace-context.js +29 -0
  49. package/package.json +2 -2
  50. package/dist/event_driven/entrypoint/subscriptions.d.ts +0 -110
  51. package/dist/event_driven/entrypoint/subscriptions.js +0 -184
@@ -2,20 +2,16 @@ 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 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
6
  import type { ErrorClass, ErrorHandler } from "../domain/errors.js";
7
7
  import type { Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, Interceptor, Listener } from "../domain/pipeline.js";
8
- import { type ExecutableClass } from "../services/listening.js";
9
8
  import type { LayerLogger } from "../../observability/domain/logging.js";
10
9
  interface Executor<C extends Executable, R> {
11
10
  execute(executable: C): R | Promise<R>;
12
11
  }
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;
12
+ type ServiceClass<C extends Executable, R> = new () => Executor<C, R>;
13
+ /** What a registration is for when it names none: everything; else the DTOs it names. */
14
+ type Of<K> = [K] extends [never] ? Executable : ExecutableOf<K>;
19
15
  /** The service a registration takes the place of, as the backend's `replaces=`. */
20
16
  export type RegistrationOptions = {
21
17
  replaces?: abstract new (...args: never[]) => object;
@@ -39,10 +35,9 @@ export type Registrar<T extends Executable> = <S extends ServiceClass<NoInfer<T>
39
35
  *
40
36
  * Context: registrations, dependencies, handlers and expected errors are snapshotted per
41
37
  * 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
38
+ * the next call — as the backend's `build_root_bus`. A service takes one DTO or N — Commands,
39
+ * domain events, generated ones —; registering it for an event is the subscription, and the
40
+ * queue's `Subscriber` executes the event here when it arrives. Injected into another run — a
46
41
  * Feature of another bounded context — it is bound to that run (`BIND`).
47
42
  */
48
43
  export declare class BoundedContext<D extends object = Record<never, never>, C extends object = ContextValues> {
@@ -66,36 +61,53 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
66
61
  replaces: D[K];
67
62
  }): this;
68
63
  /**
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.
64
+ * Registers the Feature that executes a DTO — or each DTO listed, as the backend's
65
+ * `feature([CommandX, EventY])`: a Command's class, a domain event's (the use case of the event:
66
+ * registering it is the subscription), or a generated one's entry (`operations.X`, `events.X`).
67
+ * With `replaces`, it takes the place of the service registered now for each.
68
+ *
69
+ * @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid])
70
+ * class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
71
71
  */
72
+ feature<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
72
73
  feature<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
73
74
  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`. */
75
+ feature<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
76
+ feature<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: RegistrationOptions): Registrar<E>;
77
+ /** Registers the ApplicationService of a DTO or of each DTO listed; as `feature`. */
78
+ appService<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
75
79
  appService<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
76
80
  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;
81
+ appService<I = unknown, R = unknown>(command: CommandDescriptor, options?: RegistrationOptions): Registrar<RemoteCommand<I, R>>;
82
+ appService<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: RegistrationOptions): Registrar<E>;
83
+ /** The service registered now for a DTO — what a `replaces` names. */
84
+ handlerOf(dto: DtoKey): (abstract new (...args: never[]) => object) | undefined;
85
+ /**
86
+ * What an event of that wire name is rebuilt as here — its class, or the generated entry it
87
+ * was registered with —, or `undefined` when nothing here hears it: the backend's
88
+ * `event_type(name)`.
89
+ */
90
+ eventTypeOf(name: string): EventClass<DomainEvent> | EventDescriptor | undefined;
79
91
  /**
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)`.
92
+ * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
93
+ * the generated entry it was registered with —, or `undefined` when nothing here executes it.
82
94
  */
83
- eventTypeOf(name: string): EventClass<DomainEvent> | undefined;
95
+ commandTypeOf(identity: string): CommandClass<AnyCommand> | CommandDescriptor | undefined;
84
96
  /**
85
97
  * Runs `interceptor` around every execution of these classes — of every one when none is
86
98
  * named —, outermost first in the order registered. It may look, veto (throw), adjust what it
87
99
  * passes on (of the same class) or answer by itself. Registered after a call, it wraps from
88
100
  * the next one.
89
101
  */
90
- interceptor<T extends Executable = Executable>(...dtos: (abstract new (...args: never[]) => T)[]): <F extends Interceptor<T>>(interceptor: F) => F;
102
+ interceptor<K extends DtoKey = never>(...dtos: K[]): <F extends Interceptor<Of<K>>>(interceptor: F) => F;
91
103
  /** Stops `interceptor` wherever it was registered; from the next call. */
92
104
  withoutInterceptor(interceptor: (...args: never[]) => unknown): this;
93
105
  /** 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;
106
+ onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoKey[]): () => void;
95
107
  /** Hears every run of these classes whose service answered — not an answer a handler gave. */
96
- onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoClass[]): () => void;
108
+ onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoKey[]): () => void;
97
109
  /** Hears every failure that escapes a call — after every handler —, once, where it failed. */
98
- onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoClass[]): () => void;
110
+ onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoKey[]): () => void;
99
111
  /**
100
112
  * Wires a component into this bounded context — its dependencies, services, interceptors,
101
113
  * listeners, handlers — in one place: a module of an application, a plugin. `fresh()` copies
@@ -114,18 +126,20 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
114
126
  */
115
127
  expectErrors(...types: ErrorClass[]): this;
116
128
  /**
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)`).
129
+ * Executes a Command — its Response, inferred —, a domain event — what its use case answers —,
130
+ * or a generated one (`commandOf(operations.X, input)`, an event's data). `{ signal }` cancels
131
+ * the run (it ends `aborted`); a delivered message's cause continues its flow
132
+ * (`execute(event, envelope)`).
120
133
  */
121
134
  execute<R>(command: Command<R>, returnType?: ResponseClass<NoInfer<R>>): Promise<R>;
122
135
  execute<R>(command: Command<R>, options: ExecuteOptions): Promise<R>;
123
- execute(event: DomainEvent, options?: ExecuteOptions | Cause): Promise<unknown>;
136
+ execute<I, R>(command: RemoteCommand<I, R>, options?: ExecuteOptions): Promise<R>;
137
+ execute(event: DomainEvent | RemoteEvent, options?: ExecuteOptions | Cause): Promise<unknown>;
124
138
  scoped(context: Partial<C>): CommandBus;
125
139
  /**
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,
140
+ * This bounded context as `execution` calls it — what it is as a dependency of another run (a
141
+ * Feature of another bounded context, as `common_mcp` is in the backend's helpdesk): what it
142
+ * executes is a child of that run — its span under the caller's, the same flow (`correlationId`), caused by it,
129
143
  * cancelled with it, its errors reported once along it. It still runs with its own
130
144
  * dependencies, context, interceptors and handlers.
131
145
  */
@@ -137,10 +151,15 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
137
151
  private addErrorHandler;
138
152
  private registrar;
139
153
  /**
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.
154
+ * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
155
+ * class, or a generated one's entry.
156
+ * 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
157
+ * 3. Its name is the framework's to take, at registration: the class's name as the code wrote it
158
+ * (a standard decorator's `context.name`, which a minifier does not touch), else the class's
159
+ * `name` — a production build keeps class names (`keep_classnames`, `keepNames`). No other
160
+ * service here has it; the same service may take N DTOs.
161
+ * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
162
+ * it declares one, likewise: a name or an identity means one DTO.
144
163
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
145
164
  */
146
165
  private registerService;
@@ -2,9 +2,10 @@ 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 { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
8
9
  import { handled } from "../services/error-handlers.js";
9
10
  import { executeService, failedAt } from "../services/execution.js";
10
11
  import { announceTo, concerns, listenIn, } from "../services/listening.js";
@@ -16,12 +17,9 @@ function isExecutor(value) {
16
17
  "execute" in value &&
17
18
  typeof value.execute === "function");
18
19
  }
19
- function isEventClass(dto) {
20
- return dto.prototype instanceof DomainEvent;
21
- }
22
20
  function nameOf(Service) {
23
21
  const named = Service;
24
- return String(named?.serviceName ?? named?.name ?? Service);
22
+ return String(named?.name ?? Service);
25
23
  }
26
24
  /**
27
25
  * A bounded context: the bus of its Commands and domain events, as sincpro_framework's
@@ -40,10 +38,9 @@ function nameOf(Service) {
40
38
  *
41
39
  * Context: registrations, dependencies, handlers and expected errors are snapshotted per
42
40
  * 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
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
47
44
  * Feature of another bounded context — it is bound to that run (`BIND`).
48
45
  */
49
46
  export class BoundedContext {
@@ -121,17 +118,31 @@ export class BoundedContext {
121
118
  appService(dto, options) {
122
119
  return this.registrar(dto, "application_service", options);
123
120
  }
124
- /** The service registered now for a Command or an event class — what a `replaces` names. */
121
+ /** The service registered now for a DTO — what a `replaces` names. */
125
122
  handlerOf(dto) {
126
123
  return this.registrations.get(dto)?.Service;
127
124
  }
128
125
  /**
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)`.
126
+ * What an event of that wire name is rebuilt as here — its class, or the generated entry it
127
+ * was registered with —, or `undefined` when nothing here hears it: the backend's
128
+ * `event_type(name)`.
131
129
  */
132
130
  eventTypeOf(name) {
133
131
  for (const dto of this.registrations.keys()) {
134
- if (isEventClass(dto) && dto.eventName === name)
132
+ const known = keyIdentity(dto);
133
+ if (known.kind === "event" && known.wire === name)
134
+ return dto;
135
+ }
136
+ return undefined;
137
+ }
138
+ /**
139
+ * What a Command of that identity (`<context>.<Command>`) is rebuilt as here — its class, or
140
+ * the generated entry it was registered with —, or `undefined` when nothing here executes it.
141
+ */
142
+ commandTypeOf(identity) {
143
+ for (const dto of this.registrations.keys()) {
144
+ const known = keyIdentity(dto);
145
+ if (known.kind === "command" && known.wire === identity)
135
146
  return dto;
136
147
  }
137
148
  return undefined;
@@ -215,9 +226,9 @@ export class BoundedContext {
215
226
  return new FeatureBus((executable, options) => this.generation().root(executable, scope, options));
216
227
  }
217
228
  /**
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,
229
+ * This bounded context as `execution` calls it — what it is as a dependency of another run (a
230
+ * Feature of another bounded context, as `common_mcp` is in the backend's helpdesk): what it
231
+ * executes is a child of that run — its span under the caller's, the same flow (`correlationId`), caused by it,
221
232
  * cancelled with it, its errors reported once along it. It still runs with its own
222
233
  * dependencies, context, interceptors and handlers.
223
234
  */
@@ -276,8 +287,7 @@ export class BoundedContext {
276
287
  const heard = {
277
288
  executable: at?.executable ?? executable,
278
289
  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,
290
+ layer: at?.layer,
281
291
  error,
282
292
  outcome,
283
293
  };
@@ -292,8 +302,26 @@ export class BoundedContext {
292
302
  return this;
293
303
  }
294
304
  registrar(dto, layer, options = {}) {
305
+ const dtos = Array.isArray(dto) ? dto : [dto];
306
+ if (dtos.length === 0)
307
+ throw new TypeError("A service is registered for one DTO at least");
295
308
  return (Service, decorator) => {
296
- const register = () => this.registerService(dto, Service, layer, options.replaces);
309
+ // All the DTOs listed, or none: a refused one leaves the registrations as they were.
310
+ const register = () => {
311
+ const before = [...this.registrations];
312
+ const revision = this.revision;
313
+ try {
314
+ for (const one of dtos)
315
+ this.registerService(one, Service, layer, options.replaces, decorator?.name);
316
+ }
317
+ catch (error) {
318
+ this.registrations.clear();
319
+ for (const [dto, registration] of before)
320
+ this.registrations.set(dto, registration);
321
+ this.revision = revision;
322
+ throw error;
323
+ }
324
+ };
297
325
  // Standard decorators run before static fields have initialized.
298
326
  if (decorator)
299
327
  decorator.addInitializer(register);
@@ -303,21 +331,47 @@ export class BoundedContext {
303
331
  };
304
332
  }
305
333
  /**
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.
334
+ * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
335
+ * class, or a generated one's entry.
336
+ * 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
337
+ * 3. Its name is the framework's to take, at registration: the class's name as the code wrote it
338
+ * (a standard decorator's `context.name`, which a minifier does not touch), else the class's
339
+ * `name` — a production build keeps class names (`keep_classnames`, `keepNames`). No other
340
+ * service here has it; the same service may take N DTOs.
341
+ * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
342
+ * it declares one, likewise: a name or an identity means one DTO.
310
343
  * Final: registered, said on its spans when it replaced another; the next call answers with it.
311
344
  */
312
- registerService(dto, Service, layer, replaces) {
345
+ registerService(dto, Service, layer, replaces, written) {
313
346
  const Base = layer === "feature" ? Feature : ApplicationService;
314
347
  if (!(Service.prototype instanceof Base) ||
315
348
  (layer === "feature" && Service.prototype instanceof ApplicationService)) {
316
349
  throw new TypeError(`The service is not an ${layer}`);
317
350
  }
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");
351
+ if (!isDtoKey(dto)) {
352
+ throw new TypeError("A service is registered for a Command or a DomainEvent: its class, or a generated one's entry");
353
+ }
354
+ // A Command's identity is the framework's, as the backend's `registered_name`:
355
+ // `<context>.<Command>` — the key a generated contract's `operations` carry too.
356
+ if (isCommandClass(dto) && !Object.hasOwn(dto, "commandName") && dto.name !== "") {
357
+ Object.defineProperty(dto, "commandName", {
358
+ value: `${this.name}.${dto.name}`,
359
+ configurable: true,
360
+ });
361
+ }
362
+ const known = keyIdentity(dto);
363
+ if (known.kind === "event" &&
364
+ (typeof known.wire !== "string" || known.wire.trim() === "")) {
365
+ throw new Error("A domain event needs a nonempty eventName");
366
+ }
367
+ if (known.kind === "event" && !EVENT_NAME.test(known.wire ?? "")) {
368
+ throw new Error(`${known.wire} is not an event's name: <context>.<aggregate>.vN.<fact>`);
369
+ }
370
+ if (isCommandDescriptor(dto) && dto.identity.trim() === "") {
371
+ throw new Error("A generated Command needs its identity");
372
+ }
373
+ if (isCommandClass(dto) && known.wire !== undefined && known.wire.trim() === "") {
374
+ throw new Error("A Command's commandName, when declared, is nonempty");
321
375
  }
322
376
  const current = this.registrations.get(dto);
323
377
  if (replaces !== undefined && current?.Service !== replaces) {
@@ -326,24 +380,25 @@ export class BoundedContext {
326
380
  if (replaces === undefined && current) {
327
381
  throw new Error("Command already registered: one executor across both layers");
328
382
  }
329
- const name = Service.serviceName;
383
+ const name = written ?? Service.name;
330
384
  if (typeof name !== "string" || name.trim() === "") {
331
- throw new Error("A service needs a nonempty registered name");
385
+ throw new Error("A service is a named class: its name is its use case in spans and logs");
332
386
  }
333
387
  for (const [other, registration] of this.registrations) {
334
- if (registration !== current && registration.name === name) {
388
+ if (registration !== current &&
389
+ registration.Service !== Service &&
390
+ registration.name === name) {
335
391
  throw new Error(`Service name already registered: ${name}`);
336
392
  }
337
- if (event &&
338
- other !== dto &&
339
- isEventClass(other) &&
340
- other.eventName === dto.eventName) {
341
- throw new Error(`Event name already registered: ${dto.eventName}`);
393
+ if (other === dto || known.wire === undefined)
394
+ continue;
395
+ const theirs = keyIdentity(other);
396
+ if (theirs.kind === known.kind && theirs.wire === known.wire) {
397
+ throw new Error(known.kind === "event"
398
+ ? `Event name already registered: ${known.wire}`
399
+ : `Command identity already registered: ${known.wire}`);
342
400
  }
343
401
  }
344
- if (event && (typeof dto.eventName !== "string" || dto.eventName.trim() === "")) {
345
- throw new Error("A domain event needs a nonempty eventName");
346
- }
347
402
  this.registrations.set(dto, {
348
403
  name,
349
404
  layer,
@@ -383,28 +438,43 @@ export class BoundedContext {
383
438
  announceTo(everyContext.completed, heard);
384
439
  },
385
440
  };
441
+ // One instance per service, whatever number of DTOs it takes: a singleton of its generation.
386
442
  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}`);
443
+ // A generated DTO has no class: it is found by its kind and wire identity.
444
+ const generated = new Map();
445
+ for (const [dto, registration] of registrations) {
446
+ if (!instances.has(registration.Service)) {
447
+ const instance = new registration.Service();
448
+ if (!isExecutor(instance)) {
449
+ throw new Error(`Registered service is unavailable: ${registration.name}`);
450
+ }
451
+ instances.set(registration.Service, instance);
391
452
  }
392
- instances.set(registration, instance);
453
+ const known = keyIdentity(dto);
454
+ if (known.type === undefined)
455
+ generated.set(`${known.kind}:${known.wire}`, registration);
393
456
  }
394
457
  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);
458
+ // Exact constructor identity — a subclass of a registered class is another one —; a
459
+ // generated DTO, by its kind and wire identity.
460
+ const known = identityOf(executable);
461
+ const target = known === undefined
462
+ ? undefined
463
+ : known.type !== undefined
464
+ ? registrations.get(known.type)
465
+ : generated.get(`${known.kind}:${known.wire}`);
397
466
  if (!target)
398
- throw new Error("No executor registered for this command class");
467
+ throw new Error(`No executor registered for ${describeDto(executable)}`);
399
468
  if (featureOnly && target.layer !== "feature") {
400
469
  throw new Error("An ApplicationService may compose only Features");
401
470
  }
402
- const service = instances.get(target);
471
+ const service = instances.get(target.Service);
403
472
  if (!service) {
404
473
  throw new Error(`Registered service is unavailable: ${target.name}`);
405
474
  }
406
475
  const attributes = {
407
- ...(executable instanceof DomainEvent ? { "sincpro.event": executable.name } : {}),
476
+ ...(known?.kind === "event" && known.wire ? { "sincpro.event": known.wire } : {}),
477
+ ...(known?.kind === "command" && known.wire ? { "sincpro.command": known.wire } : {}),
408
478
  ...(target.replaces ? { "sincpro.replaces": target.replaces } : {}),
409
479
  };
410
480
  return executeService(service, executable, {
@@ -417,10 +487,8 @@ export class BoundedContext {
417
487
  ...(parent ? { parent } : {}),
418
488
  // A root called from another run continues it; a child continues its parent.
419
489
  ...(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
- : {}),
490
+ // A delivered message — an event, a Command — continues the flow of what caused it.
491
+ ...(options.cause && !parent ? { cause: options.cause } : {}),
424
492
  ...(options.signal ? { signal: options.signal } : {}),
425
493
  featureBus: (execution) => new FeatureBus((child, options) => dispatch(child, execution, true, {}, options)),
426
494
  expected,
@@ -63,21 +63,18 @@ class Send extends Command {
63
63
  }
64
64
  }
65
65
  class EntityList extends Feature {
66
- static serviceName = "EntityReads.list";
67
66
  execute(dto) {
68
67
  this.span.set({ "http.route": dto.route });
69
68
  return this.transport.list(dto.route, dto.criteria, dto.signal, dto.options);
70
69
  }
71
70
  }
72
71
  class EntityGet extends Feature {
73
- static serviceName = "EntityReads.one";
74
72
  execute(dto) {
75
73
  this.span.set({ "http.route": dto.route });
76
74
  return this.transport.one(dto.route, dto.signal, dto.options);
77
75
  }
78
76
  }
79
77
  class EntityRead extends Feature {
80
- static serviceName = "EntityReads.read";
81
78
  execute(dto) {
82
79
  this.span.set({ "http.route": dto.route });
83
80
  const transport = this.transport;
@@ -88,7 +85,6 @@ class EntityRead extends Feature {
88
85
  }
89
86
  }
90
87
  class EntityExport extends Feature {
91
- static serviceName = "EntityReads.download";
92
88
  execute(dto) {
93
89
  this.span.set({ "http.route": dto.route });
94
90
  const transport = this.transport;
@@ -99,7 +95,6 @@ class EntityExport extends Feature {
99
95
  }
100
96
  }
101
97
  class EntitySend extends Feature {
102
- static serviceName = "EntityWrites.send";
103
98
  execute(dto) {
104
99
  this.span.set({ "http.method": dto.method, "http.route": dto.route });
105
100
  return this.transport.send(dto.method, dto.route, dto.body, dto.signal, dto.options);
@@ -3,16 +3,17 @@
3
3
  * Responses, Features and ApplicationServices, a bounded context that is their bus, its error
4
4
  * handlers — and the process they run in.
5
5
  *
6
- * domain/ DTOs, the bus, the service bases, the error-handler contract
6
+ * domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
7
+ * bases (`servicesWith`: typed with a context's dependencies), the error handlers
7
8
  * services/ the execution pipeline, dependency binding, the handler chain
8
9
  * entrypoint/ `BoundedContext`, `screensTransport`
9
10
  * infrastructure/ `configureProcess`, `configureLogger`
10
11
  */
11
12
  export { type CommandBus, FeatureBus } from "./domain/bus.js";
12
- export { Command, DataTransferObject, DomainEvent, type EventClass, Response, } from "./domain/dto.js";
13
+ export { type AnyCommand, Command, COMMAND_IDENTITY, type CommandClass, type CommandDescriptor, type CommandNamed, commandOf, DataTransferObject, DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable, type ExecutableOf, type RemoteCommand, type RemoteEvent, Response, } from "./domain/dto.js";
13
14
  export type { ErrorClass, ErrorHandler } from "./domain/errors.js";
14
15
  export type { CallNext, Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, InterceptedRun, Interceptor, Listener, PipelineLayer, } from "./domain/pipeline.js";
15
- export { ApplicationService, Feature } from "./domain/services.js";
16
+ export { ApplicationService, type ApplicationServiceWith, Feature, type FeatureWith, type ServiceInput, servicesWith, } from "./domain/services.js";
16
17
  export { BoundedContext, type Registrar, type RegistrationOptions, } from "./entrypoint/bounded-context.js";
17
18
  export { screensTransport } from "./entrypoint/screens.js";
18
19
  export { processListeners } from "./infrastructure/listeners.js";
@@ -3,14 +3,15 @@
3
3
  * Responses, Features and ApplicationServices, a bounded context that is their bus, its error
4
4
  * handlers — and the process they run in.
5
5
  *
6
- * domain/ DTOs, the bus, the service bases, the error-handler contract
6
+ * domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
7
+ * bases (`servicesWith`: typed with a context's dependencies), the error handlers
7
8
  * services/ the execution pipeline, dependency binding, the handler chain
8
9
  * entrypoint/ `BoundedContext`, `screensTransport`
9
10
  * infrastructure/ `configureProcess`, `configureLogger`
10
11
  */
11
12
  export { FeatureBus } from "./domain/bus.js";
12
- export { Command, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
13
- export { ApplicationService, Feature } from "./domain/services.js";
13
+ export { Command, COMMAND_IDENTITY, commandOf, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
14
+ export { ApplicationService, Feature, servicesWith, } from "./domain/services.js";
14
15
  export { BoundedContext, } from "./entrypoint/bounded-context.js";
15
16
  export { screensTransport } from "./entrypoint/screens.js";
16
17
  export { processListeners } from "./infrastructure/listeners.js";
@@ -1,5 +1,6 @@
1
+ import type { DtoKey } from "../domain/dto.js";
1
2
  import type { ExecutionCompleted, ExecutionFailed, ExecutionStarted, Listener } from "../domain/pipeline.js";
2
- import { type ExecutableClass, type Hearing } from "../services/listening.js";
3
+ import { type Hearing } from "../services/listening.js";
3
4
  /**
4
5
  * Who hears every bounded context of this process — the backend's process listeners: an
5
6
  * activity indicator, a toast, an audit that must not be wired into each context.
@@ -19,10 +20,10 @@ declare const hearing: {
19
20
  export declare function processHearing(): typeof hearing;
20
21
  export declare const processListeners: {
21
22
  /** Hears every run of every bounded context begin. Answers how to stop. */
22
- onStart(listener: Listener<ExecutionStarted>, ...dtos: ExecutableClass[]): () => void;
23
+ onStart(listener: Listener<ExecutionStarted>, ...dtos: DtoKey[]): () => void;
23
24
  /** Hears every service that answered, in every bounded context. */
24
- onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: ExecutableClass[]): () => void;
25
+ onCompletion(listener: Listener<ExecutionCompleted>, ...dtos: DtoKey[]): () => void;
25
26
  /** Hears every failure that escapes a call, once, where it failed. */
26
- onFailure(listener: Listener<ExecutionFailed>, ...dtos: ExecutableClass[]): () => void;
27
+ onFailure(listener: Listener<ExecutionFailed>, ...dtos: DtoKey[]): () => void;
27
28
  };
28
29
  export {};
@@ -1,4 +1,4 @@
1
- import { listenIn, } from "../services/listening.js";
1
+ import { listenIn } from "../services/listening.js";
2
2
  /**
3
3
  * Who hears every bounded context of this process — the backend's process listeners: an
4
4
  * activity indicator, a toast, an audit that must not be wired into each context.
@@ -0,0 +1,44 @@
1
+ import { type AnyCommand, type CommandClass, type CommandDescriptor, DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable } from "../domain/dto.js";
2
+ /** How a DTO travels: a Command to one bus, by its identity; an event to N, by its wire name. */
3
+ export type DtoKind = "command" | "event";
4
+ /** What a DTO is known by: its kind, its class when it has one, and its wire identity when it has one. */
5
+ export type DtoIdentity = {
6
+ readonly kind: DtoKind;
7
+ /** The class it is an instance of; `undefined` for a generated DTO, which is data. */
8
+ readonly type: (abstract new (...args: never[]) => object) | undefined;
9
+ /** A Command's identity (`<context>.<Command>`), an event's wire name; `undefined` when none is declared. */
10
+ readonly wire: string | undefined;
11
+ };
12
+ export declare function isEventClass(key: unknown): key is EventClass<DomainEvent>;
13
+ export declare function isCommandClass(key: unknown): key is CommandClass<AnyCommand>;
14
+ export declare function isCommandDescriptor(key: unknown): key is CommandDescriptor;
15
+ export declare function isEventDescriptor(key: unknown): key is EventDescriptor;
16
+ /** Whether `key` is something a service can be registered for. */
17
+ export declare function isDtoKey(key: unknown): key is DtoKey;
18
+ /**
19
+ * What a registration key names:
20
+ *
21
+ * keyIdentity(CommandIssueInvoice) -> { kind: "command", type: CommandIssueInvoice, wire: "billing.CommandIssueInvoice" }
22
+ * keyIdentity(OrderPaid) -> { kind: "event", type: OrderPaid, wire: "shop.order.v1.paid" }
23
+ * keyIdentity(operations.CommandSendIssue) -> { kind: "command", type: undefined, wire: "project.CommandSendIssue" }
24
+ * keyIdentity(events.IssueClosed) -> { kind: "event", type: undefined, wire: "project.issue.v1.closed" }
25
+ */
26
+ export declare function keyIdentity(key: DtoKey): DtoIdentity;
27
+ /**
28
+ * What a value being executed is:
29
+ *
30
+ * 1. An instance of a Command or a domain event: its class, and the identity the class declares.
31
+ * 2. A generated Command (`commandOf`): the identity it carries.
32
+ * 3. A generated event: the wire name in its data.
33
+ * Final: `undefined` for anything else — nothing a bus executes.
34
+ */
35
+ export declare function identityOf(executable: unknown): DtoIdentity | undefined;
36
+ /**
37
+ * Whether `key` is what `executable` was registered under: the same class — exactly, a subclass
38
+ * is another DTO — or, for a generated DTO, the same kind and wire identity.
39
+ */
40
+ export declare function matches(key: DtoKey, executable: Executable): boolean;
41
+ /** Whether two values being executed are the same DTO: an interceptor passes on only that. */
42
+ export declare function sameDto(left: unknown, right: unknown): boolean;
43
+ /** A DTO's name for a message: its wire identity, or its class's name. */
44
+ export declare function describeDto(executable: unknown): string;