@sincpro/client-framework 2.10.0 → 3.0.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 (49) hide show
  1. package/AGENTS.md +16 -7
  2. package/README.md +83 -45
  3. package/dist/client/adapters/json-rpc.d.ts +4 -0
  4. package/dist/client/adapters/json-rpc.js +44 -38
  5. package/dist/client/adapters/memory.d.ts +5 -7
  6. package/dist/client/adapters/memory.js +82 -62
  7. package/dist/client/adapters/rest-operations.d.ts +6 -2
  8. package/dist/client/adapters/rest-operations.js +8 -5
  9. package/dist/client/adapters/rest.d.ts +2 -7
  10. package/dist/client/adapters/rest.js +12 -18
  11. package/dist/client/domain/answer.d.ts +28 -0
  12. package/dist/client/domain/answer.js +52 -0
  13. package/dist/client/domain/changes.d.ts +24 -19
  14. package/dist/client/domain/changes.js +18 -9
  15. package/dist/client/domain/entity.d.ts +74 -212
  16. package/dist/client/domain/entity.js +39 -117
  17. package/dist/client/domain/operation.d.ts +22 -1
  18. package/dist/client/domain/operation.js +4 -0
  19. package/dist/client/domain/transport.d.ts +8 -6
  20. package/dist/client/domain/transport.js +3 -3
  21. package/dist/client/index.d.ts +13 -7
  22. package/dist/client/index.js +13 -7
  23. package/dist/client/services/api.d.ts +39 -0
  24. package/dist/client/services/api.js +38 -0
  25. package/dist/client/services/changes.d.ts +13 -12
  26. package/dist/client/services/changes.js +14 -13
  27. package/dist/client/services/guarded.js +3 -3
  28. package/dist/client/services/propagation.d.ts +9 -11
  29. package/dist/client/services/propagation.js +9 -11
  30. package/dist/client/services/reads.d.ts +38 -0
  31. package/dist/client/services/reads.js +46 -0
  32. package/dist/client/services/selection.d.ts +7 -6
  33. package/dist/client/services/selection.js +6 -5
  34. package/dist/codegen/domain/names.d.ts +16 -1
  35. package/dist/codegen/domain/names.js +43 -0
  36. package/dist/codegen/services/client.d.ts +7 -7
  37. package/dist/codegen/services/client.js +120 -52
  38. package/dist/codegen/services/entities.d.ts +9 -12
  39. package/dist/codegen/services/entities.js +76 -130
  40. package/dist/codegen/services/rest.d.ts +1 -6
  41. package/dist/codegen/services/rest.js +0 -11
  42. package/dist/codegen/services/scaffold.js +5 -2
  43. package/dist/core/domain/services.d.ts +1 -1
  44. package/dist/core/domain/services.js +1 -1
  45. package/dist/core/entrypoint/screens.d.ts +14 -4
  46. package/dist/core/entrypoint/screens.js +33 -141
  47. package/dist/core/index.d.ts +2 -2
  48. package/dist/core/index.js +1 -1
  49. package/package.json +1 -1
package/AGENTS.md CHANGED
@@ -168,7 +168,7 @@ module has only the layers it needs, and says what it offers in its own `index.t
168
168
  tests; do not claim Metro (Babel) or web bundler support without testing those configurations.
169
169
  - **A run binds what says it can be bound, never what looks like a transport.** A dependency is
170
170
  bound only when it carries `BIND`: a generated client, `restOperations`, `jsonRpcOperations`,
171
- `restTransport`, `memoryTransport`, `guardedTransport`, `screensTransport`, and what a
171
+ `restTransport`, `memoryTransport`, `guardedTransport`, `screensOperations`, and what a
172
172
  platform marks with `bindableOperations(…)` / `bindableTransport(…)`. Nothing else — not an
173
173
  object with `list`/`one`/`send`, not one with a `call` — is ever wrapped: an application's
174
174
  abstraction reaches its use cases as it is.
@@ -186,12 +186,21 @@ module has only the layers it needs, and says what it offers in its own `index.t
186
186
  - **A store's `load` may answer a new object each time** (one that parses JSON does): `Context`
187
187
  keeps one object per `version`, so a screen can hand `values` to `useSyncExternalStore`. A store
188
188
  that changes without moving the version is a broken store.
189
- - **The generated client never names a wire.** A method is `transport.call(operations.X, input,
190
- options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `rpc`, `grpc`,
191
- `mcp`) are data in `operations`; an `OperationTransport` adapter reads the one of its wire
192
- (`restOperations`, `jsonRpcOperations`, a platform's gRPC) and throws `OperationNotPublished`
193
- for the rest. A run binds an `OperationTransport` as it binds a `Transport`: headers and signal.
194
- The REST `Transport` stays for `restOperations` and for screens (`entity()`, pages, drafts).
189
+ - **The generated client never names a wire, and is written by nobody.** `operations` is typed
190
+ data (`operation<I, O>({…})`) and `api` groups it by entity; `apiOf` implements it — no method
191
+ body is generated or written. The contract's bindings (`rest`, `rpc`, `grpc`, `mcp`) are data;
192
+ an `OperationTransport` adapter reads the one of its wire (`restOperations`,
193
+ `jsonRpcOperations`, a platform's gRPC) and throws `OperationNotPublished` for the rest. A run
194
+ binds an `OperationTransport` as it binds a `Transport`: headers and signal. The REST
195
+ `Transport` is that adapter's and files' (`uploadTo`); nothing above an adapter names a route.
196
+ - **An entity is an index over operations, and screens read through them.** `entity()` holds
197
+ which operation is its `search`, `get`, `edit`… — by `role`, never by path — and its Commands;
198
+ `readPage` / `readRecord` read any wire's answer (`pageFrom`, `recordOf`); the screens'
199
+ calls are one Feature (`screensOperations`, span `sincpro.operation`), never one per verb.
200
+ - **A change is the contract's, announced by the operation adapters.** `restOperations` and
201
+ `jsonRpcOperations` announce each Command — operation, entities, the keys its `targets` name
202
+ — on `processChanges`, answered or refused; a Query, a `preview` and a `dry_run` never. A
203
+ platform's adapter announces through `announced(feed, operation, input, call)`.
195
204
  - **What is generated is types, never classes.** A generated DTO is the remote contract: a
196
205
  class extending `Command` could be registered on the local bus, which is what keeps a remote
197
206
  operation and a local use case apart. Runtime knowledge goes in data (`operations`, `events`);
package/README.md CHANGED
@@ -758,76 +758,114 @@ const forge = clientOf(restOperations(restTransport({ base: "/v1", headers: sess
758
758
  // or clientOf(jsonRpcOperations({ endpoint: "/rpc", headers: session }))
759
759
  // or clientOf(grpcOperations(channel)) — a platform's adapter, the same port
760
760
 
761
- await forge.sendIssue({ issue_id: "acme-3", message: "hola" }); // ResponseSendIssue
761
+ await forge.issue.send({ issue_id: "acme-3", message: "hola" }); // ResponseSendIssue
762
+ await forge.project.list({ criteria }); // a group per entity; the context's own at the top
762
763
  ```
763
764
 
764
- | Piece | What it does |
765
- | --------------------------------- | ------------------------------------------------------------------------------------- |
766
- | `OperationTransport` port | `call(operation, input, options)`: an operation by who it is, over any wire |
767
- | `restOperations(transport)` | over REST: the path from the input, a Query's and a DELETE's query, a Command's body |
768
- | `jsonRpcOperations({ endpoint })` | over JSON-RPC 2.0: one `POST`, the operation's method, its input as named params |
769
- | `restTransport({ base })` | REST over `fetch`: `Idempotency-Key`, the server's `Problem`, model versions, Parquet |
770
- | `memoryTransport(tables)` | the same REST contract in memory, copying by the wire's rules — for tests and demos |
771
- | `assignableValues(route, values)` | an `Edit`'s values as the server reads them, for a memory `handle` |
772
- | `entity(key, routes)` | a model's routes and Commands, typed — what a generated `entities.ts` declares |
773
- | `retryKeys()` | one `Idempotency-Key` per gesture, kept while a retry may repeat it |
774
- | `guardedTransport(t, breaker)` | every call of a transport through a circuit breaker |
775
- | `screensTransport(transport)` | screen reads and writes run as use cases of `screens`: traced and reported |
776
- | `markedAs(wrapper, inner)` | a wrapper of a screens transport keeps its mark: one `screens` context, not two |
777
- | `parquetDecoder` (`./parquet`) | large pages read as Parquet through the same transport |
765
+ The generated file holds no method: `operations` is the contract as typed data
766
+ (`operation<CommandSendIssue, ResponseSendIssue>({…})`), `api` groups them by the entity they work
767
+ on — named by the operation without the entity's name, `CommandSendIssue` → `issue.send` —, and
768
+ `apiOf` implements that description. A method is changed where the client is made, keeping its
769
+ signature; the original carries the run like any other call:
770
+
771
+ ```ts
772
+ const forge = clientOf(transport, {
773
+ issue: { get: (original) => (input, options) => kept(input) ?? original(input, options) },
774
+ });
775
+ ```
776
+
777
+ | Piece | What it does |
778
+ | --------------------------------- | ---------------------------------------------------------------------------------------- |
779
+ | `OperationTransport` port | `call(operation, input, options)`: an operation by who it is, over any wire |
780
+ | `apiOf(description, transport)` | a description of operations, implemented: each a typed method; `overrides` replace one |
781
+ | `restOperations(transport)` | over REST: the path from the input, a Query's and a DELETE's query, a Command's body |
782
+ | `jsonRpcOperations({ endpoint })` | over JSON-RPC 2.0: one `POST`, the operation's method, its input as named params |
783
+ | `restTransport({ base })` | REST over `fetch`: `Idempotency-Key`, the server's `Problem`, model versions, Parquet |
784
+ | `memoryTransport(tables)` | the same REST server in memory, copying by the wire's rules — for tests and demos |
785
+ | `assignableValues(route, values)` | an `Edit`'s values as the server reads them, for a memory `handle` |
786
+ | `entity(key, operations)` | an index over a model's operations by role, and its Commands — a generated `entities.ts` |
787
+ | `readPage(t, entity, criteria)` | a page of an entity through its `search`, grouped or not, over any wire |
788
+ | `readRecord(t, entity, id)` | one record through its `get`, with the caller's draft when the entity keeps them |
789
+ | `retryKeys()` | one `Idempotency-Key` per gesture, kept while a retry may repeat it |
790
+ | `guardedTransport(t, breaker)` | every call of a transport through a circuit breaker |
791
+ | `screensOperations(transport)` | every operation a screen calls runs as a use case of `screens`: traced and reported |
792
+ | `markedAs(wrapper, inner)` | a wrapper of the screens' operations keeps their mark: one `screens` context, not two |
793
+ | `parquetDecoder` (`./parquet`) | large pages read as Parquet through the same transport |
778
794
 
779
795
  Inside a Feature, inject the generated client as it is: the run binds it, so every call carries
780
796
  its trace (`traceparent`), its context (`sincpro-context`) and its signal — as headers over HTTP,
781
- as metadata where a platform's adapter puts them. `screensTransport` and `entity()` stay on the
782
- REST `Transport`: they are how a screen reads pages of an entity, with its model and its drafts.
797
+ as metadata where a platform's adapter puts them.
798
+
799
+ A screen reads and writes through the same operations, never through a route. An entity is an
800
+ index over them — which is its `search`, its `get`, its `edit`, its trash, its history, its
801
+ export, and its Commands by name — read off the contract by the generator, so an entity exists
802
+ over JSON-RPC as over REST. `readPage` asks its `search` with the criteria as plain JSON (REST
803
+ writes it in `?criteria=`, JSON-RPC as its params) and reads the answer as `pageFrom` reads any
804
+ page; `readRecord` asks its `get` with the id in the field the operation names, and reads the
805
+ one field of its own beside the envelope (`recordOf`). The definition of the model is the
806
+ contract's (`metasOf`) or one a platform keeps, given as `meta`: an answer says only its version.
807
+
808
+ ```ts
809
+ const operations = screensOperations(restOperations(restTransport({ base: "/v1" })), "web");
810
+ const page = await readPage(operations, issues, criteria<Issue>().limit(20), { meta });
811
+ const { record, draft } = await readRecord(operations, projects, "acme");
812
+ await operations.call(
813
+ issues.operations.commands.send,
814
+ targeted(issues, send, "acme-3", { message }),
815
+ );
816
+ ```
783
817
 
784
818
  An edit — the backend's `Edit`, role `edit` — creates a record under the key its caller names.
785
819
  Its generated method mints one when the input names none (`newEntityId`, a UUID v7, as the
786
- server would), so `forge.editProject({ values, action: "save" })` creates a project over any
820
+ server would), so `forge.project.edit({ values, action: "save" })` creates a project over any
787
821
  wire, REST's `PUT /projects/{id}/edit` included. A screen that keeps a draft of a new record
788
822
  names its key once, so every save of the draft reaches the same record. A Command that answers
789
823
  nothing — a `DELETE`'s 204 — resolves `null`, never `undefined`, over REST and in memory alike.
790
824
 
791
- A `DELETE` — the backend's `Delete`, role `delete`, an entity's `delete` route — is read from its
825
+ A `DELETE` — the backend's `Delete`, role `delete`, an entity's `delete` — is read from its
792
826
  URL, never from a body. `restTransport` sends its fields in the query string, as the server decodes
793
827
  them (plain values as text, anything else as JSON): `DELETE /projects/acme?dry_run=true` answers
794
828
  the `Preview` of what would go, and `origin_version` refuses a delete of a record that moved on.
795
829
  Sent in a body they are dropped, and a rehearsal would run the real delete.
796
830
 
797
831
  A trash — the backend's `Archive`, `Restore` and `Purge`, roles `archive`, `restore` and `purge` —
798
- is three more routes of an entity: `archive` and `restore` by the record's key, `purge` over the
832
+ is three more operations of an entity: `archive` and `restore` by the record's key, `purge` over the
799
833
  whole collection (`older_than`, a duration as the contract writes it: `"P30D"`). Each answers
800
834
  nothing — `null` — or, with `dry_run: true`, the `Preview` of what it would do; a purge's says how
801
835
  many would go (`data: { count }`). The trash itself is the entity's list asked for what is
802
836
  archived (`archived_at` not null), which every other reading leaves out.
803
837
 
804
838
  Which of the ways a screen reaches the backend fits a call — an entity's screens, the generated
805
- client over the screens transport, or a Command and its Feature — is in
839
+ client over the screens' operations, or a Command and its Feature — is in
806
840
  [docs/WEB.md](docs/WEB.md#which-way-a-screen-reaches-the-backend).
807
841
 
808
- A wrapper over a screens transport — a cache, a guard — keeps its mark, so the screens are not made
809
- twice: `guardedTransport` does it, and a platform's own wrapper calls `markedAs(wrapper, inner)`.
810
- One span then answers each screen read, whether the wrapper answered it from its own memory or not.
842
+ A wrapper over the screens' operations — a cache, a guard — keeps their mark, so the screens are
843
+ not made twice: `guardedTransport` does it, and a platform's own wrapper calls
844
+ `markedAs(wrapper, inner)`. One span then answers each screen call, whether the wrapper answered
845
+ it from its own memory or not.
811
846
 
812
847
  ### What a write changed
813
848
 
814
849
  A client keeps what it read — a cache, a list on screen, a record — and every one of them goes
815
- stale when a write lands, whoever wrote it. So every write says so: `restTransport` and
816
- `memoryTransport` announce each `send` on the process's change feed (`processChanges`), whether it
817
- came from a screen or from a use case's generated client, answered or refused. A preview and a dry
818
- run announce nothing. A reader follows the feed, never the writer's transport:
850
+ stale when a write lands, whoever wrote it. So every write says so: `restOperations` and
851
+ `jsonRpcOperations` announce each Command on the process's change feed (`processChanges`),
852
+ whether it came from a screen or from a use case's generated client, answered or refused. A
853
+ Query, a preview and a dry run announce nothing. A change is said in the contract's words — the
854
+ operation, its entities, the keys of the records it named —, the same over every wire. A reader
855
+ follows the feed, never the writer's transport:
819
856
 
820
857
  ```ts
821
858
  import { processChanges } from "@sincpro/client-framework";
822
859
 
823
- const stop = processChanges.follow((change) => forgetUnder(change.route)); // { method, route }
860
+ // { operation: "shop.CommandPayOrder", entities: ["Order"], keys: { Order: ["O-7"] } }
861
+ const stop = processChanges.follow((change) => forget(change.entities, change.keys));
824
862
  stop();
825
863
  ```
826
864
 
827
- A change says only what was written; what it touches — the collections a route names, a record's
828
- history — is each reader's to decide. A transport given `changes` announces there instead (a test,
829
- a transport that must not be heard), and a platform's own adapter wraps its `send` in
830
- `announced(feed, method, route, body, send)`.
865
+ What a change touches is each reader's to decide: the records it named, or every reading of an
866
+ entity when it named none (a Command that creates). An adapter given `changes` announces there
867
+ instead (a test, one that must not be heard), and a platform's own adapter (gRPC) wraps its call
868
+ in `announced(feed, operation, input, call)`.
831
869
 
832
870
  ### Sending a file
833
871
 
@@ -872,8 +910,8 @@ const recipients = toggled(
872
910
  );
873
911
  sizeOf(recipients); // 36
874
912
  const keys = await keysOf(recipients, {
875
- transport,
876
- route: "/contacts",
913
+ transport: operations,
914
+ entity: contacts,
877
915
  identity: "id",
878
916
  limit: 200,
879
917
  });
@@ -943,14 +981,14 @@ sincpro-client check --root src
943
981
  `generate` writes, from the contract the backend exports — never edited, written again whole —,
944
982
  each file in the layer it belongs to, under the bounded context's folder (`--out`):
945
983
 
946
- | File | What |
947
- | -------------------------------- | --------------------------------------------------------------------------------------------- |
948
- | `domain/generated/models.ts` | the entities and value objects: a type per model, and the definitions they hold |
949
- | `domain/generated/commands.ts` | every operation's Command and Response, and the `<Name>Input` a caller sends |
950
- | `domain/generated/events.ts` | the domain events and `DomainEvent`, their union — when the contract carries them |
951
- | `domain/generated/index.ts` | the three, re-exported: `import type * as remote from "../domain/generated"` |
952
- | `adapters/generated/client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
953
- | `adapters/generated/entities.ts` | each entity's list, record, edit, delete, trash, export, Commands and history, for screens |
984
+ | File | What |
985
+ | -------------------------------- | ------------------------------------------------------------------------------------------------ |
986
+ | `domain/generated/models.ts` | the entities and value objects: a type per model, and the definitions they hold |
987
+ | `domain/generated/commands.ts` | every operation's Command and Response, and the `<Name>Input` a caller sends |
988
+ | `domain/generated/events.ts` | the domain events and `DomainEvent`, their union — when the contract carries them |
989
+ | `domain/generated/index.ts` | the three, re-exported: `import type * as remote from "../domain/generated"` |
990
+ | `adapters/generated/client.ts` | `operations` (typed data), `api` (by entity), `Api`, `clientOf(transport, overrides?)`, `events` |
991
+ | `adapters/generated/entities.ts` | each entity's operations by role — search, get, edit, trash, export, history — and its Commands |
954
992
 
955
993
  The backend keeps them apart — the domain's words, the application layer's DTOs, the facts, the
956
994
  adapters to another system —, and so does the application: each beside its own code of that layer.
@@ -1044,7 +1082,7 @@ needs them.
1044
1082
  | Entity ref | `"billing.Invoice:0192…"` | `EntityRef`, `parseEntityRef`, `entityRefOf` |
1045
1083
  | Bytes | `{ "$bytes": "<base64>" }` | `valuesOf`, `readValues` |
1046
1084
  | Collection | items, count and cursor | `collectionOf`, `isPartial`, `relatedCriteria` |
1047
- | Export | Parquet, Arrow or JSON Lines | `downloadRoute`, `exportRoute` |
1085
+ | Export | Parquet, Arrow or JSON Lines | an entity's `export` (`streamed`), `Download` |
1048
1086
  | Upload | raw bytes to an upload id, never JSON | `uploadTo` |
1049
1087
 
1050
1088
  `Decimal` and `Money` compute exactly, on `BigInt`; a decimal never becomes a `number` and a day
@@ -1139,7 +1177,7 @@ src/
1139
1177
  domain/ Command, DomainEvent, Response, Feature, ApplicationService, FeatureBus,
1140
1178
  ErrorHandler, the pipeline's extension points
1141
1179
  services/ the execution pipeline, interceptors, dependency binding, the handler chain
1142
- entrypoint/ BoundedContext, screensTransport
1180
+ entrypoint/ BoundedContext, screensOperations
1143
1181
  infrastructure/ configureProcess, configureLogger, processListeners
1144
1182
  event_driven/
1145
1183
  domain/ Envelope, the messages (an event's, a Command's), the MessageQueue,
@@ -1,3 +1,4 @@
1
+ import type { ChangeFeed } from "../domain/changes.js";
1
2
  import { type OperationTransport } from "../domain/operation.js";
2
3
  import { type FailureKind, type Problem } from "@sincpro/criteria";
3
4
  export type JsonRpcOptions = {
@@ -7,6 +8,8 @@ export type JsonRpcOptions = {
7
8
  headers?: Record<string, string> | (() => Record<string, string>);
8
9
  /** Defaults to the global `fetch`. Inject one for tests, or a platform's. */
9
10
  fetch?: typeof fetch;
11
+ /** Where each write is announced (`Change`): the process's feed (`processChanges`) by default. */
12
+ changes?: ChangeFeed;
10
13
  };
11
14
  /**
12
15
  * A JSON-RPC call that failed: the error the gateway answered — its `code` and, when it sent
@@ -35,6 +38,7 @@ export declare class JsonRpcError extends Error {
35
38
  * (its `message` the detail when the problem has none).
36
39
  * 4. No answer (the network, an `AbortError` aside): a `JsonRpcError` nobody answered — it may
37
40
  * have run.
41
+ * 5. A write's change announced on `changes`, whatever it answered (`announced`).
38
42
  * Final: the `result`, the operation's answer as the contract describes it.
39
43
  */
40
44
  export declare function jsonRpcOperations(options: JsonRpcOptions): OperationTransport;
@@ -1,4 +1,5 @@
1
1
  import { OperationNotPublished, } from "../domain/operation.js";
2
+ import { announced, processChanges } from "../services/changes.js";
2
3
  import { bindableOperations } from "../services/propagation.js";
3
4
  import { kindOfJsonRpcCode } from "../../common/failures.js";
4
5
  import { readProblem } from "@sincpro/criteria";
@@ -45,54 +46,59 @@ let next = 0;
45
46
  * (its `message` the detail when the problem has none).
46
47
  * 4. No answer (the network, an `AbortError` aside): a `JsonRpcError` nobody answered — it may
47
48
  * have run.
49
+ * 5. A write's change announced on `changes`, whatever it answered (`announced`).
48
50
  * Final: the `result`, the operation's answer as the contract describes it.
49
51
  */
50
52
  export function jsonRpcOperations(options) {
51
53
  const send = options.fetch ?? ((...args) => fetch(...args));
52
54
  const own = () => typeof options.headers === "function" ? options.headers() : options.headers;
55
+ const changes = options.changes ?? processChanges;
53
56
  return bindableOperations({
54
57
  async call(operation, input, call = {}) {
55
58
  const method = operation.rpc?.method;
56
59
  if (method === undefined)
57
60
  throw new OperationNotPublished(operation.identity, "JSON-RPC");
58
- const id = ++next;
59
- let response;
60
- try {
61
- response = await send(options.endpoint, {
62
- method: "POST",
63
- headers: {
64
- "Content-Type": "application/json",
65
- Accept: "application/json",
66
- ...own(),
67
- ...call.headers,
68
- ...(call.idempotencyKey ? { "Idempotency-Key": call.idempotencyKey } : {}),
69
- },
70
- body: JSON.stringify({ jsonrpc: "2.0", id, method, params: input ?? {} }),
71
- ...(call.signal ? { signal: call.signal } : {}),
72
- });
73
- }
74
- catch (error) {
75
- if (error?.name === "AbortError")
76
- throw error;
77
- throw new JsonRpcError(method, null, null, `${method} got no answer`);
78
- }
79
- const text = await response.text();
80
- let answer;
81
- try {
82
- answer = JSON.parse(text);
83
- }
84
- catch {
85
- throw new JsonRpcError(method, null, readProblem(text), `${method} answered no JSON-RPC`);
86
- }
87
- if (answer.error !== undefined) {
88
- const { code, message, data } = answer.error;
89
- const said = typeof message === "string" ? message : undefined;
90
- const problem = readProblem(data);
91
- throw new JsonRpcError(method, typeof code === "number" ? code : null, problem && problem.detail === undefined && said
92
- ? { ...problem, detail: said }
93
- : problem, said);
94
- }
95
- return answer.result;
61
+ return announced(changes, operation, input, () => requested(method, input, call));
96
62
  },
97
63
  });
64
+ async function requested(method, input, call) {
65
+ const id = ++next;
66
+ let response;
67
+ try {
68
+ response = await send(options.endpoint, {
69
+ method: "POST",
70
+ headers: {
71
+ "Content-Type": "application/json",
72
+ Accept: "application/json",
73
+ ...own(),
74
+ ...call.headers,
75
+ ...(call.idempotencyKey ? { "Idempotency-Key": call.idempotencyKey } : {}),
76
+ },
77
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params: input ?? {} }),
78
+ ...(call.signal ? { signal: call.signal } : {}),
79
+ });
80
+ }
81
+ catch (error) {
82
+ if (error?.name === "AbortError")
83
+ throw error;
84
+ throw new JsonRpcError(method, null, null, `${method} got no answer`);
85
+ }
86
+ const text = await response.text();
87
+ let answer;
88
+ try {
89
+ answer = JSON.parse(text);
90
+ }
91
+ catch {
92
+ throw new JsonRpcError(method, null, readProblem(text), `${method} answered no JSON-RPC`);
93
+ }
94
+ if (answer.error !== undefined) {
95
+ const { code, message, data } = answer.error;
96
+ const said = typeof message === "string" ? message : undefined;
97
+ const problem = readProblem(data);
98
+ throw new JsonRpcError(method, typeof code === "number" ? code : null, problem && problem.detail === undefined && said
99
+ ? { ...problem, detail: said }
100
+ : problem, said);
101
+ }
102
+ return answer.result;
103
+ }
98
104
  }
@@ -1,4 +1,3 @@
1
- import type { ChangeFeed } from "../domain/changes.js";
2
1
  import { type Draft, type Method, type Transport, type Uploaded } from "../domain/transport.js";
3
2
  import type { AnyRecord, Criteria, Meta, Problem } from "@sincpro/criteria";
4
3
  /**
@@ -13,7 +12,9 @@ import type { AnyRecord, Criteria, Meta, Problem } from "@sincpro/criteria";
13
12
  * real server answers, only the transport changes.
14
13
  *
15
14
  * A record is found at `<list route>/<id>`, by the field the model fetches by (`get_id`, else
16
- * the identity) — the convention sincpro_framework's REST routes follow.
15
+ * the identity) — the convention sincpro_framework's REST routes follow. A `GET` is answered as
16
+ * the server answers it (`read`): `<list route>?criteria=…` with its records and the envelope, as
17
+ * an entity's `search` asks over `restOperations`, and `<list route>/<id>` with its one record.
17
18
  *
18
19
  * const transport = memoryTransport({
19
20
  * "/invoices": { meta: invoiceMeta, rows: invoices },
@@ -38,8 +39,8 @@ export type MemoryOptions = {
38
39
  * URL.
39
40
  */
40
41
  handle?: (method: Method, route: string, body: unknown) => unknown;
41
- /** Answer a read that is neither a page nor a record (`GET /me`), its route with its query.
42
- * Without it, the transport has no `read`. */
42
+ /** Answer a read that is neither a page nor a record (`GET /me`), its route with its query —
43
+ * `undefined`: the tables answer it, as an entity's `search` and `get` read them. */
43
44
  read?: (route: string) => unknown;
44
45
  /**
45
46
  * Keep a file sent to an upload link (`PUT /files/uploads/{id}`), the way the service would:
@@ -56,9 +57,6 @@ export type MemoryOptions = {
56
57
  refuse?: (route: string) => (Problem & {
57
58
  status?: number;
58
59
  }) | undefined;
59
- /** Where each write is announced (`Change`), as a real server's transport does: the
60
- * process's feed (`processChanges`) by default. */
61
- changes?: ChangeFeed;
62
60
  };
63
61
  export declare function memoryTransport(tables: Readonly<Record<string, MemoryTable>>, options?: MemoryOptions): Transport;
64
62
  export type AssignableOptions = {
@@ -1,5 +1,4 @@
1
1
  import { TransportError, } from "../domain/transport.js";
2
- import { announced, processChanges } from "../services/changes.js";
3
2
  import { bindableTransport } from "../services/propagation.js";
4
3
  import { pack, readValues } from "../../common/serialization.js";
5
4
  import { answer, answerGroups } from "@sincpro/criteria/engine";
@@ -25,7 +24,6 @@ function wait(ms, signal) {
25
24
  }
26
25
  export function memoryTransport(tables, options = {}) {
27
26
  const answered = new Map();
28
- const changes = options.changes ?? processChanges;
29
27
  async function check(route, signal) {
30
28
  await wait(options.latency ?? 0, signal);
31
29
  const refused = options.refuse?.(route);
@@ -47,39 +45,66 @@ export function memoryTransport(tables, options = {}) {
47
45
  });
48
46
  return table;
49
47
  }
48
+ /** A page under `criteria` — grouped when it groups, counted over EVERY row that matches,
49
+ * each group with the criteria that opens it —, the way the server's aggregation answers. */
50
+ function pageAt(route, criteria) {
51
+ options.observe?.(route, criteria);
52
+ const table = tableAt(route);
53
+ const grouped = (criteria.grouping?.group_by?.length ?? 0) > 0;
54
+ const page = grouped
55
+ ? answerGroups(table.rows, criteria, table.meta)
56
+ : answer(table.rows, criteria, table.meta);
57
+ // A copy, as over a wire: a screen holding a row must not see the server change it.
58
+ return { ...page, rows: copyOf(page.rows) };
59
+ }
60
+ /** The record at `<list route>/<id>`, found by the field its model fetches by. */
61
+ function recordAt(route) {
62
+ // A record's route may carry a question (`?draft=true`): the id is the path's last part.
63
+ const path = route.split("?")[0] ?? route;
64
+ const slash = path.lastIndexOf("/");
65
+ const table = tableAt(path.slice(0, slash));
66
+ const id = decodeURIComponent(path.slice(slash + 1));
67
+ const key = table.meta.get_id || table.meta.identity;
68
+ const record = table.rows.find((row) => String(row[key]) === id);
69
+ if (record === undefined)
70
+ throw new TransportError(route, 404, {
71
+ kind: "not_found",
72
+ reason: "AGGREGATE_NOT_FOUND",
73
+ next_step: "do_not_retry",
74
+ retryable: false,
75
+ errors: [],
76
+ extensions: {},
77
+ detail: `${table.meta.aggregate} ${id} does not exist.`,
78
+ });
79
+ return { table, record };
80
+ }
81
+ /**
82
+ * A `GET` as sincpro_framework answers it: a search (`?criteria=`, as `restOperations` writes
83
+ * it) with its records — the one field of its own — and its envelope; a record with its own.
84
+ */
85
+ function served(route) {
86
+ const [path = route, query = ""] = route.split("?");
87
+ if (tables[path] !== undefined) {
88
+ const written = new URLSearchParams(query).get("criteria");
89
+ const page = pageAt(route, written === null ? {} : JSON.parse(written));
90
+ return {
91
+ records: page.rows,
92
+ cursor: page.cursor,
93
+ count: page.count,
94
+ dropped: page.dropped,
95
+ ...(page.version === null ? {} : { model_version: page.version }),
96
+ };
97
+ }
98
+ return { record: recordAt(route).record, draft: options.draft?.(route) ?? null };
99
+ }
50
100
  return bindableTransport({
51
101
  async list(route, criteria, signal) {
52
- options.observe?.(route, criteria);
53
102
  await check(route, signal);
54
- const table = tableAt(route);
55
- // A grouped question is answered with the groups — counted over EVERY row that matches,
56
- // each with the criteria that opens it — the way the server's aggregation answers it.
57
- const grouped = (criteria.grouping?.group_by?.length ?? 0) > 0;
58
- const page = grouped
59
- ? answerGroups(table.rows, criteria, table.meta)
60
- : answer(table.rows, criteria, table.meta);
61
- // A copy, as over a wire: a screen holding a row must not see the server change it.
62
- return { ...page, rows: copyOf(page.rows) };
103
+ return pageAt(route, criteria);
63
104
  },
64
105
  async one(route, signal) {
65
106
  await check(route, signal);
66
- // A record's route may carry a question (`?draft=true`): the id is the path's last part.
67
- const path = route.split("?")[0] ?? route;
68
- const slash = path.lastIndexOf("/");
69
- const table = tableAt(path.slice(0, slash));
70
- const id = decodeURIComponent(path.slice(slash + 1));
71
- const key = table.meta.get_id || table.meta.identity;
72
- const record = table.rows.find((row) => String(row[key]) === id);
73
- if (record === undefined)
74
- throw new TransportError(route, 404, {
75
- kind: "not_found",
76
- reason: "AGGREGATE_NOT_FOUND",
77
- next_step: "do_not_retry",
78
- retryable: false,
79
- errors: [],
80
- extensions: {},
81
- detail: `${table.meta.aggregate} ${id} does not exist.`,
82
- });
107
+ const { table, record } = recordAt(route);
83
108
  return {
84
109
  record: copyOf(record),
85
110
  meta: table.meta,
@@ -88,40 +113,35 @@ export function memoryTransport(tables, options = {}) {
88
113
  };
89
114
  },
90
115
  async send(method, route, body, signal, sending) {
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. A Command that
109
- // answers nothing is `null`, as REST's 204 is — never `undefined`.
110
- const answer = (await options.handle(method, route, copyOf(body))) ?? null;
111
- if (key !== undefined)
112
- answered.set(key, copyOf(answer));
113
- return answer;
114
- });
116
+ await check(route, signal);
117
+ // A key already answered is answered again, without running the Command twice — what
118
+ // sincpro_framework's `@idempotency` does with a repeated `Idempotency-Key`.
119
+ const key = sending?.idempotencyKey;
120
+ if (key !== undefined && answered.has(key))
121
+ return copyOf(answered.get(key));
122
+ if (options.handle === undefined)
123
+ throw new TransportError(route, 404, {
124
+ kind: "not_found",
125
+ reason: "ROUTE_NOT_FOUND",
126
+ next_step: "fix_request",
127
+ retryable: false,
128
+ errors: [],
129
+ extensions: {},
130
+ detail: `Nothing answers ${method} ${route}.`,
131
+ });
132
+ // A deep copy: what the caller sent is not what the server keeps. A Command that
133
+ // answers nothing is `null`, as REST's 204 is — never `undefined`.
134
+ const answer = (await options.handle(method, route, copyOf(body))) ?? null;
135
+ if (key !== undefined)
136
+ answered.set(key, copyOf(answer));
137
+ return answer;
138
+ },
139
+ async read(route, signal) {
140
+ await check(route, signal);
141
+ // A copy, as every answer: over a wire nobody holds the server's object.
142
+ const given = await options.read?.(route);
143
+ return copyOf(given === undefined ? served(route) : given);
115
144
  },
116
- ...(options.read === undefined
117
- ? {}
118
- : {
119
- async read(route, signal) {
120
- await check(route, signal);
121
- // A copy, as every answer: over a wire nobody holds the server's object.
122
- return copyOf(await options.read(route));
123
- },
124
- }),
125
145
  ...(options.upload === undefined
126
146
  ? {}
127
147
  : {
@@ -1,3 +1,4 @@
1
+ import type { ChangeFeed } from "../domain/changes.js";
1
2
  import { type OperationTransport } from "../domain/operation.js";
2
3
  import { type Transport } from "../domain/transport.js";
3
4
  /**
@@ -14,8 +15,11 @@ import { type Transport } from "../domain/transport.js";
14
15
  * answer as it came; one that answers bytes (`streamed`, an export) is downloaded.
15
16
  * 4. Anything else — a Command — is sent with the gesture's `Idempotency-Key`: the input whole as
16
17
  * its body; a `DELETE`, read from its URL as a `GET` is, only the fields its path did not take
17
- * — the REST transport writes them as its query (`restTransport`), and a key is not said twice.
18
+ * — the REST transport writes them as its query (`restTransport`), and a key is not said twice
19
+ * —, and its change announced on `changes` (`processChanges` by default), whatever it answered.
18
20
  * Final: the operation's answer, as the contract describes it — `null` for one that answers
19
21
  * nothing (a `DELETE`'s 204).
20
22
  */
21
- export declare function restOperations(transport: Transport): OperationTransport;
23
+ export declare function restOperations(transport: Transport, options?: {
24
+ changes?: ChangeFeed;
25
+ }): OperationTransport;