@sincpro/client-framework 1.1.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 (53) hide show
  1. package/AGENTS.md +51 -17
  2. package/MANIFESTO.md +9 -7
  3. package/README.md +261 -131
  4. package/dist/client/services/guarded.d.ts +1 -1
  5. package/dist/client/services/propagation.js +4 -3
  6. package/dist/codegen/services/scaffold.d.ts +12 -10
  7. package/dist/codegen/services/scaffold.js +29 -51
  8. package/dist/context/entrypoint/context.d.ts +5 -4
  9. package/dist/core/domain/bus.d.ts +5 -3
  10. package/dist/core/domain/bus.js +8 -1
  11. package/dist/core/domain/dto.d.ts +71 -9
  12. package/dist/core/domain/dto.js +25 -5
  13. package/dist/core/domain/errors.d.ts +2 -2
  14. package/dist/core/domain/pipeline.d.ts +8 -5
  15. package/dist/core/domain/services.d.ts +40 -13
  16. package/dist/core/domain/services.js +31 -7
  17. package/dist/core/entrypoint/bounded-context.d.ts +71 -41
  18. package/dist/core/entrypoint/bounded-context.js +155 -56
  19. package/dist/core/entrypoint/screens.js +0 -5
  20. package/dist/core/index.d.ts +4 -3
  21. package/dist/core/index.js +4 -3
  22. package/dist/core/infrastructure/listeners.d.ts +6 -5
  23. package/dist/core/infrastructure/listeners.js +2 -2
  24. package/dist/core/services/dto-keys.d.ts +44 -0
  25. package/dist/core/services/dto-keys.js +97 -0
  26. package/dist/core/services/execution.d.ts +15 -10
  27. package/dist/core/services/execution.js +36 -23
  28. package/dist/core/services/interceptors.d.ts +2 -2
  29. package/dist/core/services/interceptors.js +5 -5
  30. package/dist/core/services/listening.d.ts +6 -8
  31. package/dist/core/services/listening.js +3 -2
  32. package/dist/event_driven/adapters/stored-queue.d.ts +8 -7
  33. package/dist/event_driven/adapters/stored-queue.js +8 -12
  34. package/dist/event_driven/domain/envelope.d.ts +2 -2
  35. package/dist/event_driven/domain/envelope.js +7 -1
  36. package/dist/event_driven/domain/messages.d.ts +34 -0
  37. package/dist/event_driven/domain/messages.js +1 -0
  38. package/dist/event_driven/domain/queue.d.ts +9 -5
  39. package/dist/event_driven/entrypoint/publisher.d.ts +3 -3
  40. package/dist/event_driven/entrypoint/publisher.js +5 -1
  41. package/dist/event_driven/entrypoint/subscriber.d.ts +66 -19
  42. package/dist/event_driven/entrypoint/subscriber.js +122 -15
  43. package/dist/event_driven/index.d.ts +11 -7
  44. package/dist/event_driven/index.js +9 -6
  45. package/dist/event_driven/services/messages.d.ts +41 -0
  46. package/dist/event_driven/services/messages.js +147 -0
  47. package/dist/observability/adapters/memory.d.ts +1 -1
  48. package/dist/observability/domain/logging.d.ts +2 -2
  49. package/dist/observability/services/logging.d.ts +6 -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
package/README.md CHANGED
@@ -20,151 +20,222 @@ platform storage: what a platform must give, it gives through a port.
20
20
 
21
21
  ## A bounded context
22
22
 
23
+ Laid out as a backend's context (`sincpro_mcp_odoo/domains/helpdesk`): what its services count on
24
+ (`dependencies.ts`), its bases and its instance (`framework.ts`), and one file per use case.
25
+
23
26
  ```ts
24
- import {
25
- ApplicationService,
26
- BoundedContext,
27
- Command,
28
- Feature,
29
- Response,
30
- } from "@sincpro/client-framework";
31
-
32
- class ResponseTotal extends Response {
33
- constructor(readonly total: number) {
34
- super();
35
- }
27
+ // domains/sales/infrastructure/dependencies.ts — the backend's DependencyContextType
28
+ export interface SalesDependencies {
29
+ prices: PriceList;
30
+ taxRate: number;
36
31
  }
37
-
38
- class CommandTotal extends Command<ResponseTotal> {
39
- constructor(readonly quantity: number) {
40
- super();
41
- }
32
+ export function registerDependencies(boundedContext: BoundedContext<SalesDependencies>) {
33
+ boundedContext.addDependency("prices", new PriceList());
34
+ boundedContext.addDependency("taxRate", 0.13);
35
+ return boundedContext;
42
36
  }
43
37
 
44
- class CommandQuote extends Command<ResponseTotal> {
45
- constructor(readonly quantity: number) {
38
+ // domains/sales/infrastructure/framework.ts — the bases inherit every dependency, typed
39
+ export const { Feature, ApplicationService } = servicesWith<SalesDependencies>();
40
+ export const salesBoundedContext = registerDependencies(
41
+ new BoundedContext<SalesDependencies>("sales"),
42
+ );
43
+
44
+ // domains/sales/services/quote/total.feature.ts
45
+ export class CommandTotal extends Command<ResponseTotal> {
46
+ constructor(
47
+ readonly sku: string,
48
+ readonly quantity: number,
49
+ ) {
46
50
  super();
47
51
  }
48
52
  }
49
53
 
50
- class Total extends Feature<CommandTotal, ResponseTotal> {
51
- static readonly serviceName = "Total";
52
- declare readonly unitPrice: number; // a dependency, typed
53
-
54
+ @salesBoundedContext.feature(CommandTotal)
55
+ export class Total extends Feature<CommandTotal, ResponseTotal> {
54
56
  execute(command: CommandTotal): ResponseTotal {
55
57
  this.logger.info("Totalling", { quantity: command.quantity });
56
- return new ResponseTotal(command.quantity * this.unitPrice);
58
+ const unit = this.prices.of(command.sku) * (1 + this.taxRate); // declared nowhere else
59
+ return new ResponseTotal(unit * command.quantity);
57
60
  }
58
61
  }
59
62
 
60
- class Quote extends ApplicationService<CommandQuote, ResponseTotal> {
61
- static readonly serviceName = "Quote";
62
-
63
+ // domains/sales/services/quote/quote.app-service.ts
64
+ @salesBoundedContext.appService(CommandQuote)
65
+ export class Quote extends ApplicationService<CommandQuote, ResponseTotal> {
63
66
  execute(command: CommandQuote): Promise<ResponseTotal> {
64
- return this.featureBus.execute(new CommandTotal(command.quantity));
67
+ return this.featureBus.execute(new CommandTotal(command.sku, command.quantity));
65
68
  }
66
69
  }
67
70
 
68
- const sales = new BoundedContext<{ unitPrice: number }>("sales");
69
- sales.addDependency("unitPrice", 10);
70
- sales.feature(CommandTotal)(Total);
71
- sales.appService(CommandQuote)(Quote);
72
-
73
- const answer = await sales.execute(new CommandQuote(3)); // ResponseTotal — total 30
71
+ const answer = await salesBoundedContext.execute(new CommandQuote("a1", 3)); // ResponseTotal
74
72
  ```
75
73
 
76
74
  A Command names, by its type, the Response it answers: `execute` infers it, with no second
77
75
  argument (the backend's `bus(dto, ResponseType)` is accepted too, and checked in TypeScript
78
76
  only). A Response may be a class, a plain object, a page, a primitive or `void`.
79
77
 
80
- - **One Command, one service.** A Command class is registered once, across both layers, and
81
- dispatched by its exact constructor. `serviceName` names the service in spans and logs —
82
- stable, where a minifier renames classes.
83
- - **Dependencies are attributes.** `addDependency` supplies them; a service declares their types
84
- (`declare readonly client: …`), usually once on a base class per bounded context, as
85
- `sincpro-client scaffold` writes it. Declaring registers nothing; reading a missing one fails.
78
+ - **Dependencies are the context's, never a service's.** `servicesWith<SalesDependencies>()` gives
79
+ the bases every dependency typed on `this` — the backend's `class Feature(_Feature,
80
+ DependencyContextType)` —; `addDependency` supplies them, and reading one never supplied fails.
86
81
  A replacement names what it replaces: `addDependency(name, next, { replaces: previous })`.
87
- - **A service is a singleton of its generation.** What belongs to one request goes in the
88
- Command or the context, never on `this`. Use TypeScript `private`, not `#private`: a run sees
89
- the instance through a view of its own.
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.
86
+ - **One service, N DTOs.** `feature([CommandX, EventY])` registers one service for each, as the
87
+ backend's `DTORegistration`; a DTO still has one service, across both layers, dispatched by
88
+ its exact class — or, generated, by its identity.
89
+ - **A service is a singleton of its generation**, one instance whatever the number of DTOs it
90
+ takes. What belongs to one request goes in the Command or the context, never on `this`. Use
91
+ TypeScript `private`, not `#private`: a run sees the instance through a view of its own.
90
92
  - **Generations.** The first call (or `buildRootBus()`) builds one; what is registered later
91
93
  answers from the next call, and a running call keeps its own. `fresh()` copies the
92
94
  registrations; `scoped({ company_id: 2 })` runs with more context and the same instances.
93
95
  - **Composition.** An ApplicationService runs its context's Features through `this.featureBus`,
94
- as children of its own execution; never another ApplicationService.
95
-
96
- ### Decorators, when the project has them
96
+ as children of its own execution; never another ApplicationService. A bounded context injected
97
+ into another's services (the backend's `common_mcp`) is bound to the run: what it executes is
98
+ a child of it.
97
99
 
98
- ```ts
99
- @sales.feature(CommandTotal)
100
- class Total extends Feature<CommandTotal, ResponseTotal> { … }
101
- ```
100
+ ### Registering: a decorator, or a call
102
101
 
103
- The same functions work as standard decorators and as legacy ones (`experimentalDecorators`);
104
- without a decorator transform, call them: `sales.feature(CommandTotal)(Total)`. No DI library
105
- and no `reflect-metadata`. The tests compile both decorator forms with TypeScript; a bundler's
106
- transform (Vite, Metro/Babel) is each application's to configure and test.
102
+ The same functions work as standard decorators, as legacy ones (`experimentalDecorators`), and
103
+ called: `salesBoundedContext.feature(CommandTotal)(Total)`. No DI library and no
104
+ `reflect-metadata`. The tests compile both decorator forms with TypeScript; a bundler's transform
105
+ (Vite, Metro/Babel) is each application's to configure and test. A service registers itself
106
+ where it is written; `services/index.ts` imports each file, so all are registered before anyone
107
+ executes.
107
108
 
108
109
  ### Replacing a service
109
110
 
110
111
  An application takes the place of a service a module registered, as the backend's `replaces=`:
111
112
 
112
113
  ```ts
114
+ @printingBoundedContext.feature(CommandPrint, { replaces: Print })
113
115
  class PrintOnBixolon extends Print {
114
- static override readonly serviceName = "PrintOnBixolon";
115
116
  override execute(command: CommandPrint) { … }
116
117
  }
117
- printing.feature(CommandPrint, { replaces: Print })(PrintOnBixolon);
118
- printing.handlerOf(CommandPrint); // PrintOnBixolon
118
+ printingBoundedContext.handlerOf(CommandPrint); // PrintOnBixolon
119
119
  ```
120
120
 
121
- `replaces` names the service registered now for that class, or the registration is refused. The
122
- next call answers with the new one; its spans say which it replaced (`sincpro.replaces`). A
123
- service meant to be replaced by a subclass widens its name — `static readonly serviceName:
124
- string = "Print"` —, or TypeScript keeps the literal and the subclass cannot rename itself. A
125
- dependency is replaced the same way: `addDependency(name, next, { replaces: previous })`.
126
-
127
- ## Domain events
128
-
129
- A fact that already happened — `OrderPaid` — is executed as a Command is: by the Feature or
130
- ApplicationService registered for its class, its subscriber in this bounded context, through
131
- the same pipeline (span, log lines, error handlers, report):
121
+ `replaces` names the service registered now for each DTO listed, or the registration is
122
+ refused — all of them or none. The next call answers with the new one; its spans say which it
123
+ replaced (`sincpro.replaces`). A dependency is replaced the same way.
124
+
125
+ ## Commands and events: two DTOs that travel differently
126
+
127
+ | | A Command | An event |
128
+ | -------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
129
+ | Is | a request to **one** bus | a fact **N** buses hear |
130
+ | Known on the wire by | its identity, `<context>.<Command>` — given by the bounded context that registers it (the backend's `registered_name`) | its wire name, `static eventName = "billing.invoice.v1.issued"` — required, dotted |
131
+ | Travels as | CloudEvents 1.0, `type` = its identity | CloudEvents 1.0, `type` = its name; `data` repeats `name` |
132
+ | Written / read with | `commandMessageOf(command, cause?)` / `commandFrom(type, data)` | `eventMessageOf(event, envelope)` / `eventFrom(type, data)` |
133
+
134
+ Both travel as the backend writes them on every queue — CloudEvents 1.0: `id`, `source`, `type`,
135
+ `time`, `correlationid`, `causationid`, `traceparent`, and the DTO's JSON as `data` —; what differs
136
+ is the route. `readMessage` reads one structured, or in a broker's binary mode (the attributes as
137
+ `ce_`, `ce-` or `cloudEvents:` headers, the type falling back to `sincpro-event`), as the backend's
138
+ `Envelope.of`. A delivered message continues its flow and its trace: the run's span is a child of
139
+ its `traceparent`. An event's name is declared — the contract other processes read, with its
140
+ version; a Command's identity is the framework's, the one a generated contract's `operations`
141
+ carry (`static commandName` fixes another). A value that is not JSON (`Money`, `Decimal`, a day)
142
+ comes back as such through the class's `static fromJSON`.
132
143
 
133
144
  ```ts
134
- class OrderPaid extends DomainEvent {
135
- static readonly eventName = "shop.order.v1.paid"; // its wire name, as the backend's `name`
136
- constructor(readonly order_id: string) {
145
+ class InvoiceIssued extends DomainEvent {
146
+ static readonly eventName = "billing.invoice.v1.issued";
147
+ static fromJSON(values: {
148
+ invoice_id: string;
149
+ total: { amount: string; currency: string };
150
+ }) {
151
+ return new InvoiceIssued(
152
+ values.invoice_id,
153
+ new Money(values.total.amount, values.total.currency),
154
+ );
155
+ }
156
+ constructor(
157
+ readonly invoice_id: string,
158
+ readonly total: Money,
159
+ ) {
137
160
  super();
138
161
  }
139
162
  }
163
+ ```
164
+
165
+ `event.name` reads `eventName`; `name` is reserved, and a subclass cannot make it a field.
140
166
 
141
- class ThankCustomer extends Feature<OrderPaid, void> {
142
- static readonly serviceName = "ThankCustomer";
143
- async execute(event: OrderPaid) { … }
167
+ ### What the generator writes is recognized on the bus
168
+
169
+ A contract's Commands and events are generated as types and data, never classes. The bus takes
170
+ their entries — `operations.X` (an identity), `events.X` (a wire name) — as what a service is
171
+ registered for, and executes them as data:
172
+
173
+ ```ts
174
+ import { events, operations } from "../generated/client";
175
+ import type * as remote from "../generated/domain";
176
+
177
+ @projectBoundedContext.feature([events.IssueClosed, operations.CommandArchiveIssue])
178
+ class Archive extends Feature<remote.IssueClosed | RemoteCommand<remote.CommandArchiveIssue>, void> {
179
+ execute(input: remote.IssueClosed | RemoteCommand<remote.CommandArchiveIssue>) { … }
144
180
  }
145
181
 
146
- shop.feature(OrderPaid)(ThankCustomer);
147
- await shop.execute(new OrderPaid("o-1")); // span shop/ThankCustomer, sincpro.event = its name
182
+ await projectBoundedContext.execute(issueClosed); // the event's data: its `name` says which
183
+ await projectBoundedContext.execute(commandOf(operations.CommandArchiveIssue, { issue_id }));
148
184
  ```
149
185
 
150
- - **`eventName` is declared**, as `serviceName` is: a minifier renames classes. `event.name`
151
- reads it; `name` is reserved, and a subclass cannot make it a field.
152
- - **One subscriber per bounded context.** Another context that hears the event registers its
153
- own; a `Subscriber` executes it in each.
154
- - An ApplicationService can subscribe too, and compose Features — of Commands or of events —
155
- through `featureBus`. `execute(event)` answers whatever the subscriber returns (`unknown`).
186
+ `commandOf` tags the input with the operation's identity — never serialized with its data.
187
+
188
+ ## Domain events
156
189
 
157
- ### Publishing and subscribing
190
+ Registering a use case for an event **is** the subscription — the backend's
191
+ `@accounting.feature(InvoiceIssued)`. Several bounded contexts may register it; each hears it once.
158
192
 
159
193
  ```ts
160
- import { Publisher, Subscriber, syncQueue } from "@sincpro/client-framework";
194
+ @accountingBoundedContext.feature(InvoiceIssued)
195
+ class Book extends Feature<InvoiceIssued, void> { … }
196
+
197
+ @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid]) // a screen, or the event
198
+ class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
199
+ ```
200
+
201
+ A use case of an event runs through the same pipeline (span `<context>/<Service>` with
202
+ `sincpro.event`, log lines, error handlers, report). An ApplicationService may take the event and
203
+ compose Features; `execute(event)` answers whatever its use case returns (`unknown`).
161
204
 
162
- const subscriber = new Subscriber(mail, stock); // every bounded context that hears
163
- const queue = syncQueue(subscriber); // in the call, in memory — or a platform's
164
- shop.addDependency("publisher", new Publisher(queue));
205
+ ### The Subscriber: the queue's only entrypoint
165
206
 
207
+ One per queue — the backend's `Subscriber(*buses)` and `QueueGateway`. What arrives is
208
+ recognized (an event by its name, a Command by its identity), rebuilt and executed on the bus
209
+ that registered it. Nobody writes a subscriber per event.
210
+
211
+ ```ts
212
+ new Subscriber(accountingBoundedContext, billingBoundedContext); // every event they registered
213
+
214
+ new Subscriber({
215
+ boundedContexts: [accountingBoundedContext, billingBoundedContext],
216
+ events: [InvoiceIssued, events.IssueClosed], // only these
217
+ commands: [CommandIssueInvoice], // consumed from the queue: only when declared
218
+ });
219
+
220
+ await subscriber.receive(message); // CloudEvents, structured or { headers, body }: what each answered
221
+ ```
222
+
223
+ - **An event** is handed to every bounded context that registered it, in the order named; one
224
+ that fails does not stop the others, and each is said under its name — which a stored queue
225
+ keeps, so a redelivery never runs one again. Two bounded contexts never share a name.
226
+ - **A Command** is executed by the one bounded context that registered it, continuing the
227
+ message's flow — **only when declared** (`commands`). A bus never hands all its Commands to
228
+ whoever can publish on a queue: an undeclared one fails `CommandNotConsumed`
229
+ (`permission_denied`).
230
+
231
+ ### Publishing
232
+
233
+ ```ts
234
+ const queue = syncQueue(new Subscriber(mailBoundedContext, stockBoundedContext)); // or storedQueue
235
+ shopBoundedContext.addDependency("publisher", new Publisher(queue));
236
+
237
+ @shopBoundedContext.feature(CommandPay)
166
238
  class Pay extends Feature<CommandPay, string> {
167
- declare readonly publisher: Publisher;
168
239
  async execute(command: CommandPay) {
169
240
  await this.publisher.publish(new OrderPaid(command.order_id)); // its Envelope
170
241
  return command.order_id;
@@ -173,38 +244,42 @@ class Pay extends Feature<CommandPay, string> {
173
244
  ```
174
245
 
175
246
  The `Publisher` is bound to the run that holds it, so the event joins that run's flow: its
176
- envelope carries the run's `correlationId` and names the run as its cause. The `Subscriber`
177
- executes it in `mail` and in `stock` — `context.execute(event, envelope)` —, so their runs
178
- continue the same flow; one that fails does not stop the others.
247
+ envelope carries the run's `correlationId` and names the run as its cause, and every use case
248
+ that hears it continues that flow.
179
249
 
180
250
  What is defined here, and what each platform plugs behind the ports:
181
251
 
182
- | Piece | Here | The platform's |
183
- | ------------------------- | -------------------------------------------------------------- | -------------------------------------- |
184
- | `DomainEvent`, subscriber | the class, its `eventName`, its execution | — |
185
- | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
186
- | `EventQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
187
- | `EventStore` port | `memoryEventStore()` | mobile: a SQLite table; web: IndexedDB |
188
- | `Subscribes` port | `Subscriber(...contexts)`, `eventTypeOf(name)` | — |
252
+ | Piece | Here | The platform's |
253
+ | ----------------- | -------------------------------------------------------------- | -------------------------------------- |
254
+ | `DomainEvent` | the class, its `eventName`, its messages | — |
255
+ | `Command` | its identity (given at registration), its messages | — |
256
+ | `Envelope` | `name`, `id`, `correlationId`, `causationId`, `publishedAt` | storing it beside the event |
257
+ | `EventQueue` port | `syncQueue` (in the call); `storedQueue` (store, then deliver) | a broker's queue, `BroadcastChannel` |
258
+ | `EventStore` port | `memoryEventStore()` | mobile: a SQLite table; web: IndexedDB |
259
+ | `Subscriber` | recognize, rebuild, execute; events heard, Commands declared | where messages come from (a socket) |
189
260
 
190
261
  ### Stored events: one way to carry them, any store
191
262
 
192
263
  ```ts
193
264
  const queue = storedQueue({
194
265
  store: sqliteEventStore(db), // the platform's EventStore; memoryEventStore() in a tab or a test
195
- subscriber: new Subscriber(sales, stock, printing),
266
+ subscriber: new Subscriber(
267
+ salesBoundedContext,
268
+ stockBoundedContext,
269
+ printingBoundedContext,
270
+ ),
196
271
  ready: (stored) => connectivity.online || !needsNetwork(stored.envelope.name),
197
272
  onSettled: (stored) => activity.show(stored.envelope.name, stored.state),
198
273
  });
199
- shop.addDependency("publisher", new Publisher(queue));
274
+ shopBoundedContext.addDependency("publisher", new Publisher(queue));
200
275
  connectivity.onBack(() => queue.drain()); // and on coming back to the foreground
201
276
  ```
202
277
 
203
278
  `publish` returns once the event is stored. Then the queue delivers what waits, one at a time,
204
279
  in the order stored — the backend's store-and-forward, over whatever store the platform plugs:
205
280
 
206
- - It is rebuilt as its class — `static fromJSON` when it has one — and executed in every
207
- bounded context that hears it and does not have it yet: a retry never runs one twice.
281
+ - It is rebuilt as its class — `static fromJSON` when it has one — and executed by everyone who
282
+ hears it and does not have it yet: a retry never runs one twice.
208
283
  - A failure a retry may fix (`failureOf`: unavailable, no answer, a conflict…) is tried again
209
284
  after the backoff or the wait it asks for, and what follows waits, so the order holds.
210
285
  - A failure every attempt would repeat (`PERMANENT_KINDS`: a refusal, invalid, not found) sets
@@ -219,8 +294,9 @@ memory carry events the same way, with the same rules.
219
294
  Three things a platform keeps in mind:
220
295
 
221
296
  - **At least once.** A process that stops after a context executed an event and before the store
222
- saved it runs it there again. A subscriber that must not act twice keys what it does by the
223
- envelope's id, `this.execution.causationId` in its run.
297
+ saved it runs it there again. What must not act twice keys what it does by the message's id —
298
+ `this.execution.causationId` in the use case that received it — or by what the event names
299
+ (the entity's own id).
224
300
  - **One drainer per store.** Two tabs over one IndexedDB claim it first (the Web Locks API).
225
301
  - **Values come back as JSON.** An event that carries a `Money`, a `Decimal` or a date declares
226
302
  `static fromJSON` to read them back as such.
@@ -236,19 +312,24 @@ and an application changes or hears it from outside, as the backend's `bus_pipel
236
312
 
237
313
  ```ts
238
314
  // control: around the service — look, veto (throw), adjust (same class), or answer
239
- shop.interceptor(CommandPay)(async (command, next, run) => {
315
+ shopBoundedContext.interceptor(CommandPay)(async (command, next, run) => {
240
316
  if (!credit.allows(command.customer_id)) throw new NoCredit();
241
317
  return next(command);
242
318
  });
243
- shop.interceptor()((executable, next, run) => next(executable)); // every class
319
+ shopBoundedContext.interceptor()((executable, next, run) => next(executable)); // every class
244
320
 
245
321
  // observation: never changes the answer
246
- shop.onStart((started) => activity.running(started.execution.useCase));
247
- shop.onCompletion((done) => activity.succeeded(done.execution.useCase), CommandPay);
248
- shop.onFailure((failed) => activity.failed(failed.execution?.useCase, failed.outcome));
322
+ shopBoundedContext.onStart((started) => activity.running(started.execution.useCase));
323
+ shopBoundedContext.onCompletion(
324
+ (done) => activity.succeeded(done.execution.useCase),
325
+ CommandPay,
326
+ );
327
+ shopBoundedContext.onFailure((failed) =>
328
+ activity.failed(failed.execution?.useCase, failed.outcome),
329
+ );
249
330
 
250
331
  // composition: a module or plugin wires its pieces in one place
251
- shop.extend(auditing);
332
+ shopBoundedContext.extend(auditing);
252
333
  ```
253
334
 
254
335
  - **Interceptors** run inside the run, outermost first in the order registered: a veto is the
@@ -270,14 +351,14 @@ first-registered-first. A handler returns the answer, or throws to hand the erro
270
351
  one's throw reaches the caller:
271
352
 
272
353
  ```ts
273
- sales.addFeatureErrorHandler((error) => {
354
+ salesBoundedContext.addFeatureErrorHandler((error) => {
274
355
  if (error instanceof PriceNotFound) return new ResponseTotal(0); // the answer
275
356
  throw error; // the next handler, or the caller
276
357
  });
277
- sales.addAppServiceErrorHandler(toBusinessError);
278
- sales.addGlobalErrorHandler(toProblem); // what reaches sales.execute or a scope
358
+ salesBoundedContext.addAppServiceErrorHandler(toBusinessError);
359
+ salesBoundedContext.addGlobalErrorHandler(toProblem); // what reaches salesBoundedContext.execute or a scope
279
360
 
280
- sales.expectErrors(QuoteExpired); // the business answering: `refused`, never reported
361
+ salesBoundedContext.expectErrors(QuoteExpired); // the business answering: `refused`, never reported
281
362
  ```
282
363
 
283
364
  A failure is observed where it happened, before any handler runs: its span closes with its
@@ -338,7 +419,7 @@ reports what fails outside a use case — a view, a worker —, with the same ru
338
419
 
339
420
  ```ts
340
421
  const screen = new AbortController();
341
- const answer = sales.execute(new CommandQuote(3), { signal: screen.signal });
422
+ const answer = salesBoundedContext.execute(new CommandQuote(3), { signal: screen.signal });
342
423
  screen.abort(); // the run ends `aborted` at once; nothing is reported
343
424
  ```
344
425
 
@@ -378,7 +459,7 @@ configureProcess({
378
459
  });
379
460
  ```
380
461
 
381
- Every execution opens a span `<bounded context>/<serviceName>`; an ApplicationService's Features
462
+ Every execution opens a span `<bounded context>/<Service>`; an ApplicationService's Features
382
463
  are its children, on the same trace. A dependency that is a `Transport` or a generated client is
383
464
  bound to the run, so each request carries `traceparent` (and `tracestate`) and
384
465
  `sincpro-context` — the backend continues the trace. A tracer, reporter or logger that fails is
@@ -399,21 +480,21 @@ import { logger, loggerAdapter } from "@sincpro/client-framework";
399
480
 
400
481
  logger.info("Database opened"); // infrastructure — the global logger
401
482
  loggerAdapter.warn("Printer is slow", { ms: 900 }); // an adapter
402
- sales.logger.info("Catalog preloaded"); // a bounded context, outside a use case
483
+ salesBoundedContext.logger.info("Catalog preloaded"); // a bounded context, outside a use case
403
484
  this.logger.info("Totalling"); // inside a Feature or ApplicationService
404
485
  ```
405
486
 
406
- | Logger | Layer | Each line carries |
407
- | ------------------------- | --------------------- | ---------------------------------------------- |
408
- | `logger` | `infrastructure` | — |
409
- | `loggerAdapter` | `adapter` | the run, when injected as a dependency |
410
- | `sales.logger` | `bounded_context` | its bounded context |
411
- | `this.logger`, Feature | `feature` | bounded context, use case, execution and trace |
412
- | `this.logger`, AppService | `application_service` | the same |
487
+ | Logger | Layer | Each line carries |
488
+ | ---------------------------- | --------------------- | ---------------------------------------------- |
489
+ | `logger` | `infrastructure` | — |
490
+ | `loggerAdapter` | `adapter` | the run, when injected as a dependency |
491
+ | `salesBoundedContext.logger` | `bounded_context` | its bounded context |
492
+ | `this.logger`, Feature | `feature` | bounded context, use case, execution and trace |
493
+ | `this.logger`, AppService | `application_service` | the same |
413
494
 
414
495
  `this.logger` keeps its run across awaits and concurrent calls, without a global stack. An
415
496
  adapter that imports `loggerAdapter` at module level writes without the run; inject it
416
- (`sales.addDependency("log", loggerAdapter)`) or pass `this.logger` when a line must carry it.
497
+ (`salesBoundedContext.addDependency("log", loggerAdapter)`) or pass `this.logger` when a line must carry it.
417
498
 
418
499
  One configuration, two doors — `configureProcess({ logger })` replaces every process port,
419
500
  `configureLogger(...)` only logging (an in-app debug switch):
@@ -441,8 +522,8 @@ snapshot, and what travels goes to the server in `sincpro-context`.
441
522
 
442
523
  ```ts
443
524
  processContext.set({ tenant_id: "acme" });
444
- sales.context.set({ warehouse_id: 4 });
445
- await sales.scoped({ company_id: 2 }).execute(new CommandQuote(1));
525
+ salesBoundedContext.context.set({ warehouse_id: 4 });
526
+ await salesBoundedContext.scoped({ company_id: 2 }).execute(new CommandQuote(1));
446
527
  ```
447
528
 
448
529
  Where the values live is a port (`ContextStore`): synchronous reads, a version per change and an
@@ -534,8 +615,9 @@ sincpro-client check --root src
534
615
  Each method takes the operation's input and answers its answer, as `domain.ts` types them — a
535
616
  search answers its `Response…` with its records and cursor, as the backend's callers get it, on
536
617
  every wire. `scaffold` writes, once, the application's own files: its dependencies (the client
537
- over the `operations` the application exports — `--operations <module>` —), its service bases
538
- and `registerServices`. `check` enforces the application's layers and bounded-context
618
+ over the `operations` the application exports — `--operations <module>` —), its `framework.ts`
619
+ (the service bases with every dependency typed, and the instance) and `services/index.ts`. `check`
620
+ enforces the application's layers and bounded-context
539
621
  boundaries.
540
622
 
541
623
  **Domain events, on demand.** A backend leaves its events out of the contract unless it is
@@ -612,6 +694,52 @@ never a `Date`. `valuesOf`/`pack` write; `readValues` reads tagged values back;
612
694
  use a reader given explicitly. Cycles, functions and non-finite numbers are refused. How a value
613
695
  is shown, typed or stored is the platform's.
614
696
 
697
+ ## An application's layout
698
+
699
+ An application is laid out as a sincpro_framework service is — the entrypoints call the bus, the
700
+ bus runs the use cases, the use cases use the adapters:
701
+
702
+ ```text
703
+ src/
704
+ entrypoints/main.ts(x) configureProcess, the stored queue and its Subscriber
705
+ domains/
706
+ common/infrastructure/operations.ts export const operations — the wire every client uses
707
+ <bounded context>/
708
+ generated/ sincpro-client generate — never edited
709
+ domain/ local Commands, Responses, DomainEvents, value rules
710
+ adapters/ repositories, printers, other systems
711
+ services/ the use cases, one folder per aggregate or entity
712
+ <aggregate>/ sale_order/: its Features and ApplicationServices
713
+ confirm-quotation.feature.ts
714
+ <entity of the aggregate>/ payments/: a related entity with use cases of its own
715
+ register-payment.feature.ts
716
+ reconcile-payments.app-service.ts
717
+ index.ts imports each service: it registers itself (a decorator)
718
+ infrastructure/
719
+ dependencies.ts <Context>Dependencies and registerDependencies
720
+ framework.ts servicesWith<…>() bases, and <context>BoundedContext
721
+ entrypoints/ the doors: they translate, they decide nothing
722
+ cron/ mobile only — its scheduler: tick → Command → bus
723
+ index.ts <context>BoundedContext, ready to execute
724
+ ```
725
+
726
+ - **Services by aggregate.** A simple entity is one folder with its Features (a CRUD). When an
727
+ aggregate holds related entities with use cases of their own — the payments of a sale order —,
728
+ they get a folder inside it, and its Features and ApplicationServices live there, grouped by
729
+ what they are about.
730
+ - **Entrypoints translate.** A screen and a cron build a Command and execute it; what a queue
731
+ carries goes through the one `Subscriber` (`entrypoints/main.ts`). A workflow of several use
732
+ cases is an ApplicationService. `sincpro-client check` refuses a service that imports an
733
+ entrypoint.
734
+ - **A cron is a platform's door, and only where the platform has a scheduler.** A phone wakes a
735
+ closed app on a schedule (mobile's `CronWorker`); a browser does not — Periodic Background Sync
736
+ is Chromium-only, for an installed PWA, and the browser decides when. On the web, refreshing
737
+ what a screen shows is the screen's (a query's refetch interval), not a cron, and work on a
738
+ schedule is the backend's (`Crons`). This package has no cron: the day web needs one, its
739
+ registry and a `Scheduler` port come here.
740
+ - **A bounded context is named for what it is**: `salesBoundedContext`, never `sales` (an
741
+ entity?) or `ctx` — `context` is already the run's (`this.context`).
742
+
615
743
  ## Package layout
616
744
 
617
745
  Each module is laid out as sincpro_framework's are, and says what it offers in its `index.ts`:
@@ -644,9 +772,11 @@ src/
644
772
  entrypoint/ BoundedContext, screensTransport
645
773
  infrastructure/ configureProcess, configureLogger, processListeners
646
774
  event_driven/
647
- domain/ Envelope, the EventQueue, Subscribes and EventStore ports
775
+ domain/ Envelope, the messages (an event's, a Command's), the EventQueue,
776
+ Subscribes and EventStore ports
777
+ services/ writing and reading messages
648
778
  adapters/ syncQueue, storedQueue, memoryEventStore
649
- entrypoint/ Publisher, Subscriber
779
+ entrypoint/ Publisher, Subscriber (the queue's only entrypoint)
650
780
  codegen/ the generator and its CLI — the only place Node is allowed
651
781
  testing/ memoryTracer, memoryReporter, memoryLogger
652
782
  ```
@@ -6,7 +6,7 @@ import type { Transport } from "../domain/transport.js";
6
6
  * `Transport`:
7
7
  *
8
8
  * const operations = guardedTransport(jsonRpcOperations({ endpoint }), new CircuitBreaker("forge"));
9
- * project.addDependency("client", clientOf(operations));
9
+ * projectBoundedContext.addDependency("client", clientOf(operations));
10
10
  *
11
11
  * Context: the circuit belongs where the dependency is — the transport —, not in each Feature. A
12
12
  * run binds it as it binds any transport, so the trace and the context still travel; an open
@@ -1,6 +1,7 @@
1
1
  import { plainCodec } from "../../context/adapters/plain-codec.js";
2
2
  import { CONTEXT_HEADER, travels } from "../../context/domain/codec.js";
3
3
  import { BIND } from "../../context/domain/execution.js";
4
+ import { traceparentOf } from "../../observability/services/trace-context.js";
4
5
  /** Whether a value is a `Transport`: what a run binds to itself even without `BIND`. */
5
6
  export function isTransport(value) {
6
7
  if (value === null || typeof value !== "object")
@@ -18,9 +19,9 @@ export function isTransport(value) {
18
19
  export function headersOf(execution) {
19
20
  const headers = {};
20
21
  const { span, context } = execution;
21
- if (span.traceId !== "" && span.spanId !== "") {
22
- headers["traceparent"] =
23
- `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}`;
22
+ const traceparent = traceparentOf(span);
23
+ if (traceparent !== undefined) {
24
+ headers["traceparent"] = traceparent;
24
25
  if (span.state)
25
26
  headers["tracestate"] = span.state;
26
27
  }
@@ -1,20 +1,22 @@
1
1
  import type { Metamodel } from "../domain/metamodel.js";
2
2
  /**
3
3
  * A bounded context's skeleton, written ONCE beside what is generated — the files that are the
4
- * application's from then on:
4
+ * application's from then on, laid out as the backend's (`sincpro_mcp_odoo/domains/helpdesk`):
5
5
  *
6
6
  * domains/project/
7
7
  * generated/ `sincpro-client generate` — regenerated, never edited
8
- * infrastructure/dependencies.ts what the services can count on: the generated client
9
- * infrastructure/bounded_context.ts its Feature and ApplicationService, and how it is made
10
- * services/index.ts registers command classes and their services
11
- * index.ts `export const project` — ready to use
8
+ * infrastructure/dependencies.ts what its services count on, and who supplies it
9
+ * infrastructure/framework.ts its Feature and ApplicationService — every dependency
10
+ * typed on `this` — and `projectBoundedContext`
11
+ * services/index.ts imports each service, which registers itself
12
+ * index.ts `projectBoundedContext`, ready to use
12
13
  *
13
- * Context: the layout sincpro_framework gives a service (`dependencies.py`, `framework.py`,
14
- * `services/`, `__init__.py`), so a bounded context starts the way every other does and nobody
15
- * copies it by hand from another. It is the application's to change: the CLI writes a file only
16
- * when it is not there, and never touches one that is — unlike `generated/`, which is written
17
- * whole every time.
14
+ * Context: `dependencies.py`, `framework.py`, `services/` and `__init__.py` — a bounded context
15
+ * starts the way every other does. The instance lives in `framework.ts`, not `index.ts`: a service
16
+ * imports it to register itself (`@projectBoundedContext.feature(Command)`), and ES modules run
17
+ * their imports first, so `index.ts` importing the services could not also define it. It is the
18
+ * application's to change: the CLI writes a file only when it is not there, and never touches one
19
+ * that is — unlike `generated/`, which is written whole every time.
18
20
  */
19
21
  export type ScaffoldOptions = {
20
22
  /**