@sincpro/client-framework 2.3.0 → 2.5.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
@@ -70,12 +70,15 @@ module has only the layers it needs, and says what it offers in its own `index.t
70
70
  - **A service is a singleton of its generation.** What a method writes on `this` lands on the
71
71
  instance, shared by the next call, the call beside it and every `scoped` variant — as in
72
72
  sincpro_framework. What belongs to one request goes in its arguments or its context.
73
- - **A service's name is the framework's, taken at registration.** A standard decorator hands it
74
- the class's name as the code wrote it (`context.name`, untouched by a minifier); otherwise the
75
- class's `name` — so a production build keeps class names (`keep_classnames`, `keepNames`).
76
- `class Cancel` gives `project/Cancel`, identity `project.Cancel`. Nothing on a service declares
77
- it. Commands and events route by exact constructor identity — a generated one by its identity
78
- or wire name.
73
+ - **A service's name is the framework's, taken at registration.** The registration may give it
74
+ (`feature(dto, { name })`, `appService`, `handler` — a string literal, so a minifier never
75
+ touches it); else a standard decorator hands it the class's name as the code wrote it
76
+ (`context.name`, untouched by a minifier); otherwise the class's `name` — so a production build
77
+ keeps class names (`keep_classnames`, `keepNames`) or names each service (Next.js: legacy
78
+ decorators, no `keepNames`). `class Cancel` gives `project/Cancel`, identity `project.Cancel`.
79
+ Nothing on a service declares it, and `{ name }` stays optional: without it every form —
80
+ standard decorator, legacy decorator, a call — behaves as before. Commands and events route by
81
+ exact constructor identity — a generated one by its identity or wire name.
79
82
  - **An event's name is declared; a Command's identity is the framework's.** `static eventName` is
80
83
  required and dotted (`<context>.<aggregate>.vN.<fact>`); `name` is reserved for it. A Command's
81
84
  identity is given when a bounded context registers it — `<context>.<Command>`, the backend's
@@ -207,6 +210,12 @@ options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `r
207
210
  its optional entry, and nothing else imports one (`make doctor`).
208
211
  - **A span nothing records claims no trace.** OpenTelemetry's API with no provider answers an
209
212
  all-zeros span: the adapter gives no ids, so no `traceparent` of zeros reaches the server.
213
+ - **A run with no parent may start under the application's active span — only when asked.**
214
+ `openTelemetryTracer(tracer, { adoptActiveSpan: true })` reads `context.active()` for a span
215
+ given no parent, and nowhere else: a span given one (the run above, a delivered message) keeps
216
+ it, the framework never makes its own spans active (no `context.with`) and registers no context
217
+ manager — that is the application's (Node: what `NodeSDK` or `@vercel/otel` register, or
218
+ `AsyncLocalStorageContextManager`). Without one, as in a browser, it changes nothing.
210
219
  - **Reported means unexpected.** A `TransportError` the server answered with a 4xx is `refused`,
211
220
  an `AbortError` is `aborted`; neither is reported (`outcomeOf`). A bounded context adds its own
212
221
  with `expectErrors(...)`; a process replaces the rule with `ProcessOptions.outcomeOf`. Never
package/MANIFESTO.md CHANGED
@@ -23,11 +23,18 @@ The backend already answers how a use case is written, traced and reported. This
23
23
  every client the same answer, once: **a Feature written here runs in a browser, on a phone, in a
24
24
  server-side render, in a script and in a test, unchanged.**
25
25
 
26
+ And it serves many projects, not one. Each application chooses its shape — a single-page app, a
27
+ server render, both in one, a phone, a script —, its shell, its bundler and its style; this
28
+ package fixes only how a use case is written, run and observed, so every one of them is built
29
+ the same way underneath and read the same way when something goes wrong.
30
+
26
31
  ## What it is responsible for
27
32
 
28
33
  1. **Services.** A `Feature` executes a registered Command through `execute(dto)`;
29
34
  an `ApplicationService` composes its context's Features through `featureBus`, never another
30
- ApplicationService. Dependencies are typed attributes supplied by the bounded context.
35
+ ApplicationService. Dependencies are typed attributes supplied by the bounded context. A
36
+ service's name — what its span, its logs and its reports say — survives any build: where a
37
+ bundler renames classes, its registration gives it (`{ name }`).
31
38
  2. **Execution.** Every Command and event enters one execution pipeline, defined here: context,
32
39
  chain, span, log lines, outcome, report, error handlers — not handwritten by each service. An
33
40
  application changes it from outside through its extension points, as the backend's
@@ -38,7 +45,10 @@ server-side render, in a script and in a test, unchanged.**
38
45
  with its trace id; what the server already explained (a validation, a conflict), or what a
39
46
  bounded context declares expected, not reported.
40
47
  The platform plugs the implementation — OpenTelemetry, GlitchTip, a queue on the phone, memory
41
- in a test — once, for the process (`configureProcess`). Structured logs are tagged by layer
48
+ in a test — once, for the process (`configureProcess`). One trace crosses the platforms: a run
49
+ carries its `traceparent` to the server, and where the platform holds a span of its own — a
50
+ server render's request — a run can start under it (`adoptActiveSpan`), so a page, its reads
51
+ and what the backend did are one tree. Structured logs are tagged by layer
42
52
  (infrastructure, adapter, bounded context, ApplicationService, Feature) and by execution;
43
53
  console filtering never controls another sink's delivery.
44
54
  4. **Context.** The levels a call sees — the process, its bounded context, a scope — read once
@@ -131,6 +141,10 @@ server-side render, in a script and in a test, unchanged.**
131
141
  dependency it can avoid.
132
142
  9. **Grow by evidence.** Nothing before its second use; every change ships with a test that fails
133
143
  without it.
144
+ 10. **Grow without breaking.** A new capability arrives as an option, never as a change to what
145
+ exists. Every form keeps working — standard decorators, legacy decorators, the plain call —
146
+ on every platform and in every rendering: a single-page app, a server render, a phone. An
147
+ application upgrades by changing a version number; nothing is deprecated to make room.
134
148
 
135
149
  ## How it is composed
136
150
 
@@ -195,6 +209,11 @@ whatever backend — in the backend's kinds and next steps; retrying, setting as
195
209
  a screen's answer follow from it. A run can be cancelled, and its requests with it. The
196
210
  backend's circuit breaker guards any transport.
197
211
 
212
+ **A server render is one more client.** It runs the same use cases through the same pipeline;
213
+ its runs keep the names their registrations give, and nest under the request the server traces
214
+ when the application opts in. Nothing here knows which renderer, router or framework drew the
215
+ page.
216
+
198
217
  **Consumers have a guide.** The `sincpro-client-framework` skill says, for an application and for
199
218
  a platform's framework, what goes where and how each thing is done.
200
219
 
package/README.md CHANGED
@@ -79,10 +79,12 @@ only). A Response may be a class, a plain object, a page, a primitive or `void`.
79
79
  the bases every dependency typed on `this` — the backend's `class Feature(_Feature,
80
80
  DependencyContextType)` —; `addDependency` supplies them, and reading one never supplied fails.
81
81
  A replacement names what it replaces: `addDependency(name, next, { replaces: previous })`.
82
- - **The framework names a service when it registers it**: its class, as the code wrote it — a
83
- standard decorator hands the name over before any minifier runs —, else the class's `name`. A
84
- production build keeps class names (`keep_classnames` in Metro's minifier, `keepNames` in
85
- esbuild and Vite). Nothing on the class declares it.
82
+ - **The framework names a service when it registers it**: the name the registration gives
83
+ (`{ name: "Total" }`), else its class, as the code wrote it — a standard decorator hands the
84
+ name over before any minifier runs —, else the class's `name`. A production build keeps class
85
+ names (`keep_classnames` in Metro's minifier, `keepNames` in esbuild and Vite) or names each
86
+ service ([Names that survive a minifier](#names-that-survive-a-minifier)). Nothing on the class
87
+ declares it.
86
88
  - **One service, N DTOs.** `feature([CommandX, EventY])` registers one service for each, as the
87
89
  backend's `DTORegistration`; a DTO still has one service, across both layers, dispatched by
88
90
  its exact class — or, generated, by its identity.
@@ -106,6 +108,53 @@ called: `salesBoundedContext.feature(CommandTotal)(Total)`. No DI library and no
106
108
  where it is written; `services/index.ts` imports each file, so all are registered before anyone
107
109
  executes.
108
110
 
111
+ ### Names that survive a minifier
112
+
113
+ A service's name is what its spans, logs and reports say (`cursos/LeerCursos`), and what its
114
+ bounded context keys it by; an event handler's is also the consumer a stored queue acknowledges
115
+ (`app/OnCursoCreado`). Taken from the class, it is only as stable as the build: a production
116
+ minifier renames classes, so the same service reads `cursos/c5`, and two services renamed alike
117
+ collide — `Service name already registered: l` — and the application does not start.
118
+
119
+ A standard decorator hands over the name as written (`context.name`), and Vite and Metro can keep
120
+ class names. Next.js can do neither: its compiler lowers standard decorators in a version this
121
+ package does not read, so an application on Next uses legacy decorators
122
+ (`experimentalDecorators`), which hand over no name, and it has no `keepNames`. There — or
123
+ anywhere a build renames classes — the registration gives the name, a string literal no minifier
124
+ touches:
125
+
126
+ ```ts
127
+ @cursosBoundedContext.feature(CommandLeerCursos, { name: "LeerCursos" })
128
+ class LeerCursos extends Feature<CommandLeerCursos, ResponseCursos> { … }
129
+
130
+ @cursosBoundedContext.appService(CommandInscribir, { name: "Inscribir" })
131
+ class Inscribir extends ApplicationService<CommandInscribir, ResponseInscripcion> { … }
132
+
133
+ @appSubscriber.handler([CursoCreado], { name: "AvisarCursoCreado" })
134
+ class AvisarCursoCreado extends EventHandler<CursoCreado> { … }
135
+
136
+ class CommandLeerCursos extends Command<ResponseCursos> {
137
+ static readonly commandName = "cursos.CommandLeerCursos"; // its identity, likewise
138
+ }
139
+ ```
140
+
141
+ - **Precedence:** `{ name }`, then a standard decorator's `context.name`, then the class's
142
+ `name`. Without `{ name }` nothing changes, in any of the three forms (standard decorator,
143
+ legacy decorator, a call).
144
+ - **It is a class's name:** an identifier (`LeerCursos`, `AñadirCurso`) — never `cursos/leer` or
145
+ `leer cursos` —, unique in its bounded context or subscriber, as a class's is; refused where the
146
+ registration is written otherwise. With `replaces`, the replacement says the name it replaced.
147
+ - **The same in every realm.** It is a string in the module, nothing read from the platform: a
148
+ browser and a server rendering the same modules (SSR, React server components) name the
149
+ service alike.
150
+ - **A Command's identity comes from its class's name too** (`<context>.<Command>`): a Command
151
+ that must keep it under a minifier — two renamed alike collide as
152
+ `Command identity already registered` — declares `static commandName`. An event's wire name is
153
+ always declared (`eventName`).
154
+
155
+ The tests lower legacy decorators with TypeScript and minify with Vite's own minifier, and read
156
+ the names back from the spans.
157
+
109
158
  ### Replacing a service
110
159
 
111
160
  An application takes the place of a service a module registered, as the backend's `replaces=`:
@@ -260,7 +309,8 @@ await appSubscriber.receive(message); // CloudEvents, structured or { headers, b
260
309
  the ones that do not have it yet.
261
310
  - **A handler** runs in the pipeline of a use case, in its own layer (`event_handler`): its span
262
311
  `<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
312
+ executes is its child. `<owner>/<Handler>` is the key a stored queue keeps: a build that renames
313
+ classes names it (`handler([SalePaid], { name: "OnSalePaid" })`). A handler takes N events: its type is their union, and TypeScript checks
264
314
  it accepts every event listed.
265
315
  - **A Command** is executed by the one bounded context that registered it, continuing the
266
316
  message's flow — **only when declared** (`commands`). A bus never hands all its Commands to
@@ -531,11 +581,43 @@ name: an application's own object (an Odoo client with a `call`) reaches its use
531
581
  ignored: telling about a use case never changes its answer.
532
582
 
533
583
  The vendor entries wrap what the application built — they initialize nothing, read no
534
- environment and register nothing global. There is no context manager: the trace reaches the
584
+ environment and register nothing global. No context manager is needed: the trace reaches the
535
585
  wire through the transport. On the web, leave the backend's origin out of OpenTelemetry's
536
586
  automatic `fetch` instrumentation (`ignoreUrls`), or it writes a `traceparent` of a trace of its
537
587
  own over this one.
538
588
 
589
+ ### One trace from a server render
590
+
591
+ A run's parent is the run above it, or the message it continues — never what is active in
592
+ OpenTelemetry's context —, so a use case with neither starts a trace of its own. A server that
593
+ renders pages (Next.js) keeps a span of its own active while it renders; to have the use cases
594
+ the render runs start under it — one trace: render → use case → API —, opt in:
595
+
596
+ ```ts
597
+ import { context } from "@opentelemetry/api";
598
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
599
+
600
+ // once, where the server registers its provider — NodeSDK and @vercel/otel already do this
601
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
602
+
603
+ configureProcess({
604
+ tracer: openTelemetryTracer(provider.getTracer("forge-web"), { adoptActiveSpan: true }),
605
+ });
606
+ ```
607
+
608
+ - **Only a run with no parent reads the active span.** A Feature under its ApplicationService, a
609
+ bounded context injected into a run, a run continuing a delivered message keep the parent they
610
+ are given — the active span is never mixed in —, and the framework never makes its own spans
611
+ active, so two renders at once never take each other's use cases. It is the backend's rule at
612
+ its root: sincpro_framework's use case is a child of the span active in its process.
613
+ - **It reads what the application registered, and registers nothing.** On Node that is a context
614
+ manager: `NodeSDK` and `@vercel/otel` register one; a bare `TracerProvider` does not, and then
615
+ the application registers `AsyncLocalStorageContextManager` itself, as above. Without one the
616
+ active context is the root and the option changes nothing.
617
+ - **In a browser it is harmless.** With no context manager registered (`browserTracer` registers
618
+ none) every root run starts its own trace, as without the option.
619
+ - **Off by default.** `openTelemetryTracer(tracer)` behaves as it always has.
620
+
539
621
  ### Logging
540
622
 
541
623
  The application layer imports no logger. Two are predefined, for the code around the use cases:
@@ -129,3 +129,12 @@ export declare function handlersWith<D extends object, Context extends object =
129
129
  };
130
130
  /** @internal — what a run finds on `this` that no dependency may take. */
131
131
  export declare const RESERVED_MEMBERS: ReadonlySet<string>;
132
+ /**
133
+ * @internal — the name a registration gives its service or event handler, or `undefined` when
134
+ * it gives none (the framework then takes the class's). A string literal: no minifier rewrites
135
+ * it, and every realm that evaluates the module — a browser, a server rendering it — reads the
136
+ * same one.
137
+ */
138
+ export declare function givenNameOf(options: {
139
+ readonly name?: unknown;
140
+ } | undefined): string | undefined;
@@ -88,3 +88,25 @@ export const RESERVED_MEMBERS = new Set([
88
88
  "signal",
89
89
  "execution",
90
90
  ]);
91
+ /**
92
+ * A name given at registration (`{ name }`): it stands where a class's name would, so it is one —
93
+ * an identifier, as `LeerCursos` —, with no `/` or `.` inside the span's `<context>/<Name>`, the
94
+ * use case's `<context>.<Name>` or the consumer a stored queue acknowledges (`<owner>/<Name>`).
95
+ */
96
+ const SERVICE_NAME = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u;
97
+ /**
98
+ * @internal — the name a registration gives its service or event handler, or `undefined` when
99
+ * it gives none (the framework then takes the class's). A string literal: no minifier rewrites
100
+ * it, and every realm that evaluates the module — a browser, a server rendering it — reads the
101
+ * same one.
102
+ */
103
+ export function givenNameOf(options) {
104
+ const name = options?.name;
105
+ if (name === undefined)
106
+ return undefined;
107
+ if (typeof name !== "string" || !SERVICE_NAME.test(name)) {
108
+ const shown = typeof name === "string" ? JSON.stringify(name) : String(name);
109
+ throw new TypeError(`${shown} is not a service's name: an identifier, as its class would be called (LeerCursos)`);
110
+ }
111
+ return name;
112
+ }
@@ -7,7 +7,7 @@ import { type Answer, type AnyCommand, type Command, type CommandClass, type Com
7
7
  import type { ErrorClass, ErrorHandler } from "../domain/errors.js";
8
8
  import type { Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, Interceptor, Listener } from "../domain/pipeline.js";
9
9
  import { type HandledEvent } from "../domain/services.js";
10
- import { type HandlerRegistrar } from "../services/event-handlers.js";
10
+ import { type HandlerOptions, type HandlerRegistrar } from "../services/event-handlers.js";
11
11
  import type { LayerLogger } from "../../observability/domain/logging.js";
12
12
  interface Executor<C extends Executable, R> {
13
13
  execute(executable: C): R | Promise<R>;
@@ -15,9 +15,18 @@ interface Executor<C extends Executable, R> {
15
15
  type ServiceClass<C extends Executable, R> = new () => Executor<C, R>;
16
16
  /** What a registration is for when it names none: everything; else the DTOs it names. */
17
17
  type Of<K> = [K] extends [never] ? Executable : ExecutableOf<K>;
18
- /** The service a registration takes the place of, as the backend's `replaces=`. */
18
+ /** How a service is registered: what it takes the place of, and what it is called. */
19
19
  export type RegistrationOptions = {
20
+ /** The service registered now that this one takes the place of, as the backend's `replaces=`. */
20
21
  replaces?: abstract new (...args: never[]) => object;
22
+ /**
23
+ * Its name — what its spans, logs and reports say, and what this bounded context keys it by
24
+ * —, given as a string literal so no minifier rewrites it: an identifier, as its class would be
25
+ * called (`"LeerCursos"`). Without it, a standard decorator's `context.name`, else the class's
26
+ * `name`, as always. A build that renames classes and registers with legacy decorators
27
+ * (`experimentalDecorators`) or a call — Next.js, which has no `keepNames` — gives it.
28
+ */
29
+ name?: string;
21
30
  };
22
31
  /** What `feature(...)` and `appService(...)` answer: the function that registers the service. */
23
32
  export type Registrar<T extends Executable> = <S extends ServiceClass<NoInfer<T>, Answer<NoInfer<T>>>>(Service: S, decorator?: ClassDecoratorContext<S>) => S;
@@ -68,10 +77,14 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
68
77
  * Registers the Feature that executes a DTO — or each DTO listed, as the backend's
69
78
  * `feature([CommandX, EventY])`: a Command's class, a domain event's (the use case of the event:
70
79
  * 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.
80
+ * With `replaces`, it takes the place of the service registered now for each; with `name`, it
81
+ * is called that instead of its class's name — which a minifier rewrites.
72
82
  *
73
83
  * @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid])
74
84
  * class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
85
+ *
86
+ * @cursosBoundedContext.feature(CommandLeerCursos, { name: "LeerCursos" })
87
+ * class LeerCursos extends Feature<CommandLeerCursos, ResponseCursos> { … }
75
88
  */
76
89
  feature<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
77
90
  feature<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
@@ -96,11 +109,12 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
96
109
  * salesBoundedContext.handler([SalePaid, SaleCancelled])(OnSaleChanged);
97
110
  *
98
111
  * An event may have its use case and N handlers here; each is its own consumer
99
- * (`sales/OnSaleChanged`), acknowledged apart by the queue.
112
+ * (`sales/OnSaleChanged`), acknowledged apart by the queue — by that name, so a build that
113
+ * renames classes gives it one: `handler([SalePaid], { name: "OnSaleChanged" })`.
100
114
  */
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>;
115
+ handler<const K extends readonly EventKey[]>(events: K, options?: HandlerOptions): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
116
+ handler<E extends DomainEvent>(event: EventClass<E>, options?: HandlerOptions): HandlerRegistrar<E>;
117
+ handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: HandlerOptions): HandlerRegistrar<E>;
104
118
  /** The service registered now for a DTO — what a `replaces` names. */
105
119
  handlerOf(dto: DtoKey): (abstract new (...args: never[]) => object) | undefined;
106
120
  /**
@@ -180,9 +194,10 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
180
194
  * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
181
195
  * class, or a generated one's entry.
182
196
  * 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
197
+ * 3. Its name is the one its registration gives (`{ name }`, a string no minifier touches); else
198
+ * the framework's to take, at registration: the class's name as the code wrote it (a standard
199
+ * decorator's `context.name`, which a minifier does not touch), else the class's `name` — a
200
+ * production build keeps class names (`keep_classnames`, `keepNames`) or names it. No other
186
201
  * service here has it; the same service may take N DTOs.
187
202
  * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
188
203
  * it declares one, likewise: a name or an identity means one DTO.
@@ -3,7 +3,7 @@ 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
5
  import { EVENT_NAME, } from "../domain/dto.js";
6
- import { ApplicationService, Feature, RESERVED_MEMBERS, } from "../domain/services.js";
6
+ import { ApplicationService, Feature, givenNameOf, RESERVED_MEMBERS, } from "../domain/services.js";
7
7
  import { processHearing } from "../infrastructure/listeners.js";
8
8
  import { bindDependency } from "../services/binding.js";
9
9
  import { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
@@ -121,9 +121,9 @@ export class BoundedContext {
121
121
  appService(dto, options) {
122
122
  return this.registrar(dto, "application_service", options);
123
123
  }
124
- handler(events) {
124
+ handler(events, options) {
125
125
  const keys = eventKeysOf(events);
126
- return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys));
126
+ return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys), options);
127
127
  }
128
128
  /** The service registered now for a DTO — what a `replaces` names. */
129
129
  handlerOf(dto) {
@@ -326,14 +326,16 @@ export class BoundedContext {
326
326
  const dtos = Array.isArray(dto) ? dto : [dto];
327
327
  if (dtos.length === 0)
328
328
  throw new TypeError("A service is registered for one DTO at least");
329
+ const given = givenNameOf(options);
329
330
  return (Service, decorator) => {
330
331
  // All the DTOs listed, or none: a refused one leaves the registrations as they were.
331
332
  const register = () => {
332
333
  const before = [...this.registrations];
333
334
  const revision = this.revision;
335
+ const written = given ?? decorator?.name;
334
336
  try {
335
337
  for (const one of dtos)
336
- this.registerService(one, Service, layer, options.replaces, decorator?.name);
338
+ this.registerService(one, Service, layer, options.replaces, written);
337
339
  }
338
340
  catch (error) {
339
341
  this.registrations.clear();
@@ -355,9 +357,10 @@ export class BoundedContext {
355
357
  * 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
356
358
  * class, or a generated one's entry.
357
359
  * 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
360
+ * 3. Its name is the one its registration gives (`{ name }`, a string no minifier touches); else
361
+ * the framework's to take, at registration: the class's name as the code wrote it (a standard
362
+ * decorator's `context.name`, which a minifier does not touch), else the class's `name` — a
363
+ * production build keeps class names (`keep_classnames`, `keepNames`) or names it. No other
361
364
  * service here has it; the same service may take N DTOs.
362
365
  * 4. An event's wire name is given, and no other event here has it; a Command's identity, when
363
366
  * it declares one, likewise: a name or an identity means one DTO.
@@ -22,4 +22,4 @@ export { BoundedContext, type Registrar, type RegistrationOptions, } from "./ent
22
22
  export { screensTransport } from "./entrypoint/screens.js";
23
23
  export { processListeners } from "./infrastructure/listeners.js";
24
24
  export { configureLogger, configureProcess, type LoggerConfiguration, processIdentity, type ProcessOptions, } from "./infrastructure/process.js";
25
- export type { HandlerRegistrar } from "./services/event-handlers.js";
25
+ export type { HandlerOptions, HandlerRegistrar, } from "./services/event-handlers.js";
@@ -26,12 +26,23 @@ export type HandlerRegistrar<E extends HandledEvent> = <S extends new () => {
26
26
  * event's entry, with a valid wire name, none twice.
27
27
  */
28
28
  export declare function eventKeysOf(events: EventKey | readonly EventKey[]): readonly EventKey[];
29
+ /** How an event handler is registered: what it is called. */
30
+ export type HandlerOptions = {
31
+ /**
32
+ * Its name — `<owner>/<Name>` on its spans and logs, and the consumer a stored queue
33
+ * acknowledges —, given as a string literal so no minifier rewrites it: an identifier, as its
34
+ * class would be called (`"OnSaleChanged"`). Without it, a standard decorator's
35
+ * `context.name`, else the class's `name`, as always.
36
+ */
37
+ name?: string;
38
+ };
29
39
  /**
30
40
  * Registers `Handler` with `register`, at once or — applied as a standard decorator — once its
31
- * class is defined; its name is the class's as the code wrote it (a decorator's `context.name`,
32
- * untouched by a minifier), else its `name`.
41
+ * class is defined; its name is the one `options` gives (a string, untouched by a minifier),
42
+ * else the class's as the code wrote it (a decorator's `context.name`, untouched too), else its
43
+ * `name`.
33
44
  */
34
- export declare function handlerRegistrar<E extends HandledEvent>(register: (Handler: HandlerClass, name: string) => void): HandlerRegistrar<E>;
45
+ export declare function handlerRegistrar<E extends HandledEvent>(register: (Handler: HandlerClass, name: string) => void, options?: HandlerOptions): HandlerRegistrar<E>;
35
46
  /** Whether a handler registered for `key` handles the event `known` identifies. */
36
47
  export declare function handles(key: EventKey, known: DtoIdentity): boolean;
37
48
  /** What a run of an event handler needs besides the handler and the event. */
@@ -1,5 +1,5 @@
1
1
  import { EVENT_NAME } from "../domain/dto.js";
2
- import { EventHandler, } from "../domain/services.js";
2
+ import { EventHandler, givenNameOf, } from "../domain/services.js";
3
3
  import { isEventClass, isEventDescriptor, keyIdentity, } from "./dto-keys.js";
4
4
  import { executeService, failedAt, } from "./execution.js";
5
5
  import { observabilityNow } from "../../observability/infrastructure/registry.js";
@@ -28,16 +28,18 @@ export function eventKeysOf(events) {
28
28
  }
29
29
  /**
30
30
  * Registers `Handler` with `register`, at once or — applied as a standard decorator — once its
31
- * class is defined; its name is the class's as the code wrote it (a decorator's `context.name`,
32
- * untouched by a minifier), else its `name`.
31
+ * class is defined; its name is the one `options` gives (a string, untouched by a minifier),
32
+ * else the class's as the code wrote it (a decorator's `context.name`, untouched too), else its
33
+ * `name`.
33
34
  */
34
- export function handlerRegistrar(register) {
35
+ export function handlerRegistrar(register, options) {
36
+ const given = givenNameOf(options);
35
37
  return (Handler, decorator) => {
36
38
  const take = () => {
37
39
  if (!(Handler.prototype instanceof EventHandler)) {
38
40
  throw new TypeError("An event handler extends EventHandler");
39
41
  }
40
- const name = decorator?.name ?? Handler.name;
42
+ const name = given ?? decorator?.name ?? Handler.name;
41
43
  if (typeof name !== "string" || name.trim() === "") {
42
44
  throw new Error("An event handler is a named class: its name is said in spans and logs");
43
45
  }
@@ -2,7 +2,7 @@ import type { EventConsumer, EventKey } from "../../core/domain/consumers.js";
2
2
  import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, ExecutableOf, RemoteCommand, RemoteEvent } from "../../core/domain/dto.js";
3
3
  import type { Cause, ExecuteOptions } from "../../core/domain/pipeline.js";
4
4
  import { type HandledEvent } from "../../core/domain/services.js";
5
- import { type HandlerRegistrar } from "../../core/services/event-handlers.js";
5
+ import { type HandlerOptions, type HandlerRegistrar } from "../../core/services/event-handlers.js";
6
6
  import type { Envelope } from "../domain/envelope.js";
7
7
  import type { BinaryMessage, Message } from "../domain/messages.js";
8
8
  import type { CommandType, EventType, Handled, Subscribes } from "../domain/queue.js";
@@ -99,10 +99,13 @@ export declare class Subscriber<D extends object = Record<never, never>> impleme
99
99
  * export class OnSaleChanged extends EventHandler<SalePaid | SaleCancelled> { … }
100
100
  *
101
101
  * appSubscriber.handler([SalePaid, SaleCancelled])(OnSaleChanged);
102
+ *
103
+ * Its name (`app/OnSaleChanged`) is the consumer the stored queue acknowledges: a build that
104
+ * renames classes gives it one, `handler([SalePaid], { name: "OnSaleChanged" })`.
102
105
  */
103
- handler<const K extends readonly EventKey[]>(events: K): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
104
- handler<E extends DomainEvent>(event: EventClass<E>): HandlerRegistrar<E>;
105
- handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor): HandlerRegistrar<E>;
106
+ handler<const K extends readonly EventKey[]>(events: K, options?: HandlerOptions): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
107
+ handler<E extends DomainEvent>(event: EventClass<E>, options?: HandlerOptions): HandlerRegistrar<E>;
108
+ handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: HandlerOptions): HandlerRegistrar<E>;
106
109
  /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
107
110
  eventTypeOf(name: string): EventType | undefined;
108
111
  /** What a consumed Command of that identity is rebuilt as, or `undefined` when it is not consumed here. */
@@ -148,7 +148,7 @@ export class Subscriber {
148
148
  this.buses.push({ context: boundedContext, key });
149
149
  return this;
150
150
  }
151
- handler(events) {
151
+ handler(events, options) {
152
152
  const keys = eventKeysOf(events);
153
153
  return handlerRegistrar((Handler, name) => {
154
154
  if (this.name === "") {
@@ -161,7 +161,7 @@ export class Subscriber {
161
161
  throw new Error(`Event handler name already registered: ${name}`);
162
162
  }
163
163
  this.handlers.push({ name, Handler, events: keys });
164
- });
164
+ }, options);
165
165
  }
166
166
  /** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
167
167
  eventTypeOf(name) {
@@ -1,5 +1,24 @@
1
1
  import { type Tracer as OtelTracer } from "@opentelemetry/api";
2
2
  import type { Tracer } from "../domain/tracing.js";
3
+ /** How `openTelemetryTracer` places a use case's span. Every option is off by default. */
4
+ export type OpenTelemetryTracerOptions = {
5
+ /**
6
+ * A span given no parent — a run with no run above it and no delivered message to continue —
7
+ * starts in OpenTelemetry's active context, a child of the span active there: a use case run
8
+ * while a server renders a page is a child of the render, one trace from the page to the API,
9
+ * as sincpro_framework's use case is a child of the span active in its process. A span given a
10
+ * parent keeps it, always — the active span is never mixed in —, and the framework never makes
11
+ * its own spans active, so two runs at once never take each other's. Default `false`: a run
12
+ * with no parent starts a trace of its own, whatever is active.
13
+ *
14
+ * It reads what the application registered and registers nothing. On Node that is a context
15
+ * manager: `AsyncLocalStorageContextManager` from `@opentelemetry/context-async-hooks`, or the
16
+ * one its SDK registers (`NodeSDK`, `@vercel/otel`). Without one the active context is the
17
+ * root and this changes nothing — so in a browser that registers none it is harmless; one that
18
+ * does (`ZoneContextManager`) has a root run start under the span active where it is executed.
19
+ */
20
+ readonly adoptActiveSpan?: boolean;
21
+ };
3
22
  /**
4
23
  * The `Tracer` port over OpenTelemetry's API: every use case a span of whatever provider the
5
24
  * platform registered.
@@ -8,14 +27,20 @@ import type { Tracer } from "../domain/tracing.js";
8
27
  * const tracer = openTelemetryTracer(provider.getTracer("forge-web"));
9
28
  * configureProcess({ tracer });
10
29
  *
30
+ * // a server that renders pages (Next.js), with a context manager registered: a use case
31
+ * // the render runs is a child of the render's span
32
+ * openTelemetryTracer(provider.getTracer("forge-web"), { adoptActiveSpan: true });
33
+ *
11
34
  * Context: only `@opentelemetry/api`, which runs the same on every platform — the provider, its
12
35
  * exporter and where it sends are the platform's (the browser's OTLP over fetch, a phone's
13
36
  * queue, a server's SDK). An optional entry with an optional peer: an application that does not
14
37
  * import it installs nothing and ships nothing.
15
38
  *
16
- * The parent is given, never read from OpenTelemetry's context: a run carries its own execution
17
- * (`Execution`), so two use cases at once never take each other's span, and no context manager
18
- * (Zone.js) is needed. A span nothing records (a sampler said no, no provider registered)
19
- * answers no ids — so no `traceparent` claims a trace that does not exist.
39
+ * The parent is given — the run above, the message a run continues —, never read from
40
+ * OpenTelemetry's context: a run carries its own execution (`Execution`), so two use cases at
41
+ * once never take each other's span, and no context manager (Zone.js) is needed. A run given
42
+ * none starts a trace of its own; the one place the active context is read is there, and only
43
+ * when the application asks (`adoptActiveSpan`). A span nothing records (a sampler said no, no
44
+ * provider registered) answers no ids — so no `traceparent` claims a trace that does not exist.
20
45
  */
21
- export declare function openTelemetryTracer(tracer: OtelTracer): Tracer;
46
+ export declare function openTelemetryTracer(tracer: OtelTracer, { adoptActiveSpan }?: OpenTelemetryTracerOptions): Tracer;
@@ -1,4 +1,4 @@
1
- import { isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, TraceFlags, } from "@opentelemetry/api";
1
+ import { context as otelContext, isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, TraceFlags, } from "@opentelemetry/api";
2
2
  /**
3
3
  * The `Tracer` port over OpenTelemetry's API: every use case a span of whatever provider the
4
4
  * platform registered.
@@ -7,32 +7,29 @@ import { isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, Trac
7
7
  * const tracer = openTelemetryTracer(provider.getTracer("forge-web"));
8
8
  * configureProcess({ tracer });
9
9
  *
10
+ * // a server that renders pages (Next.js), with a context manager registered: a use case
11
+ * // the render runs is a child of the render's span
12
+ * openTelemetryTracer(provider.getTracer("forge-web"), { adoptActiveSpan: true });
13
+ *
10
14
  * Context: only `@opentelemetry/api`, which runs the same on every platform — the provider, its
11
15
  * exporter and where it sends are the platform's (the browser's OTLP over fetch, a phone's
12
16
  * queue, a server's SDK). An optional entry with an optional peer: an application that does not
13
17
  * import it installs nothing and ships nothing.
14
18
  *
15
- * The parent is given, never read from OpenTelemetry's context: a run carries its own execution
16
- * (`Execution`), so two use cases at once never take each other's span, and no context manager
17
- * (Zone.js) is needed. A span nothing records (a sampler said no, no provider registered)
18
- * answers no ids — so no `traceparent` claims a trace that does not exist.
19
+ * The parent is given — the run above, the message a run continues —, never read from
20
+ * OpenTelemetry's context: a run carries its own execution (`Execution`), so two use cases at
21
+ * once never take each other's span, and no context manager (Zone.js) is needed. A run given
22
+ * none starts a trace of its own; the one place the active context is read is there, and only
23
+ * when the application asks (`adoptActiveSpan`). A span nothing records (a sampler said no, no
24
+ * provider registered) answers no ids — so no `traceparent` claims a trace that does not exist.
19
25
  */
20
- export function openTelemetryTracer(tracer) {
26
+ export function openTelemetryTracer(tracer, { adoptActiveSpan = false } = {}) {
21
27
  return {
22
28
  start(name, options) {
23
- const parent = options.parent;
24
- const parentContext = parent !== undefined && parent.traceId !== "" && parent.spanId !== ""
25
- ? trace.setSpanContext(ROOT_CONTEXT, {
26
- traceId: parent.traceId,
27
- spanId: parent.spanId,
28
- traceFlags: parent.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
29
- isRemote: false,
30
- })
31
- : ROOT_CONTEXT;
32
29
  const span = tracer.startSpan(name, {
33
30
  kind: SpanKind.INTERNAL,
34
31
  ...(options.attributes ? { attributes: options.attributes } : {}),
35
- }, parentContext);
32
+ }, parentContextOf(options.parent, adoptActiveSpan));
36
33
  const own = span.spanContext();
37
34
  const valid = isSpanContextValid(own);
38
35
  const state = own.traceState?.serialize();
@@ -47,6 +44,23 @@ export function openTelemetryTracer(tracer) {
47
44
  },
48
45
  };
49
46
  }
47
+ /**
48
+ * Where a span starts. Given a parent, under it — at the root when that parent traces nothing —,
49
+ * never in the active context: the run above, or the message it continues, is its parent. Given
50
+ * none, in the active context when the application asked for it, else at the root.
51
+ */
52
+ function parentContextOf(parent, adoptActiveSpan) {
53
+ if (parent === undefined)
54
+ return adoptActiveSpan ? otelContext.active() : ROOT_CONTEXT;
55
+ if (parent.traceId === "" || parent.spanId === "")
56
+ return ROOT_CONTEXT;
57
+ return trace.setSpanContext(ROOT_CONTEXT, {
58
+ traceId: parent.traceId,
59
+ spanId: parent.spanId,
60
+ traceFlags: parent.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
61
+ isRemote: false,
62
+ });
63
+ }
50
64
  /**
51
65
  * How the use case ended, said the way OpenTelemetry reads it: `failed` is an error — with its
52
66
  * exception on the span where it was raised, the only one handed it —; `refused` and `aborted`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -98,6 +98,7 @@
98
98
  "devDependencies": {
99
99
  "@eslint/js": "^10.0.1",
100
100
  "@opentelemetry/api": "1.10.0",
101
+ "@opentelemetry/context-async-hooks": "3.1.0",
101
102
  "@opentelemetry/sdk-trace": "3.1.0",
102
103
  "@sincpro/criteria": "^2.1.0",
103
104
  "@types/node": "^26.6.6",