@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
@@ -3,14 +3,14 @@ import { type GenerateOptions } from "./rest.js";
3
3
  /**
4
4
  * The TypeScript of the client of `metamodel`, as the text of one file next to its `domain.ts`.
5
5
  *
6
- * 1. Every operation, by its local name, as data: identity, role, `query`, entities, targets,
7
- * whether it answers bytes, and the binding of each wire that publishes it.
8
- * 2. A method per operation, named by `methodOf`: its input — optional when nothing in it is
9
- * required — and the call's options (headers, signal, idempotency key), answering its answer.
10
- * An edit's method mints the record's key when the input names none (`mintsKey`).
6
+ * 1. Every operation, by its local name, as typed data: identity, role, `query`, entities,
7
+ * targets, whether it answers bytes, the field an edit mints, the binding of each wire that
8
+ * publishes it, and — as types — its input and its answer.
9
+ * 2. The API: a group per entity (`issue.cancel`), the context's own operations at the top
10
+ * (`groupOf`, `membersOf`), each entry documented as the operation is.
11
11
  * 3. When the contract carries them, every domain event as data, by its type's name: its wire
12
12
  * name, and whether the bounded context records it or handles it.
13
- * Final: `clientOf(transport)` over an `OperationTransport`, bound to each run that uses it; two
14
- * methods with one name are refused, naming both.
13
+ * Final: `Api`, its type, and `clientOf(transport, overrides?)`, which `apiOf` implements over an
14
+ * `OperationTransport`, bound to each run that uses it.
15
15
  */
16
16
  export declare function clientFileOf(metamodel: Metamodel, options?: GenerateOptions): string;
@@ -1,16 +1,17 @@
1
- import { aliasOf, answerOf, claimed, deprecationOf, docOf, DOMAIN_MODULE, FRAMEWORK, headerOf, identifierOf, localOf, methodOf, recordLiteral, sorted, } from "../domain/names.js";
1
+ import { aliasOf, answerOf, claimed, deprecationOf, docOf, DOMAIN_MODULE, FRAMEWORK, groupNameOf, headerOf, identifierOf, localOf, memberOf, methodOf, ownerOf, recordLiteral, sorted, } from "../domain/names.js";
2
2
  import { restOf, } from "./rest.js";
3
3
  /**
4
- * The client of a bounded context as TypeScript: every operation as data, and a method for each
5
- * one, called by who it is through an `OperationTransport` — so a script, a test, a Feature or a
6
- * hook calls the service typed, over whatever wire the application injects.
4
+ * The client of a bounded context as TypeScript: every operation as typed data, and the API that
5
+ * groups them by the entity they work on (`issue.cancel`) — a description `apiOf` implements over
6
+ * an `OperationTransport`, so a script, a test, a Feature or a hook calls the service typed, over
7
+ * whatever wire the application injects.
7
8
  *
8
9
  * Context: the generated client names an operation and its input, never a route, a verb or an
9
10
  * RPC method: those are the contract's bindings, in `operations`, and the adapter reads the one of
10
11
  * its wire (`restOperations`, `jsonRpcOperations`, a platform's gRPC). So the same client, and the
11
12
  * Features that use it, run over REST today and JSON-RPC or gRPC tomorrow without regenerating.
12
- * Each method takes the operation's input and answers its answer, as the contract types them
13
- * (`domain.ts`).
13
+ * No method is written here: what a method does — its input, its answer, the key an edit mints —
14
+ * is the operation's data, and one function implements them all (`apiOf`).
14
15
  */
15
16
  const WIRES = [
16
17
  ["rest", "REST"],
@@ -44,13 +45,19 @@ function mintsKey(operation) {
44
45
  operation.input.properties?.[EDIT_KEY] !== undefined &&
45
46
  !(operation.input.required ?? []).includes(EDIT_KEY));
46
47
  }
47
- /** The input a method hands the transport: as the caller gave it, an edit's key minted if absent. */
48
- function inputOf(operation, optional) {
49
- if (mintsKey(operation))
50
- return `{ ...input, ${EDIT_KEY}: input?.${EDIT_KEY} || newEntityId() }`;
51
- return optional ? "input ?? {}" : "input";
48
+ /** The entities whose target field holds a list of keys (`list[EntityID[Order]]`), not one. */
49
+ function manyOf(operation) {
50
+ return Object.entries(operation.targets)
51
+ .filter(([, field]) => {
52
+ const schema = operation.input.properties?.[field];
53
+ const held = schema?.anyOf?.find((one) => one.type !== "null") ?? schema;
54
+ return held?.type === "array";
55
+ })
56
+ .map(([model]) => model)
57
+ .sort();
52
58
  }
53
- /** The data of one operation: what it is, and how each wire reaches it. */
59
+ /** The data of one operation: what it is, how each wire reaches it, and — as types — what it
60
+ * takes and answers. */
54
61
  function dataOf(metamodel, identity, operation, rest) {
55
62
  const lines = [
56
63
  ` identity: ${JSON.stringify(identity)},`,
@@ -61,6 +68,11 @@ function dataOf(metamodel, identity, operation, rest) {
61
68
  ];
62
69
  if (isStreamed(operation))
63
70
  lines.push(" streamed: true,");
71
+ const many = manyOf(operation);
72
+ if (many.length > 0)
73
+ lines.push(` many: ${JSON.stringify(many)},`);
74
+ if (mintsKey(operation))
75
+ lines.push(` mints: ${JSON.stringify(EDIT_KEY)},`);
64
76
  if (rest !== undefined)
65
77
  lines.push(` rest: { method: ${JSON.stringify(rest.method)}, path: ${JSON.stringify(rest.path)} },`);
66
78
  const rpc = metamodel.bindings?.rpc?.[identity];
@@ -72,70 +84,126 @@ function dataOf(metamodel, identity, operation, rest) {
72
84
  const mcp = metamodel.bindings?.mcp?.[identity];
73
85
  if (mcp !== undefined)
74
86
  lines.push(` mcp: { tool: ${JSON.stringify(mcp.tool)} },`);
75
- return ` ${localOf(metamodel, identity)}: {\n${lines.join("\n")}\n },`;
87
+ const local = localOf(metamodel, identity);
88
+ const optional = (operation.input.required ?? []).length === 0;
89
+ const input = optional ? `dto.${local} | undefined` : `dto.${local}`;
90
+ const typed = `operation<${input}, dto.${answerOf(metamodel, identity)}>`;
91
+ return ` ${local}: ${typed}({\n${lines.join("\n")}\n }),`;
92
+ }
93
+ /**
94
+ * The entity whose group an operation's method goes in: the one it works on — its only entity,
95
+ * or the one its answer carries (`ownerOf`), or the one record it targets —; none, and it is the
96
+ * context's own, at the top of the API.
97
+ */
98
+ function groupOf(metamodel, operation) {
99
+ const owner = ownerOf(metamodel, operation);
100
+ if (owner !== undefined)
101
+ return owner;
102
+ const targeted = Object.keys(operation.targets);
103
+ return targeted.length === 1 ? targeted[0] : undefined;
104
+ }
105
+ /**
106
+ * Every operation's place in the API: its group and its method. Two operations a group would
107
+ * call the same are both called by their whole name, so adding one never renames another.
108
+ */
109
+ function membersOf(metamodel) {
110
+ const members = sorted(metamodel.operations).map(([identity, operation]) => {
111
+ const local = localOf(metamodel, identity);
112
+ const group = groupOf(metamodel, operation);
113
+ const name = group === undefined ? methodOf(local) : memberOf(local, group);
114
+ return { identity, operation, group, name };
115
+ });
116
+ const placeOf = (one) => `${one.group ?? ""}.${one.name}`;
117
+ const counted = new Map();
118
+ for (const one of members)
119
+ counted.set(placeOf(one), (counted.get(placeOf(one)) ?? 0) + 1);
120
+ return members.map((one) => (counted.get(placeOf(one)) ?? 0) > 1
121
+ ? { ...one, name: methodOf(localOf(metamodel, one.identity)) }
122
+ : one);
123
+ }
124
+ /** The API's entry of one operation: its doc, its method, the operation it calls. */
125
+ function entryOf(metamodel, member, pad) {
126
+ const { identity, operation } = member;
127
+ const wires = wiresOf(metamodel, identity);
128
+ const doc = docOf([
129
+ operation.description,
130
+ deprecationOf(metamodel, operation),
131
+ mintsKey(operation)
132
+ ? `A new record's \`${EDIT_KEY}\` is minted here when the input names none (\`newEntityId\`).`
133
+ : undefined,
134
+ wires.length === 0 ? undefined : `Published over ${wires.join(", ")}.`,
135
+ ], pad);
136
+ return `${doc}${pad}${member.name}: operations.${localOf(metamodel, identity)},`;
137
+ }
138
+ /**
139
+ * The API as a description: a group per entity, by its name, with its operations; the
140
+ * context's own operations at the top. Every name is claimed once at each level.
141
+ */
142
+ function apiDescriptionOf(metamodel, members) {
143
+ const top = claimed();
144
+ const groups = new Map();
145
+ const own = [];
146
+ for (const member of members) {
147
+ if (member.group === undefined) {
148
+ top(member.name, `operation ${member.identity}`);
149
+ own.push(entryOf(metamodel, member, " "));
150
+ }
151
+ else
152
+ groups.set(member.group, [...(groups.get(member.group) ?? []), member]);
153
+ }
154
+ const grouped = [...groups.entries()]
155
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
156
+ .map(([model, inside]) => {
157
+ const name = groupNameOf(model);
158
+ top(name, `the operations of ${model}`);
159
+ const claim = claimed();
160
+ for (const member of inside)
161
+ claim(member.name, `operation ${member.identity}`);
162
+ return ` ${name}: {\n${inside.map((member) => entryOf(metamodel, member, " ")).join("\n")}\n },`;
163
+ });
164
+ return [...grouped, ...own].join("\n");
76
165
  }
77
166
  /**
78
167
  * The TypeScript of the client of `metamodel`, as the text of one file next to its `domain.ts`.
79
168
  *
80
- * 1. Every operation, by its local name, as data: identity, role, `query`, entities, targets,
81
- * whether it answers bytes, and the binding of each wire that publishes it.
82
- * 2. A method per operation, named by `methodOf`: its input — optional when nothing in it is
83
- * required — and the call's options (headers, signal, idempotency key), answering its answer.
84
- * An edit's method mints the record's key when the input names none (`mintsKey`).
169
+ * 1. Every operation, by its local name, as typed data: identity, role, `query`, entities,
170
+ * targets, whether it answers bytes, the field an edit mints, the binding of each wire that
171
+ * publishes it, and — as types — its input and its answer.
172
+ * 2. The API: a group per entity (`issue.cancel`), the context's own operations at the top
173
+ * (`groupOf`, `membersOf`), each entry documented as the operation is.
85
174
  * 3. When the contract carries them, every domain event as data, by its type's name: its wire
86
175
  * name, and whether the bounded context records it or handles it.
87
- * Final: `clientOf(transport)` over an `OperationTransport`, bound to each run that uses it; two
88
- * methods with one name are refused, naming both.
176
+ * Final: `Api`, its type, and `clientOf(transport, overrides?)`, which `apiOf` implements over an
177
+ * `OperationTransport`, bound to each run that uses it.
89
178
  */
90
179
  export function clientFileOf(metamodel, options = {}) {
91
- const claim = claimed();
92
- const data = [];
93
- const methods = [];
94
- let minting = false;
95
- for (const [identity, operation] of sorted(metamodel.operations)) {
96
- const local = localOf(metamodel, identity);
97
- data.push(dataOf(metamodel, identity, operation, restOf(metamodel, identity, options)));
98
- const method = methodOf(local);
99
- claim(method, `operation ${identity}`);
100
- const wires = wiresOf(metamodel, identity);
101
- const mints = mintsKey(operation);
102
- minting ||= mints;
103
- const doc = docOf([
104
- operation.description,
105
- deprecationOf(metamodel, operation),
106
- mints
107
- ? `A new record's \`${EDIT_KEY}\` is minted here when the input names none (\`newEntityId\`).`
108
- : undefined,
109
- wires.length === 0 ? undefined : `Published over ${wires.join(", ")}.`,
110
- ], " ");
111
- const optional = (operation.input.required ?? []).length === 0;
112
- methods.push([
113
- `${doc} ${method}: (input${optional ? "?" : ""}: dto.${local}, options?: OperationOptions) =>`,
114
- ` transport.call<dto.${answerOf(metamodel, identity)}>(operations.${local}, ${inputOf(operation, optional)}, options),`,
115
- ].join("\n"));
116
- }
180
+ const data = sorted(metamodel.operations).map(([identity, operation]) => dataOf(metamodel, identity, operation, restOf(metamodel, identity, options)));
181
+ const description = apiDescriptionOf(metamodel, membersOf(metamodel));
117
182
  const events = sorted(metamodel.events ?? {}).map(([name, event]) => ` ${identifierOf(event.title)}: { name: ${JSON.stringify(name)}, recorded: ${event.recorded}, handled: ${event.handled} },`);
118
183
  const imports = [
119
- `import { bindable,${minting ? " newEntityId," : ""} type OperationOptions, type OperationTransport } from "${FRAMEWORK}";`,
184
+ `import { type ApiOf, apiOf, operation, type OperationTransport, type Overrides } from "${FRAMEWORK}";`,
120
185
  "",
121
186
  `import type * as dto from "${DOMAIN_MODULE}";`,
122
187
  ].join("\n");
123
188
  const client = [
124
189
  "/**",
125
- ` * «${aliasOf(metamodel)}» over any wire: a method per operation, called by who it is. The transport`,
126
- " * decides how it travels — `restOperations(restTransport(…))`, `jsonRpcOperations(…)`, a",
127
- " * platform's —; used by a Feature, each call carries the run's trace, context and signal.",
190
+ ` * «${aliasOf(metamodel)}» over any wire: \`api\` implemented by \`apiOf\`. The transport decides how`,
191
+ " * it travels — `restOperations(restTransport(…))`, `jsonRpcOperations(…)`, a platform's —; used",
192
+ " * by a Feature, each call carries the run's trace, context and signal. `overrides` replaces a",
193
+ " * method with one that receives the original.",
128
194
  " */",
129
195
  ].join("\n");
130
196
  return `${[
131
197
  headerOf("The client", metamodel),
132
198
  imports,
133
- `/** Every operation of «${aliasOf(metamodel)}», as data: what it is, and how each wire reaches it. */\nexport const operations = {\n${data.join("\n")}\n} as const;`,
199
+ `/** Every operation of «${aliasOf(metamodel)}», as data: what it is, how each wire reaches it, what it takes and answers. */\nexport const operations = {\n${data.join("\n")}\n} as const;`,
200
+ `/** The API of «${aliasOf(metamodel)}»: its operations by the entity they work on, and its own at the top. */\nexport const api = {\n${description}\n} as const;`,
201
+ `/** What the API offers, method by method. */\nexport type Api = ApiOf<typeof api>;`,
134
202
  ...(events.length === 0
135
203
  ? []
136
204
  : [
137
205
  `/** Every domain event of «${aliasOf(metamodel)}» in the contract, as data: its wire name, and whether it records or handles it. */\nexport const events = {\n${events.join("\n")}\n} as const;`,
138
206
  ]),
139
- `${client}\nexport function clientOf(transport: OperationTransport) {\n return bindable(transport, (transport) => ({\n${methods.join("\n")}\n }));\n}`,
207
+ `${client}\nexport function clientOf(transport: OperationTransport, overrides?: Overrides<Api>): Api {\n return apiOf(api, transport, overrides);\n}`,
140
208
  ].join("\n\n")}\n`;
141
209
  }
@@ -1,17 +1,14 @@
1
1
  import type { Metamodel } from "../domain/metamodel.js";
2
- import { type GenerateOptions } from "./rest.js";
2
+ import type { GenerateOptions } from "./rest.js";
3
3
  /**
4
- * The TypeScript of the entities of `metamodel`, as the text of one file next to its `domain.ts`.
4
+ * The TypeScript of the entities of `metamodel`, as the text of one file next to its `client.ts`.
5
5
  *
6
- * 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
7
- * several) — none, and the model gets no entity, said in the file's own doc.
8
- * 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`,
9
- * and its trash's — `archive`, `restore` and `purge`, this one by its path —; its `events` — a
10
- * record's `DomainEvents` — as `history`, the same way; and its `export` — every record of a
11
- * criteria as a file — by its path.
12
- * 3. Every write of role `command` that concerns it: with `target` when its body names the
13
- * record, as it is when it creates one; its body typed without that field.
14
- * Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
15
- * them, for `FrameworkProvider entities`.
6
+ * 1. Per model, by name: the one `search` for it (`own` when there are several) — none, and the
7
+ * model gets no entity, said in the file's own doc.
8
+ * 2. Each other role the same way — `get` and `events` only when they name the record —, and
9
+ * `drafts` when its record is edited through `Edit` and read with the caller's draft.
10
+ * 3. Every operation of role `command` that concerns it, by its name without the entity's.
11
+ * Final: an `entity()` per model listed, keyed `<domain>:<kind>`, over the client's
12
+ * `operations`, and `entities`, all of them, for `FrameworkProvider entities`.
16
13
  */
17
14
  export declare function entitiesFileOf(metamodel: Metamodel, options?: GenerateOptions): string;
@@ -1,7 +1,20 @@
1
1
  import { entityKeyOf } from "../../client/domain/contract.js";
2
- import { aliasOf, answerOf, claimed, DOMAIN_MODULE, FRAMEWORK, headerOf, identifierOf, isEntity, localOf, methodOf, pluralOf, sorted, } from "../domain/names.js";
3
- import { ownerOf, restOf, WRITES, } from "./rest.js";
4
- /** The one operation of `role` for `entity` a transport can call, by `own` when there are many. */
2
+ import { aliasOf, claimed, CLIENT_MODULE, FRAMEWORK, headerOf, identifierOf, isEntity, localOf, memberOf, methodOf, ownerOf, pluralOf, sorted, } from "../domain/names.js";
3
+ /** The roles besides `search` an entity may have, in the order its declaration writes them. */
4
+ const ROLES = [
5
+ "get",
6
+ "edit",
7
+ "preview",
8
+ "delete",
9
+ "archive",
10
+ "restore",
11
+ "purge",
12
+ "events",
13
+ "export",
14
+ ];
15
+ /** Roles that read ONE record: they need the field naming it (`targets`). */
16
+ const OF_ONE = new Set(["get", "events"]);
17
+ /** The one operation of `role` for an entity, by `own` when there are many. */
5
18
  function oneOf(candidates, role) {
6
19
  if (candidates.length === 0)
7
20
  return undefined;
@@ -13,130 +26,65 @@ function oneOf(candidates, role) {
13
26
  const names = candidates.map((one) => `\`${one.local}\``).join(", ");
14
27
  return { missing: `${candidates.length} of role \`${role}\` (${names}) and none \`own\`` };
15
28
  }
16
- /** A route for `entity()`: the record's field in the path written `{id}`, as `entity()` fills it. */
17
- function recordPath(rest, field) {
18
- return field === undefined || field === "id"
19
- ? rest.path
20
- : rest.path.replace(`{${field}}`, "{id}");
21
- }
22
29
  /**
23
- * The field of a Command's body that names the one record of `model` it runs on. A list of keys
24
- * (`list[EntityID[Issue]]`, `issue_ids`) names many: `run(id, body)` has one id to give, so the
25
- * screen sends that list in the body itself.
30
+ * Its Commands by name — the operation's without the entity's (`memberOf`) —; two that a name
31
+ * would join keep their whole names, so adding one never renames another.
26
32
  */
27
- function singleTarget(operation, model) {
28
- const field = operation.targets[model];
29
- if (field === undefined)
30
- return undefined;
31
- const schema = operation.input.properties?.[field];
32
- const held = schema?.anyOf?.find((one) => one.type !== "null") ?? schema;
33
- return held?.type === "array" ? undefined : field;
33
+ function commandsOf(candidates, model) {
34
+ const named = candidates.map((one) => [memberOf(one.local, model), one.local]);
35
+ const counted = new Map();
36
+ for (const [name] of named)
37
+ counted.set(name, (counted.get(name) ?? 0) + 1);
38
+ return named.map(([name, local]) => [
39
+ (counted.get(name) ?? 0) > 1 ? methodOf(local) : name,
40
+ local,
41
+ ]);
34
42
  }
35
- function entitySourceOf(metamodel, model, domain, options, claim) {
36
- const reached = sorted(metamodel.operations).flatMap(([identity, operation]) => {
37
- const rest = restOf(metamodel, identity, options);
38
- return rest === undefined
39
- ? []
40
- : [
41
- {
42
- local: localOf(metamodel, identity),
43
- answer: answerOf(metamodel, identity),
44
- operation,
45
- rest,
46
- },
47
- ];
48
- });
49
- const reads = (role, method) => reached.filter((one) => one.operation.role === role &&
50
- method(one.rest.method) &&
51
- ownerOf(metamodel, one.operation) === model);
52
- const isGet = (verb) => verb === "GET";
53
- const isWrite = (verb) => WRITES.has(verb);
54
- const list = oneOf(reads("search", isGet), "search");
55
- if (list === undefined)
56
- return { missing: "no `search` a transport reads" };
57
- if ("missing" in list)
58
- return { missing: list.missing };
59
- // A list under a record (`/tenants/{tenant_id}/members`) keeps its keys: the screen gives
60
- // them as the list's parameters (`useListing(entity, { params })`), and `listRoute` fills them.
43
+ function entitySourceOf(metamodel, model, domain, claim) {
44
+ const all = sorted(metamodel.operations).map(([identity, operation]) => ({
45
+ local: localOf(metamodel, identity),
46
+ operation,
47
+ }));
48
+ const owned = (role) => all.filter((one) => one.operation.role === role && ownerOf(metamodel, one.operation) === model);
49
+ const search = oneOf(owned("search"), "search");
50
+ if (search === undefined)
51
+ return { missing: "no `search`" };
52
+ if ("missing" in search)
53
+ return { missing: search.missing };
61
54
  const missing = [];
62
- const routes = [` list: ${JSON.stringify(list.found.rest.path)},`];
63
- const one = oneOf(reads("get", isGet), "get");
64
- const edit = oneOf(reads("edit", isWrite), "edit");
65
- if (one !== undefined && "found" in one) {
66
- const field = one.found.operation.targets[model];
67
- // sincpro_framework's `Get` answers the caller's own draft only when asked (`draft`), and an
68
- // entity edited through `Edit` keeps its drafts there: its record is read with them, or a
69
- // draft kept on one visit never comes back on the next.
70
- const drafts = edit !== undefined &&
71
- "found" in edit &&
72
- one.found.operation.input.properties?.["draft"]?.type === "boolean";
73
- const path = `${recordPath(one.found.rest, field)}${drafts ? "?draft=true" : ""}`;
74
- if (field !== undefined && one.found.rest.fields.length === 1)
75
- routes.push(` one: ${JSON.stringify(path)},`);
76
- else
77
- missing.push(`one: \`${one.found.local}\` is at ${one.found.rest.path}`);
78
- }
79
- else if (one !== undefined)
80
- missing.push(`one: ${one.missing}`);
81
- // sincpro_framework's `Delete` (role `delete`) is the record's own route too, never a Command;
82
- // so are its trash's `Archive` and `Restore`, and `Purge`, the route of the whole collection.
83
- for (const role of ["edit", "preview", "delete", "archive", "restore", "purge"]) {
84
- const write = oneOf(reads(role, isWrite), role);
85
- if (write === undefined)
55
+ const lines = [
56
+ ` model: ${JSON.stringify(model)},`,
57
+ ` search: operations.${search.found.local},`,
58
+ ];
59
+ const chosen = new Map();
60
+ for (const role of ROLES) {
61
+ const one = oneOf(owned(role), role);
62
+ if (one === undefined)
86
63
  continue;
87
- if ("missing" in write) {
88
- missing.push(`${role}: ${write.missing}`);
89
- continue;
90
- }
91
- const field = write.found.operation.targets[model];
92
- const route = `${write.found.rest.method} ${recordPath(write.found.rest, field)}`;
93
- routes.push(` ${role}: ${JSON.stringify(route)},`);
94
- }
95
- // A record's events (sincpro_framework's `DomainEvents`): its history, read by the record's key.
96
- const events = oneOf(reads("events", isGet), "events");
97
- if (events !== undefined) {
98
- if ("missing" in events)
99
- missing.push(`history: ${events.missing}`);
64
+ if ("missing" in one)
65
+ missing.push(`${role}: ${one.missing}`);
66
+ else if (OF_ONE.has(role) && one.found.operation.targets[model] === undefined)
67
+ missing.push(`${role}: \`${one.found.local}\` names no ${model} in its input`);
100
68
  else {
101
- const field = events.found.operation.targets[model];
102
- if (field !== undefined && events.found.rest.fields.length === 1)
103
- routes.push(` history: ${JSON.stringify(recordPath(events.found.rest, field))},`);
104
- else
105
- missing.push(`history: \`${events.found.local}\` is at ${events.found.rest.path}`);
69
+ chosen.set(role, one.found);
70
+ lines.push(` ${role}: operations.${one.found.local},`);
106
71
  }
107
72
  }
108
- const exported = oneOf(reads("export", isGet), "export");
109
- if (exported !== undefined) {
110
- if ("missing" in exported)
111
- missing.push(`export: ${exported.missing}`);
112
- else
113
- routes.push(` export: ${JSON.stringify(exported.found.rest.path)},`);
114
- }
115
- const commands = reached.filter((one) => one.operation.role === "command" &&
116
- isWrite(one.rest.method) &&
117
- one.operation.entities.includes(model));
118
- const bodies = [];
119
- const answers = [];
120
- const named = [];
121
- for (const command of commands) {
122
- const method = methodOf(command.local);
123
- const target = singleTarget(command.operation, model);
124
- const route = `${command.rest.method} ${command.rest.path}`;
125
- bodies.push(target === undefined
126
- ? ` ${method}: dto.${command.local};`
127
- : ` ${method}: Omit<dto.${command.local}, ${JSON.stringify(target)}>;`);
128
- answers.push(` ${method}: dto.${command.answer};`);
129
- named.push(target === undefined
130
- ? ` ${method}: ${JSON.stringify(route)},`
131
- : ` ${method}: { route: ${JSON.stringify(route)}, target: ${JSON.stringify(target)} },`);
73
+ // sincpro_framework's `Get` answers the caller's own draft only when asked (`draft`), and an
74
+ // entity edited through `Edit` keeps its drafts there: its record is read with them, or a draft
75
+ // kept on one visit never comes back on the next.
76
+ const get = chosen.get("get");
77
+ if (chosen.has("edit") && get?.operation.input.properties?.["draft"]?.type === "boolean")
78
+ lines.push(" drafts: true,");
79
+ const commands = commandsOf(all.filter((one) => one.operation.role === "command" && one.operation.entities.includes(model)), model);
80
+ if (commands.length > 0) {
81
+ const inside = claimed();
82
+ for (const [name, local] of commands)
83
+ inside(name, `operation ${local}`);
84
+ lines.push(` commands: {\n${commands.map(([name, local]) => ` ${name}: operations.${local},`).join("\n")}\n },`);
132
85
  }
133
- if (named.length > 0)
134
- routes.push(` commands: {\n${named.join("\n")}\n },`);
135
86
  const name = pluralOf(identifierOf(model));
136
87
  claim(name, `the entity of ${model}`);
137
- const types = bodies.length === 0
138
- ? `dto.${identifierOf(model)}`
139
- : `\n dto.${identifierOf(model)},\n {\n${bodies.join("\n")}\n },\n {\n${answers.join("\n")}\n }\n`;
140
88
  const doc = [
141
89
  "/**",
142
90
  ` * \`${model}\`: its list, its record and the Commands that run on it or create it.`,
@@ -149,32 +97,30 @@ function entitySourceOf(metamodel, model, domain, options, claim) {
149
97
  return {
150
98
  name,
151
99
  missing,
152
- source: `${doc}\nexport const ${name} = entity<${types}>(${key}, {\n${routes.join("\n")}\n});`,
100
+ source: `${doc}\nexport const ${name} = entity(${key}, {\n${lines.join("\n")}\n});`,
153
101
  };
154
102
  }
155
103
  /**
156
- * The TypeScript of the entities of `metamodel`, as the text of one file next to its `domain.ts`.
104
+ * The TypeScript of the entities of `metamodel`, as the text of one file next to its `client.ts`.
157
105
  *
158
- * 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
159
- * several) — none, and the model gets no entity, said in the file's own doc.
160
- * 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`,
161
- * and its trash's — `archive`, `restore` and `purge`, this one by its path —; its `events` — a
162
- * record's `DomainEvents` — as `history`, the same way; and its `export` — every record of a
163
- * criteria as a file — by its path.
164
- * 3. Every write of role `command` that concerns it: with `target` when its body names the
165
- * record, as it is when it creates one; its body typed without that field.
166
- * Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
167
- * them, for `FrameworkProvider entities`.
106
+ * 1. Per model, by name: the one `search` for it (`own` when there are several) — none, and the
107
+ * model gets no entity, said in the file's own doc.
108
+ * 2. Each other role the same way — `get` and `events` only when they name the record —, and
109
+ * `drafts` when its record is edited through `Edit` and read with the caller's draft.
110
+ * 3. Every operation of role `command` that concerns it, by its name without the entity's.
111
+ * Final: an `entity()` per model listed, keyed `<domain>:<kind>`, over the client's
112
+ * `operations`, and `entities`, all of them, for `FrameworkProvider entities`.
168
113
  */
169
114
  export function entitiesFileOf(metamodel, options = {}) {
170
115
  const domain = options.domain ?? aliasOf(metamodel);
171
116
  const claim = claimed();
172
117
  claim("entities", "the list of every entity");
118
+ claim("operations", "the client's operations");
173
119
  const declared = [];
174
120
  const left = [];
175
121
  // A value a record holds (no identity) is no entity: it is never listed nor opened alone.
176
122
  for (const [model] of sorted(metamodel.models).filter(([name]) => isEntity(metamodel, name))) {
177
- const one = entitySourceOf(metamodel, model, domain, options, claim);
123
+ const one = entitySourceOf(metamodel, model, domain, claim);
178
124
  if ("source" in one)
179
125
  declared.push(one);
180
126
  else
@@ -183,7 +129,7 @@ export function entitiesFileOf(metamodel, options = {}) {
183
129
  const imports = [
184
130
  `import { entity } from "${FRAMEWORK}";`,
185
131
  "",
186
- `import type * as dto from "${DOMAIN_MODULE}";`,
132
+ `import { operations } from "${CLIENT_MODULE}";`,
187
133
  ].join("\n");
188
134
  const all = [
189
135
  "/**",
@@ -1,4 +1,4 @@
1
- import type { Metamodel, Operation } from "../domain/metamodel.js";
1
+ import type { Metamodel } from "../domain/metamodel.js";
2
2
  /**
3
3
  * How REST reaches each operation of a contract, as the generated client and entities write it.
4
4
  *
@@ -24,8 +24,3 @@ export type Reached = {
24
24
  /** What a transport can send: GET is read by `list` (a page) or `one` (a record) only. */
25
25
  export declare const WRITES: Set<string>;
26
26
  export declare function restOf(metamodel: Metamodel, identity: string, options: GenerateOptions): Reached | undefined;
27
- /**
28
- * The one entity a read belongs to: its only entity, or — when it concerns several — the one
29
- * whose model its answer carries. `undefined` when that still leaves more than one.
30
- */
31
- export declare function ownerOf(metamodel: Metamodel, operation: Operation): string | undefined;
@@ -14,14 +14,3 @@ export function restOf(metamodel, identity, options) {
14
14
  fields: binding.path_fields,
15
15
  };
16
16
  }
17
- /**
18
- * The one entity a read belongs to: its only entity, or — when it concerns several — the one
19
- * whose model its answer carries. `undefined` when that still leaves more than one.
20
- */
21
- export function ownerOf(metamodel, operation) {
22
- if (operation.entities.length === 1)
23
- return operation.entities[0];
24
- const answer = JSON.stringify(operation.output ?? {});
25
- const carried = operation.entities.filter((one) => one in metamodel.models && answer.includes(`"#/models/${one}"`));
26
- return carried.length === 1 ? carried[0] : undefined;
27
- }
@@ -30,13 +30,16 @@ export function scaffoldFilesOf(metamodel, options = {}) {
30
30
  `import type { OperationTransport } from "${FRAMEWORK}";`,
31
31
  `import type { BoundedContext } from "${at(FRAMEWORK, "core")}";`,
32
32
  ...(client
33
- ? ["", `import { clientOf } from "${at("..", GENERATED_ADAPTERS, "client")}";`]
33
+ ? [
34
+ "",
35
+ `import { type Api, clientOf } from "${at("..", GENERATED_ADAPTERS, "client")}";`,
36
+ ]
34
37
  : []),
35
38
  "",
36
39
  `/** What every service of «${alias}» finds on \`this\`${client ? ": `this.client`, the service's operations" : ""}. */`,
37
40
  `export interface ${Dependencies} {`,
38
41
  ...(client
39
- ? [" client: ReturnType<typeof clientOf>;"]
42
+ ? [" client: Api;"]
40
43
  : [
41
44
  " /** What the services need: a repository, an adapter, another bounded context. */",
42
45
  ]),
@@ -15,7 +15,7 @@ export type ServiceInput<R> = Command<R> | DomainEvent | RemoteEvent | RemoteCom
15
15
  * class CancelIssue extends Feature<CommandCancelIssue, ResponseCancelIssue> {
16
16
  * async execute(command: CommandCancelIssue) {
17
17
  * this.logger.info("Cancelling"); // bound to this run
18
- * return new ResponseCancelIssue(await this.client.cancelIssue(command));
18
+ * return new ResponseCancelIssue(await this.client.issue.cancel(command));
19
19
  * }
20
20
  * }
21
21
  *
@@ -7,7 +7,7 @@
7
7
  * class CancelIssue extends Feature<CommandCancelIssue, ResponseCancelIssue> {
8
8
  * async execute(command: CommandCancelIssue) {
9
9
  * this.logger.info("Cancelling"); // bound to this run
10
- * return new ResponseCancelIssue(await this.client.cancelIssue(command));
10
+ * return new ResponseCancelIssue(await this.client.issue.cancel(command));
11
11
  * }
12
12
  * }
13
13
  *