@sincpro/client-framework 1.8.0 → 1.10.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/README.md CHANGED
@@ -171,8 +171,8 @@ their entries — `operations.X` (an identity), `events.X` (a wire name) — as
171
171
  registered for, and executes them as data:
172
172
 
173
173
  ```ts
174
- import { events, operations } from "../generated/client";
175
- import type * as remote from "../generated/domain";
174
+ import { events, operations } from "../adapters/generated/client";
175
+ import type * as remote from "../domain/generated";
176
176
 
177
177
  @projectBoundedContext.feature([events.IssueClosed, operations.CommandArchiveIssue])
178
178
  class Archive extends Feature<remote.IssueClosed | RemoteCommand<remote.CommandArchiveIssue>, void> {
@@ -358,7 +358,7 @@ Three things a platform keeps in mind:
358
358
  `static fromJSON` to read them back as such.
359
359
 
360
360
  The events a remote service publishes arrive as generated types (`DomainEvent` in
361
- `generated/domain.ts`, a union narrowed by `name`); a local event is a class, like a local
361
+ `domain/generated/events.ts`, a union narrowed by `name`); a local event is a class, like a local
362
362
  Command.
363
363
 
364
364
  ## Extending the pipeline
@@ -587,9 +587,26 @@ The console is the default engine. In production it is silent; in development it
587
587
  everything, and `level` and `layers` hide only INFO/DEBUG. A supplied `engine` owns its own
588
588
  policy, and each sink of `combineLoggers` keeps its own — the console's silence never silences
589
589
  another. Every execution writes `execution.started` (DEBUG) and `execution.finished` with its
590
- outcome and duration (INFO, WARN when refused, ERROR when failed). No line carries a DTO, a
591
- result, an error body or the session's context unless the author writes it. Delivery, buffering
592
- and credentials (Loki, a phone's queue) are the platform's.
590
+ outcome and duration (INFO, also when refused or aborted; ERROR when failed). No line carries a
591
+ DTO, a result, an error body or the session's context unless the author writes it. Delivery,
592
+ buffering and credentials (Loki, a phone's queue) are the platform's.
593
+
594
+ In development each record is one line for a person — time, level, layer, use case, message, its
595
+ attributes as `key=value`, and the run's short id — never the record object after it:
596
+
597
+ ```text
598
+ 10:20:30.045 DEBUG [feature] ▶ shop.Pay #0193a1
599
+ 10:20:30.051 INFO [feature] shop.Pay Paying order=A-1 note="two words" #0193a1
600
+ 10:20:30.057 INFO [feature] ✔ shop.Pay 12ms #0193a1
601
+ 10:20:31.002 INFO [feature] ✖ shop.Pay refused: domain 3ms #0193b7
602
+ 10:20:32.118 ERROR [feature] ✖ shop.Pay TypeError: card is undefined 4ms #0193c2 + the Error, with its stack
603
+ ```
604
+
605
+ An unexpected failure also prints its `Error`, so LogBox, Expo's terminal and a browser show its
606
+ code frame. `consoleLogger({ mode, colors })` colors the lines of the levels named (`true`: every
607
+ one) with ANSI codes: the platform knows where its console renders them — a terminal does, React
608
+ Native's LogBox (WARN and ERROR in the app) does not. `prettyLine(record)` is the same line, for a
609
+ sink of one's own.
593
610
 
594
611
  ## Context
595
612
 
@@ -615,7 +632,7 @@ which operation, with what input, and the adapter the application injects decide
615
632
  travels.
616
633
 
617
634
  ```ts
618
- import { clientOf } from "./generated/client";
635
+ import { clientOf } from "./adapters/generated/client";
619
636
 
620
637
  // pick the wire; the client, the Features and the tests stay the same
621
638
  const forge = clientOf(restOperations(restTransport({ base: "/v1", headers: session })));
@@ -643,6 +660,26 @@ its trace (`traceparent`), its context (`sincpro-context`) and its signal — as
643
660
  as metadata where a platform's adapter puts them. `screensTransport` and `entity()` stay on the
644
661
  REST `Transport`: they are how a screen reads pages of an entity, with its model and its drafts.
645
662
 
663
+ ### What a write changed
664
+
665
+ A client keeps what it read — a cache, a list on screen, a record — and every one of them goes
666
+ stale when a write lands, whoever wrote it. So every write says so: `restTransport` and
667
+ `memoryTransport` announce each `send` on the process's change feed (`processChanges`), whether it
668
+ came from a screen or from a use case's generated client, answered or refused. A preview and a dry
669
+ run announce nothing. A reader follows the feed, never the writer's transport:
670
+
671
+ ```ts
672
+ import { processChanges } from "@sincpro/client-framework";
673
+
674
+ const stop = processChanges.follow((change) => forgetUnder(change.route)); // { method, route }
675
+ stop();
676
+ ```
677
+
678
+ A change says only what was written; what it touches — the collections a route names, a record's
679
+ history — is each reader's to decide. A transport given `changes` announces there instead (a test,
680
+ a transport that must not be heard), and a platform's own adapter wraps its `send` in
681
+ `announced(feed, method, route, body, send)`.
682
+
646
683
  ### Writing an adapter for another wire
647
684
 
648
685
  An adapter is one function: read the operation's binding for its wire, send the input, answer the
@@ -676,20 +713,29 @@ Every operation in `operations` carries its identity and each wire's binding (`r
676
713
 
677
714
  ```bash
678
715
  python -m sincpro_framework.entrypoints export-client-contract app.http:gateways contracts [--events]
679
- sincpro-client generate contracts/project.contract.json --out src/domains/project/generated --domain project
716
+ sincpro-client generate contracts/project.contract.json --out src/domains/project --domain project
680
717
  sincpro-client scaffold contracts/project.contract.json --out src/domains/project
681
718
  sincpro-client check --root src
682
719
  ```
683
720
 
684
- `generate` writes, from the contract the backend exports — never edited, written again whole:
721
+ `generate` writes, from the contract the backend exports — never edited, written again whole —,
722
+ each file in the layer it belongs to, under the bounded context's folder (`--out`):
723
+
724
+ | File | What |
725
+ | -------------------------------- | --------------------------------------------------------------------------------------------- |
726
+ | `domain/generated/models.ts` | the entities and value objects: a type per model, and the definitions they hold |
727
+ | `domain/generated/commands.ts` | every operation's Command and Response, and the `<Name>Input` a caller sends |
728
+ | `domain/generated/events.ts` | the domain events and `DomainEvent`, their union — when the contract carries them |
729
+ | `domain/generated/index.ts` | the three, re-exported: `import type * as remote from "../domain/generated"` |
730
+ | `adapters/generated/client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
731
+ | `adapters/generated/entities.ts` | each entity's list, record, edit, export, Commands and history, for screens |
685
732
 
686
- | File | What |
687
- | ------------- | --------------------------------------------------------------------------------------------- |
688
- | `domain.ts` | a type per model, per `<Name>Input`, per operation's input and answer, per domain event |
689
- | `client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
690
- | `entities.ts` | each entity's list, record, edit, export, Commands and history, for screens |
733
+ The backend keeps them apart — the domain's words, the application layer's DTOs, the facts, the
734
+ adapters to another system —, and so does the application: each beside its own code of that layer.
735
+ A shared definition goes with the first kind that names it (the models, then the operations, then
736
+ the events), and a file that names one written elsewhere imports it from there.
691
737
 
692
- Each method takes the operation's input and answers its answer, as `domain.ts` types them — a
738
+ Each method takes the operation's input and answers its answer, as `commands.ts` types them — a
693
739
  search answers its `Response…` with its records and cursor, as the backend's callers get it, on
694
740
  every wire. `scaffold` writes, once, the application's own files: its dependencies (the client
695
741
  over the `operations` the application exports — `--operations <module>` —), its `framework.ts`
@@ -702,7 +748,7 @@ exported with `--events`. Then each event is a type as it is received — every
702
748
  `name` its wire name as a literal — and `DomainEvent`, their union, narrows by `name`:
703
749
 
704
750
  ```ts
705
- import type * as remote from "./generated/domain";
751
+ import type * as remote from "./domain/generated";
706
752
 
707
753
  function subjectOf(event: remote.DomainEvent): string {
708
754
  switch (event.name) {
@@ -713,7 +759,7 @@ function subjectOf(event: remote.DomainEvent): string {
713
759
  }
714
760
  ```
715
761
 
716
- `events` in `client.ts` says, per event, its wire name and whether the bounded context records it
762
+ `events` in `adapters/generated/client.ts` says, per event, its wire name and whether the bounded context records it
717
763
  (its aggregates' own) or handles it (a Feature subscribes).
718
764
 
719
765
  ### Types, not classes
@@ -730,13 +776,13 @@ types; the application's own Commands are classes, written by hand.
730
776
  a local Feature, through the injected client.
731
777
  - **Events read best as a union.** A stream of facts — a queue, a history page — is narrowed by
732
778
  `name`, with no registry of constructors to rebuild each one.
733
- - **Nothing runs.** `domain.ts` adds no byte to a bundle and no side effect; a contract of three
779
+ - **Nothing runs.** `domain/generated/` adds no byte to a bundle and no side effect; a contract of three
734
780
  hundred models costs nothing at runtime.
735
781
 
736
782
  A local class takes the contract's shape and stays checked against it:
737
783
 
738
784
  ```ts
739
- import type * as remote from "../generated/domain";
785
+ import type * as remote from "../domain/generated";
740
786
 
741
787
  class CommandCancelIssue
742
788
  extends Command<ResponseCancelIssue>
@@ -783,9 +829,10 @@ src/
783
829
  domains/
784
830
  common/infrastructure/operations.ts export const operations — the wire every client uses
785
831
  <bounded context>/
786
- generated/ sincpro-client generate — never edited
787
832
  domain/ local Commands, Responses, DomainEvents, value rules
833
+ generated/ sincpro-client generate: models, commands, events — never edited
788
834
  adapters/ repositories, printers, other systems
835
+ generated/ sincpro-client generate: the client and the entities
789
836
  services/ the use cases, one folder per aggregate or entity
790
837
  <aggregate>/ sale_order/: its Features and ApplicationServices
791
838
  confirm-quotation.feature.ts
@@ -1,3 +1,4 @@
1
+ import type { ChangeFeed } from "../domain/changes.js";
1
2
  import { type Draft, type Method, type Transport } from "../domain/transport.js";
2
3
  import type { AnyRecord, Criteria, Meta, Problem } from "@sincpro/criteria";
3
4
  /**
@@ -42,5 +43,8 @@ export type MemoryOptions = {
42
43
  refuse?: (route: string) => (Problem & {
43
44
  status?: number;
44
45
  }) | undefined;
46
+ /** Where each write is announced (`Change`), as a real server's transport does: the
47
+ * process's feed (`processChanges`) by default. */
48
+ changes?: ChangeFeed;
45
49
  };
46
50
  export declare function memoryTransport(tables: Readonly<Record<string, MemoryTable>>, options?: MemoryOptions): Transport;
@@ -1,4 +1,5 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
+ import { announced, processChanges } from "../services/changes.js";
2
3
  import { bindableTransport } from "../services/propagation.js";
3
4
  import { pack, readValues } from "../../common/serialization.js";
4
5
  import { answer, answerGroups } from "@sincpro/criteria/engine";
@@ -24,6 +25,7 @@ function wait(ms, signal) {
24
25
  }
25
26
  export function memoryTransport(tables, options = {}) {
26
27
  const answered = new Map();
28
+ const changes = options.changes ?? processChanges;
27
29
  async function check(route, signal) {
28
30
  await wait(options.latency ?? 0, signal);
29
31
  const refused = options.refuse?.(route);
@@ -86,27 +88,29 @@ export function memoryTransport(tables, options = {}) {
86
88
  };
87
89
  },
88
90
  async send(method, route, body, signal, sending) {
89
- await check(route, signal);
90
- // A key already answered is answered again, without running the Command twice — what
91
- // sincpro_framework's `@idempotency` does with a repeated `Idempotency-Key`.
92
- const key = sending?.idempotencyKey;
93
- if (key !== undefined && answered.has(key))
94
- return copyOf(answered.get(key));
95
- if (options.handle === undefined)
96
- throw new TransportError(route, 404, {
97
- kind: "not_found",
98
- reason: "ROUTE_NOT_FOUND",
99
- next_step: "fix_request",
100
- retryable: false,
101
- errors: [],
102
- extensions: {},
103
- detail: `Nothing answers ${method} ${route}.`,
104
- });
105
- // A deep copy: what the caller sent is not what the server keeps.
106
- const answer = await options.handle(method, route, copyOf(body));
107
- if (key !== undefined)
108
- answered.set(key, copyOf(answer));
109
- return answer;
91
+ return announced(changes, method, route, body, async () => {
92
+ await check(route, signal);
93
+ // A key already answered is answered again, without running the Command twice — what
94
+ // sincpro_framework's `@idempotency` does with a repeated `Idempotency-Key`.
95
+ const key = sending?.idempotencyKey;
96
+ if (key !== undefined && answered.has(key))
97
+ return copyOf(answered.get(key));
98
+ if (options.handle === undefined)
99
+ throw new TransportError(route, 404, {
100
+ kind: "not_found",
101
+ reason: "ROUTE_NOT_FOUND",
102
+ next_step: "fix_request",
103
+ retryable: false,
104
+ errors: [],
105
+ extensions: {},
106
+ detail: `Nothing answers ${method} ${route}.`,
107
+ });
108
+ // A deep copy: what the caller sent is not what the server keeps.
109
+ const answer = await options.handle(method, route, copyOf(body));
110
+ if (key !== undefined)
111
+ answered.set(key, copyOf(answer));
112
+ return answer;
113
+ });
110
114
  },
111
115
  ...(options.read === undefined
112
116
  ? {}
@@ -1,3 +1,4 @@
1
+ import type { ChangeFeed } from "../domain/changes.js";
1
2
  import { type Decoder, type Transport } from "../domain/transport.js";
2
3
  import { type Criteria } from "@sincpro/criteria";
3
4
  /**
@@ -44,6 +45,9 @@ export type RestOptions = {
44
45
  /** Called once per model and version the server answers that the snapshot does not hold —
45
46
  * never an error: the screen keeps working on the live definition. */
46
47
  onVersionDrift?: (drift: VersionDrift) => void;
48
+ /** Where each write is announced (`Change`): the process's feed (`processChanges`) by default,
49
+ * so a cache or a screen hears it whoever wrote — a screen, or a use case's client. */
50
+ changes?: ChangeFeed;
47
51
  };
48
52
  /** A model the server answers at another version than the snapshot the code came from. */
49
53
  export type VersionDrift = {
@@ -1,4 +1,5 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
+ import { announced, processChanges } from "../services/changes.js";
2
3
  import { definitionOf, modelAt, } from "../services/discovery.js";
3
4
  import { bindableTransport } from "../services/propagation.js";
4
5
  import { readProblem } from "@sincpro/criteria";
@@ -45,6 +46,7 @@ function documentUrl(base, document) {
45
46
  export function restTransport(options = {}) {
46
47
  const base = options.base ?? "";
47
48
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
49
+ const changes = options.changes ?? processChanges;
48
50
  const decoders = options.decoders ?? [];
49
51
  const accept = decoders.length === 0
50
52
  ? {}
@@ -183,7 +185,9 @@ export function restTransport(options = {}) {
183
185
  };
184
186
  },
185
187
  async send(method, route, body, signal, sending) {
186
- return (await get(route, urlOf(base, route), signal, { method, body, key: sending?.idempotencyKey }, sending));
188
+ return announced(changes, method, route, body, async () => {
189
+ return (await get(route, urlOf(base, route), signal, { method, body, key: sending?.idempotencyKey }, sending));
190
+ });
187
191
  },
188
192
  });
189
193
  }
@@ -0,0 +1,45 @@
1
+ import type { Method } from "./transport.js";
2
+ /**
3
+ * A write that may have changed what was read: how it was sent and where.
4
+ *
5
+ * Context: a client keeps what it read — a cache, a list on screen, a record, a name in a cell —
6
+ * and every one of them goes stale the moment a write lands, whoever wrote: a screen's save, a use
7
+ * case's Command, a second panel. Each used to learn it only when the write went through the same
8
+ * object it read through, so a use case writing over its generated client left every screen
9
+ * reading the old answer. A change is the fact every reader can hear instead (`ChangeFeed`). It
10
+ * says only what was written — what that touches (the collections a route names, a record's
11
+ * history) is each reader's to decide, as a cache and a screen decide differently.
12
+ *
13
+ * { method: "POST", route: "/issues/odoo-acme-7/messages" }
14
+ */
15
+ export type Change = {
16
+ readonly method: Method;
17
+ /** As the transport received it: a path under its base, maybe with a query. */
18
+ readonly route: string;
19
+ };
20
+ /**
21
+ * Who hears what was written: one feed the writers announce to and the readers follow, so neither
22
+ * knows the other.
23
+ *
24
+ * const stop = processChanges.follow((change) => cache.forget(change.route));
25
+ * processChanges.announce({ method: "PUT", route: "/projects/odoo-acme/edit" });
26
+ * stop();
27
+ *
28
+ * Context: a listener that fails is ignored — hearing a write never changes its answer, as
29
+ * tracing and listening never do.
30
+ */
31
+ export type ChangeFeed = {
32
+ /** Tells everyone who follows now: this was written. */
33
+ announce(change: Change): void;
34
+ /** `listener` hears every change announced from now on; answers the way to stop. */
35
+ follow(listener: (change: Change) => void): () => void;
36
+ };
37
+ /**
38
+ * The change a `send` makes, or `undefined` when it writes nothing: a preview (`…/preview`) and a
39
+ * dry run (`dry_run: true`, sincpro_framework's `DryRunnable`) only say what a write WOULD do.
40
+ *
41
+ * changeOf("POST", "/issues/7/cancel", {}) -> { method: "POST", route: "/issues/7/cancel" }
42
+ * changeOf("POST", "/issues/7/cancel", { dry_run: true }) -> undefined
43
+ * changeOf("POST", "/invoices/preview", { lines: [] }) -> undefined
44
+ */
45
+ export declare function changeOf(method: Method, route: string, body: unknown): Change | undefined;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The change a `send` makes, or `undefined` when it writes nothing: a preview (`…/preview`) and a
3
+ * dry run (`dry_run: true`, sincpro_framework's `DryRunnable`) only say what a write WOULD do.
4
+ *
5
+ * changeOf("POST", "/issues/7/cancel", {}) -> { method: "POST", route: "/issues/7/cancel" }
6
+ * changeOf("POST", "/issues/7/cancel", { dry_run: true }) -> undefined
7
+ * changeOf("POST", "/invoices/preview", { lines: [] }) -> undefined
8
+ */
9
+ export function changeOf(method, route, body) {
10
+ if ((route.split("?")[0] ?? route).endsWith("/preview"))
11
+ return undefined;
12
+ if (typeof body === "object" && body !== null && "dry_run" in body && body.dry_run === true)
13
+ return undefined;
14
+ return { method, route };
15
+ }
@@ -3,18 +3,21 @@
3
3
  * commands, the service's client contract, and how a run's trace and context reach the wire.
4
4
  *
5
5
  * domain/ the port and the server's words: `Transport`, `TransportError`, `entity()`, the
6
- * client contract
6
+ * client contract, what a write changed (`Change`, `ChangeFeed`)
7
7
  * adapters/ REST, memory, and Parquet (optional entry `./parquet`)
8
- * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`)
8
+ * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`), the
9
+ * process's change feed (`processChanges`)
9
10
  */
10
11
  export { JsonRpcError, jsonRpcOperations, type JsonRpcOptions, } from "./adapters/json-rpc.js";
11
12
  export { type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
12
13
  export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./adapters/rest.js";
13
14
  export { restOperations } from "./adapters/rest-operations.js";
15
+ export { type Change, type ChangeFeed, changeOf, } from "./domain/changes.js";
14
16
  export { type ClientContract, entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
15
17
  export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type EntityRef, type EntityRoutes, type ExportFormat, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, type SummaryFields, type SummaryPart, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./domain/entity.js";
16
18
  export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
17
19
  export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, type Method, type One, readRoute, type SendOptions, type Transport, TransportError, } from "./domain/transport.js";
20
+ export { announced, changeFeed, processChanges, } from "./services/changes.js";
18
21
  export { guardedTransport } from "./services/guarded.js";
19
22
  export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
20
23
  export { type RetryKeys, retryKeys, unanswered, } from "./services/retry.js";
@@ -3,18 +3,21 @@
3
3
  * commands, the service's client contract, and how a run's trace and context reach the wire.
4
4
  *
5
5
  * domain/ the port and the server's words: `Transport`, `TransportError`, `entity()`, the
6
- * client contract
6
+ * client contract, what a write changed (`Change`, `ChangeFeed`)
7
7
  * adapters/ REST, memory, and Parquet (optional entry `./parquet`)
8
- * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`)
8
+ * services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`), the
9
+ * process's change feed (`processChanges`)
9
10
  */
10
11
  export { JsonRpcError, jsonRpcOperations, } from "./adapters/json-rpc.js";
11
12
  export { memoryTransport, } from "./adapters/memory.js";
12
13
  export { restTransport, urlOf, } from "./adapters/rest.js";
13
14
  export { restOperations } from "./adapters/rest-operations.js";
15
+ export { changeOf, } from "./domain/changes.js";
14
16
  export { entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
15
17
  export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./domain/entity.js";
16
18
  export { OperationNotPublished, } from "./domain/operation.js";
17
19
  export { downloadRoute, readRoute, TransportError, } from "./domain/transport.js";
20
+ export { announced, changeFeed, processChanges, } from "./services/changes.js";
18
21
  export { guardedTransport } from "./services/guarded.js";
19
22
  export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
20
23
  export { retryKeys, unanswered, } from "./services/retry.js";
@@ -0,0 +1,32 @@
1
+ import { type ChangeFeed } from "../domain/changes.js";
2
+ import type { Method } from "../domain/transport.js";
3
+ /**
4
+ * A feed in the process's memory: every listener hears every change announced while it follows.
5
+ *
6
+ * const changes = changeFeed();
7
+ * const stop = changes.follow((change) => console.log(change.route));
8
+ *
9
+ * Context: one is enough for an application — `processChanges`, which every transport of this
10
+ * package announces to by default —; another is for a test, or a transport that must not be heard.
11
+ * A listener added while a change is being announced hears the next one, not that one.
12
+ */
13
+ export declare function changeFeed(): ChangeFeed;
14
+ /**
15
+ * What the process wrote, for whoever keeps what it read: the feed this package's transports
16
+ * (`restTransport`, `memoryTransport`) announce every write to unless told otherwise, and the one
17
+ * a platform's caches and screens follow.
18
+ *
19
+ * processChanges.follow((change) => …);
20
+ *
21
+ * Context: it lives as long as the process — `configureProcess` does not clear it —, so whoever
22
+ * follows keeps the function that stops it, as with `processListeners`.
23
+ */
24
+ export declare const processChanges: ChangeFeed;
25
+ /**
26
+ * `write` — a transport's `send` —, and then its change announced on `feed`, whatever it answered:
27
+ * a refusal may have changed something too (a 409 says someone else did), and a request with no
28
+ * answer may have run. A preview or a dry run announces nothing (`changeOf`).
29
+ *
30
+ * send: (method, route, body) => announced(changes, method, route, body, () => post(…)),
31
+ */
32
+ export declare function announced<T>(feed: ChangeFeed, method: Method, route: string, body: unknown, write: () => Promise<T>): Promise<T>;
@@ -0,0 +1,60 @@
1
+ import { changeOf, } from "../domain/changes.js";
2
+ /**
3
+ * A feed in the process's memory: every listener hears every change announced while it follows.
4
+ *
5
+ * const changes = changeFeed();
6
+ * const stop = changes.follow((change) => console.log(change.route));
7
+ *
8
+ * Context: one is enough for an application — `processChanges`, which every transport of this
9
+ * package announces to by default —; another is for a test, or a transport that must not be heard.
10
+ * A listener added while a change is being announced hears the next one, not that one.
11
+ */
12
+ export function changeFeed() {
13
+ const listeners = new Set();
14
+ return {
15
+ announce(change) {
16
+ for (const listener of [...listeners]) {
17
+ try {
18
+ listener(change);
19
+ }
20
+ catch {
21
+ // Hearing a write never changes its answer, as tracing and listening never do.
22
+ }
23
+ }
24
+ },
25
+ follow(listener) {
26
+ if (typeof listener !== "function")
27
+ throw new TypeError("A listener is a function");
28
+ listeners.add(listener);
29
+ return () => void listeners.delete(listener);
30
+ },
31
+ };
32
+ }
33
+ /**
34
+ * What the process wrote, for whoever keeps what it read: the feed this package's transports
35
+ * (`restTransport`, `memoryTransport`) announce every write to unless told otherwise, and the one
36
+ * a platform's caches and screens follow.
37
+ *
38
+ * processChanges.follow((change) => …);
39
+ *
40
+ * Context: it lives as long as the process — `configureProcess` does not clear it —, so whoever
41
+ * follows keeps the function that stops it, as with `processListeners`.
42
+ */
43
+ export const processChanges = changeFeed();
44
+ /**
45
+ * `write` — a transport's `send` —, and then its change announced on `feed`, whatever it answered:
46
+ * a refusal may have changed something too (a 409 says someone else did), and a request with no
47
+ * answer may have run. A preview or a dry run announces nothing (`changeOf`).
48
+ *
49
+ * send: (method, route, body) => announced(changes, method, route, body, () => post(…)),
50
+ */
51
+ export async function announced(feed, method, route, body, write) {
52
+ try {
53
+ return await write();
54
+ }
55
+ finally {
56
+ const change = changeOf(method, route, body);
57
+ if (change !== undefined)
58
+ feed.announce(change);
59
+ }
60
+ }
@@ -5,7 +5,17 @@ import type { Metamodel } from "./metamodel.js";
5
5
  * whole, the generated files came out importing `"../index.js"` and `"./domain.js"`.
6
6
  */
7
7
  export declare const FRAMEWORK: string;
8
+ /**
9
+ * Where `generate` writes each layer of a bounded context, from its folder: the domain's types
10
+ * (`models.ts`, `commands.ts`, `events.ts`, `index.ts`) and the adapters over the service's wire
11
+ * (`client.ts`, `entities.ts`) — each beside the code of its layer, as the backend lays it out.
12
+ */
13
+ export declare const GENERATED_DOMAIN: string;
14
+ export declare const GENERATED_ADAPTERS: string;
15
+ /** What a generated adapter imports the domain's types from: `../../domain/generated/index`. */
8
16
  export declare const DOMAIN_MODULE: string;
17
+ /** A file of `domain/generated/` as its sibling imports it: `models` → `./models`. */
18
+ export declare function siblingOf(file: string): string;
9
19
  /** A name of the server's as a TypeScript identifier: `shop__orders__Line` stays, `-` is `_`. */
10
20
  export declare function identifierOf(name: string): string;
11
21
  /** A property key as TypeScript writes it: bare when it can be, quoted otherwise. */
@@ -14,7 +14,19 @@ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
14
14
  * whole, the generated files came out importing `"../index.js"` and `"./domain.js"`.
15
15
  */
16
16
  export const FRAMEWORK = ["@sincpro", "client-framework"].join("/");
17
- export const DOMAIN_MODULE = [".", "domain"].join("/");
17
+ /**
18
+ * Where `generate` writes each layer of a bounded context, from its folder: the domain's types
19
+ * (`models.ts`, `commands.ts`, `events.ts`, `index.ts`) and the adapters over the service's wire
20
+ * (`client.ts`, `entities.ts`) — each beside the code of its layer, as the backend lays it out.
21
+ */
22
+ export const GENERATED_DOMAIN = ["domain", "generated"].join("/");
23
+ export const GENERATED_ADAPTERS = ["adapters", "generated"].join("/");
24
+ /** What a generated adapter imports the domain's types from: `../../domain/generated/index`. */
25
+ export const DOMAIN_MODULE = ["..", "..", GENERATED_DOMAIN, "index"].join("/");
26
+ /** A file of `domain/generated/` as its sibling imports it: `models` → `./models`. */
27
+ export function siblingOf(file) {
28
+ return [".", file].join("/");
29
+ }
18
30
  /** A name of the server's as a TypeScript identifier: `shop__orders__Line` stays, `-` is `_`. */
19
31
  export function identifierOf(name) {
20
32
  const cleaned = name.replace(/[^A-Za-z0-9_$]/g, "_");
@@ -1,28 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
- import { aliasOf } from "../domain/names.js";
4
+ import { aliasOf, GENERATED_ADAPTERS, GENERATED_DOMAIN, } from "../domain/names.js";
5
5
  import { CheckError, checkImports } from "../services/check.js";
6
- import { clientFileOf } from "../services/client.js";
7
- import { domainFileOf } from "../services/domain.js";
8
- import { entitiesFileOf } from "../services/entities.js";
6
+ import { generatedFilesOf } from "../services/generated.js";
9
7
  import { scaffoldFilesOf } from "../services/scaffold.js";
10
8
  /**
11
9
  * `sincpro-client generate <contract.json> --out <dir> [--domain <name>] [--base <path>]` — what an
12
10
  * application's `make client` runs, once per bounded context, over the client contract
13
- * sincpro_framework exported (`export-client-contract`):
11
+ * sincpro_framework exported (`export-client-contract`). `--out` is the bounded context's folder
12
+ * (`src/domains/project`); each file goes in its layer (`generatedFilesOf`):
14
13
  *
15
- * - `domain.ts`: the DTOs, only types — and the domain events with `DomainEvent`, their union,
16
- * when the contract was exported with them (`export-client-contract --events`);
17
- * - `client.ts`: every operation (and event) as data, and `clientOf(operations)` over any wire;
18
- * - `entities.ts`: an `entity<T, C>()` per model a screen can list;
19
- * - `contract.json`: the snapshot they were written from, for `metasOf`.
14
+ * - `domain/generated/models.ts`: the entities and value objects, only types;
15
+ * - `domain/generated/commands.ts`: every operation's Command and Response;
16
+ * - `domain/generated/events.ts`: the domain events and `DomainEvent`, their union — when the
17
+ * contract was exported with them (`export-client-contract --events`);
18
+ * - `domain/generated/index.ts`: the three, re-exported;
19
+ * - `domain/generated/contract.json`: the snapshot they were written from, for `metasOf`;
20
+ * - `adapters/generated/client.ts`: every operation (and event) as data, and
21
+ * `clientOf(operations)` over any wire;
22
+ * - `adapters/generated/entities.ts`: an `entity<T, C>()` per model a screen can list.
20
23
  *
21
- * A bare metamodel (`export_metamodel`, no bindings) writes `domain.ts` and `contract.json` only.
24
+ * A bare metamodel (`export_metamodel`, no bindings) writes only `domain/generated/`.
22
25
  *
23
- * Context: it writes only into `--out`, and the same bytes for the same contract, so `make
24
- * verify-client` regenerates and fails on any difference. The folder is the generator's: keep
25
- * it out of the application's prettier and eslint, or a formatter rewrites what was generated.
26
+ * Context: it writes only its two `generated/` folders, whole every time — what is no longer
27
+ * generated goes —, and the same bytes for the same contract, so `make verify-client` regenerates
28
+ * and fails on any difference. The folders are the generator's: keep them out of the
29
+ * application's prettier and eslint, or a formatter rewrites what was generated.
26
30
  */
27
31
  const USAGE = [
28
32
  "usage: sincpro-client generate <contract.json> --out <dir> [--domain <name>] [--base <path>]",
@@ -129,15 +133,16 @@ function main(args) {
129
133
  const metamodel = JSON.parse(readFileSync(asked.source, "utf8"));
130
134
  if (asked.command === "scaffold")
131
135
  return scaffold(metamodel, asked.out, asked.operations);
132
- const files = { "domain.ts": domainFileOf(metamodel) };
133
- if (metamodel.bindings !== undefined) {
134
- files["client.ts"] = clientFileOf(metamodel, asked.options);
135
- files["entities.ts"] = entitiesFileOf(metamodel, asked.options);
136
+ const files = generatedFilesOf(metamodel, asked.options);
137
+ files[`${GENERATED_DOMAIN}/contract.json`] =
138
+ `${JSON.stringify(canonical(metamodel), null, 2)}\n`;
139
+ for (const folder of [GENERATED_DOMAIN, GENERATED_ADAPTERS])
140
+ rmSync(join(asked.out, folder), { recursive: true, force: true });
141
+ for (const [name, source] of Object.entries(files)) {
142
+ const path = join(asked.out, name);
143
+ mkdirSync(dirname(path), { recursive: true });
144
+ writeFileSync(path, source);
136
145
  }
137
- files["contract.json"] = `${JSON.stringify(canonical(metamodel), null, 2)}\n`;
138
- mkdirSync(asked.out, { recursive: true });
139
- for (const [name, source] of Object.entries(files))
140
- writeFileSync(join(asked.out, name), source);
141
146
  console.log(`✓ ${aliasOf(metamodel)} → ${asked.out} (${Object.keys(files).join(", ")})`);
142
147
  return 0;
143
148
  }