@sincpro/web-framework 1.0.0 → 1.1.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 (50) hide show
  1. package/README.md +36 -1
  2. package/dist/codegen/cli.d.ts +2 -0
  3. package/dist/codegen/cli.js +82 -0
  4. package/dist/codegen/client.d.ts +14 -0
  5. package/dist/codegen/client.js +178 -0
  6. package/dist/codegen/domain.d.ts +14 -0
  7. package/dist/codegen/domain.js +195 -0
  8. package/dist/codegen/entities.d.ts +14 -0
  9. package/dist/codegen/entities.js +158 -0
  10. package/dist/codegen/index.d.ts +11 -0
  11. package/dist/codegen/index.js +9 -0
  12. package/dist/codegen/metamodel.d.ts +89 -0
  13. package/dist/codegen/metamodel.js +1 -0
  14. package/dist/codegen/names.d.ts +40 -0
  15. package/dist/codegen/names.js +114 -0
  16. package/dist/codegen/rest.d.ts +31 -0
  17. package/dist/codegen/rest.js +27 -0
  18. package/dist/core/cache.js +7 -0
  19. package/dist/core/contract.d.ts +34 -0
  20. package/dist/core/contract.js +41 -0
  21. package/dist/core/entity.d.ts +77 -9
  22. package/dist/core/entity.js +51 -6
  23. package/dist/core/index.d.ts +4 -3
  24. package/dist/core/index.js +4 -3
  25. package/dist/core/memory.d.ts +3 -0
  26. package/dist/core/memory.js +9 -0
  27. package/dist/core/relation.d.ts +11 -1
  28. package/dist/core/relation.js +30 -2
  29. package/dist/core/rest.d.ts +15 -0
  30. package/dist/core/rest.js +16 -0
  31. package/dist/core/transport.d.ts +11 -0
  32. package/dist/core/transport.js +9 -0
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/useCommand.d.ts +15 -5
  36. package/dist/react/useCommand.js +7 -4
  37. package/dist/react/useListing.d.ts +5 -4
  38. package/dist/react/useListing.js +3 -2
  39. package/dist/react/useNameOf.d.ts +13 -0
  40. package/dist/react/useNameOf.js +44 -0
  41. package/dist/web/list/EntityList.d.ts +5 -4
  42. package/dist/web/list/EntityList.js +1 -1
  43. package/dist/web/list/presentation.d.ts +3 -3
  44. package/dist/web/list/presentation.js +1 -0
  45. package/dist/web/list/rowCommands.d.ts +16 -12
  46. package/dist/web/list/rowCommands.js +3 -2
  47. package/dist/web/record/CommandButton.d.ts +9 -6
  48. package/dist/web/record/edit.js +19 -7
  49. package/dist/web/record/lines.js +7 -1
  50. package/package.json +16 -5
@@ -0,0 +1,158 @@
1
+ import { aliasOf, claimed, DOMAIN_MODULE, FRAMEWORK, headerOf, identifierOf, isEntity, localOf, methodOf, pluralOf, sorted, } from "./names.js";
2
+ import { ownerOf, restOf, WRITES, } from "./rest.js";
3
+ import { entityKeyOf } from "../core/contract.js";
4
+ /** The one operation of `role` for `entity` a transport can call, by `own` when there are many. */
5
+ function oneOf(candidates, role) {
6
+ if (candidates.length === 0)
7
+ return undefined;
8
+ if (candidates.length === 1)
9
+ return { found: candidates[0] };
10
+ const own = candidates.filter((one) => one.operation.own === true);
11
+ if (own.length === 1)
12
+ return { found: own[0] };
13
+ const names = candidates.map((one) => `\`${one.local}\``).join(", ");
14
+ return { missing: `${candidates.length} of role \`${role}\` (${names}) and none \`own\`` };
15
+ }
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
+ /**
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.
26
+ */
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;
34
+ }
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
+ : [{ local: localOf(metamodel, identity), operation, rest }];
41
+ });
42
+ const reads = (role, method) => reached.filter((one) => one.operation.role === role &&
43
+ method(one.rest.method) &&
44
+ ownerOf(metamodel, one.operation) === model);
45
+ const isGet = (verb) => verb === "GET";
46
+ const isWrite = (verb) => WRITES.has(verb);
47
+ const list = oneOf(reads("search", isGet), "search");
48
+ if (list === undefined)
49
+ return { missing: "no `search` a transport reads" };
50
+ if ("missing" in list)
51
+ return { missing: list.missing };
52
+ // A list under a record (`/tenants/{tenant_id}/members`) keeps its keys: the screen gives
53
+ // them as the list's parameters (`useListing(entity, { params })`), and `listRoute` fills them.
54
+ const missing = [];
55
+ const routes = [` list: ${JSON.stringify(list.found.rest.path)},`];
56
+ const one = oneOf(reads("get", isGet), "get");
57
+ if (one !== undefined && "found" in one) {
58
+ const field = one.found.operation.targets[model];
59
+ if (field !== undefined && one.found.rest.fields.length === 1)
60
+ routes.push(` one: ${JSON.stringify(recordPath(one.found.rest, field))},`);
61
+ else
62
+ missing.push(`one: \`${one.found.local}\` is at ${one.found.rest.path}`);
63
+ }
64
+ else if (one !== undefined)
65
+ missing.push(`one: ${one.missing}`);
66
+ for (const role of ["edit", "preview"]) {
67
+ const write = oneOf(reads(role, isWrite), role);
68
+ if (write === undefined)
69
+ continue;
70
+ if ("missing" in write) {
71
+ missing.push(`${role}: ${write.missing}`);
72
+ continue;
73
+ }
74
+ const field = write.found.operation.targets[model];
75
+ const route = `${write.found.rest.method} ${recordPath(write.found.rest, field)}`;
76
+ routes.push(` ${role}: ${JSON.stringify(route)},`);
77
+ }
78
+ const commands = reached.filter((one) => one.operation.role === "command" &&
79
+ isWrite(one.rest.method) &&
80
+ one.operation.entities.includes(model));
81
+ const bodies = [];
82
+ const answers = [];
83
+ const named = [];
84
+ for (const command of commands) {
85
+ const method = methodOf(command.local);
86
+ const target = singleTarget(command.operation, model);
87
+ const route = `${command.rest.method} ${command.rest.path}`;
88
+ bodies.push(target === undefined
89
+ ? ` ${method}: dto.${command.local};`
90
+ : ` ${method}: Omit<dto.${command.local}, ${JSON.stringify(target)}>;`);
91
+ answers.push(` ${method}: dto.${command.local}Answer;`);
92
+ named.push(target === undefined
93
+ ? ` ${method}: ${JSON.stringify(route)},`
94
+ : ` ${method}: { route: ${JSON.stringify(route)}, target: ${JSON.stringify(target)} },`);
95
+ }
96
+ if (named.length > 0)
97
+ routes.push(` commands: {\n${named.join("\n")}\n },`);
98
+ const name = pluralOf(identifierOf(model));
99
+ claim(name, `the entity of ${model}`);
100
+ const types = bodies.length === 0
101
+ ? `dto.${identifierOf(model)}`
102
+ : `\n dto.${identifierOf(model)},\n {\n${bodies.join("\n")}\n },\n {\n${answers.join("\n")}\n }\n`;
103
+ const doc = [
104
+ "/**",
105
+ ` * \`${model}\`: its list, its record and the Commands that run on it or create it.`,
106
+ ...(missing.length === 0
107
+ ? []
108
+ : [" *", " * Not declared:", ...missing.map((one) => ` * - ${one}.`)]),
109
+ " */",
110
+ ].join("\n");
111
+ const key = JSON.stringify(entityKeyOf(domain, model));
112
+ return {
113
+ name,
114
+ missing,
115
+ source: `${doc}\nexport const ${name} = entity<${types}>(${key}, {\n${routes.join("\n")}\n});`,
116
+ };
117
+ }
118
+ /**
119
+ * The TypeScript of the entities of `metamodel`, as the text of one file next to its `domain.ts`.
120
+ *
121
+ * 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
122
+ * several) — none, and the model gets no entity, said in the file's own doc.
123
+ * 2. Its `get`, `edit` and `preview` the same way, the record's field written `{id}`.
124
+ * 3. Every write of role `command` that concerns it: with `target` when its body names the
125
+ * record, as it is when it creates one; its body typed without that field.
126
+ * Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
127
+ * them, for `FrameworkProvider entities`.
128
+ */
129
+ export function entitiesFileOf(metamodel, options = {}) {
130
+ const domain = options.domain ?? aliasOf(metamodel);
131
+ const claim = claimed();
132
+ claim("entities", "the list of every entity");
133
+ const declared = [];
134
+ const left = [];
135
+ // A value a record holds (no identity) is no entity: it is never listed nor opened alone.
136
+ for (const [model] of sorted(metamodel.models).filter(([name]) => isEntity(metamodel, name))) {
137
+ const one = entitySourceOf(metamodel, model, domain, options, claim);
138
+ if ("source" in one)
139
+ declared.push(one);
140
+ else
141
+ left.push(`\`${model}\`: ${one.missing}`);
142
+ }
143
+ const imports = [
144
+ `import { entity } from "${FRAMEWORK}";`,
145
+ "",
146
+ `import type * as dto from "${DOMAIN_MODULE}";`,
147
+ ].join("\n");
148
+ const all = [
149
+ "/**",
150
+ ` * Every entity of «${aliasOf(metamodel)}», for \`FrameworkProvider entities\`.`,
151
+ ...(left.length === 0
152
+ ? []
153
+ : [" *", " * Without an entity here:", ...left.map((one) => ` * - ${one}.`)]),
154
+ " */",
155
+ `export const entities = [${declared.map((one) => one.name).join(", ")}] as const;`,
156
+ ].join("\n");
157
+ return `${[headerOf("The entities", metamodel), imports, ...declared.map((one) => one.source), all].join("\n\n")}\n`;
158
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The generator: a bounded context's DTOs, client and entities out of the client contract
3
+ * sincpro_framework exports (PRD_01 phase B). A build step that runs in Node — nothing in
4
+ * `core/`, `react/` or `web/` imports it (`make doctor`), and the package's root entry does not
5
+ * re-export it. `sincpro-web generate` (`cli.ts`) is the same, from a terminal.
6
+ */
7
+ export { clientFileOf } from "./client.js";
8
+ export { domainFileOf } from "./domain.js";
9
+ export { entitiesFileOf } from "./entities.js";
10
+ export type { Bindings, Metamodel, Operation, RestBinding, Schema, } from "./metamodel.js";
11
+ export type { GenerateOptions } from "./rest.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The generator: a bounded context's DTOs, client and entities out of the client contract
3
+ * sincpro_framework exports (PRD_01 phase B). A build step that runs in Node — nothing in
4
+ * `core/`, `react/` or `web/` imports it (`make doctor`), and the package's root entry does not
5
+ * re-export it. `sincpro-web generate` (`cli.ts`) is the same, from a terminal.
6
+ */
7
+ export { clientFileOf } from "./client.js";
8
+ export { domainFileOf } from "./domain.js";
9
+ export { entitiesFileOf } from "./entities.js";
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The client contract of a bounded context, as sincpro_framework exports it
3
+ * (`export_client_contract`, PRD_33): its metamodel — models, the definitions they share, every
4
+ * operation a client may call — and how each wire reaches each operation (`bindings`). A bare
5
+ * metamodel (`export_metamodel`) is the same without `format` and `bindings`.
6
+ *
7
+ * Context: only what the generator reads is typed here. The file is the server's, written with
8
+ * its keys sorted, so the same code writes the same bytes; a key this does not name is kept in
9
+ * the snapshot and ignored by the generator.
10
+ */
11
+ export type Schema = {
12
+ type?: string | readonly string[];
13
+ format?: string;
14
+ enum?: readonly unknown[];
15
+ const?: unknown;
16
+ items?: Schema;
17
+ $ref?: string;
18
+ anyOf?: readonly Schema[];
19
+ oneOf?: readonly Schema[];
20
+ properties?: Readonly<Record<string, Schema>>;
21
+ required?: readonly string[];
22
+ additionalProperties?: boolean | Schema;
23
+ title?: string;
24
+ description?: string;
25
+ "x-sincpro"?: {
26
+ type?: string;
27
+ relation?: string | null;
28
+ identity?: string;
29
+ };
30
+ };
31
+ export type Operation = {
32
+ /** What it is for its entity: `search`, `get`, `edit`, `command`… */
33
+ role: string;
34
+ /** It writes nothing: retrying or caching it is safe. */
35
+ query: boolean;
36
+ entities: readonly string[];
37
+ /** The field of `input` that names the record of each entity it runs on. */
38
+ targets: Readonly<Record<string, string>>;
39
+ dry_run: boolean;
40
+ description?: string | null;
41
+ input: Schema;
42
+ /** What it answers; `null` when the server declares nothing. */
43
+ output: Schema | null;
44
+ /** The entity's own operation of its role, when it has several (`@entity_tags(own=True)`). */
45
+ own?: boolean;
46
+ deprecated?: boolean;
47
+ /** The day it stops being served, `YYYY-MM-DD`. */
48
+ sunset?: string | null;
49
+ /** The operation that replaces it, by identity. */
50
+ replacement?: string | null;
51
+ };
52
+ /** How REST reaches an operation: its method and its whole path, `{field}` where a field goes. */
53
+ export type RestBinding = {
54
+ method: string;
55
+ path: string;
56
+ /** The fields of the input the path carries. */
57
+ path_fields: readonly string[];
58
+ };
59
+ export type Bindings = {
60
+ rest?: Readonly<Record<string, RestBinding>>;
61
+ rpc?: Readonly<Record<string, {
62
+ method: string;
63
+ }>>;
64
+ grpc?: Readonly<Record<string, {
65
+ method: string;
66
+ }>>;
67
+ mcp?: Readonly<Record<string, {
68
+ tool: string;
69
+ }>>;
70
+ };
71
+ export type Metamodel = {
72
+ /** `sincpro.client-contract/1` for an exported client contract. */
73
+ format?: string;
74
+ /** The bounded context's own name: what every operation's identity starts with. */
75
+ bounded_context?: string;
76
+ /** The name the gateways publish it under (`FastApiGateway({"project": …})`): what a client
77
+ * names the context by. */
78
+ alias?: string;
79
+ /** The bounded context's name, as sincpro_framework 3.32 wrote it before `bounded_context`. */
80
+ context?: string;
81
+ version: string;
82
+ /** Every shape the contract names: an entity (it has an `identity`) or a value it holds. */
83
+ models: Readonly<Record<string, Schema>>;
84
+ /** By the Command's identity, `"<bounded_context>.<Class>"`. */
85
+ operations: Readonly<Record<string, Operation>>;
86
+ $defs?: Readonly<Record<string, Schema>>;
87
+ /** By wire, then by the Command's identity. */
88
+ bindings?: Bindings;
89
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ import type { Metamodel } from "./metamodel.js";
2
+ /**
3
+ * What a generated file imports, built in parts. The build rewrites this package's own
4
+ * specifiers to relative paths (`tsc-alias`), and it reads `from "…"` inside a string too: written
5
+ * whole, the generated files came out importing `"../index.js"` and `"./domain.js"`.
6
+ */
7
+ export declare const FRAMEWORK: string;
8
+ export declare const FRAMEWORK_CORE: string;
9
+ export declare const DOMAIN_MODULE: string;
10
+ /** A name of the server's as a TypeScript identifier: `shop__orders__Line` stays, `-` is `_`. */
11
+ export declare function identifierOf(name: string): string;
12
+ /** A property key as TypeScript writes it: bare when it can be, quoted otherwise. */
13
+ export declare function keyOf(name: string): string;
14
+ export declare function sorted<V>(record: Readonly<Record<string, V>>): [string, V][];
15
+ /** `{ Issue: "issue_id" }`: a record of texts as TypeScript writes it, keys sorted. */
16
+ export declare function recordLiteral(record: Readonly<Record<string, string>>): string;
17
+ /** The bounded context's own name: `bounded_context`, or `context` in a 3.32 contract. */
18
+ export declare function contextOf(metamodel: Metamodel): string;
19
+ /** What a client names the context by: its `alias`, else its own name. */
20
+ export declare function aliasOf(metamodel: Metamodel): string;
21
+ /** A model the contract names is an entity when it has an identity; else a value it holds. */
22
+ export declare function isEntity(metamodel: Metamodel, model: string): boolean;
23
+ /** An operation's name in its context: its identity without `<bounded_context>.`. */
24
+ export declare function localOf(metamodel: Metamodel, identity: string): string;
25
+ /** The method an operation is called by: `CommandSendIssue` → `sendIssue`. */
26
+ export declare function methodOf(local: string): string;
27
+ /** `Issue` → `issues`, `ProjectEvent` → `projectEvents`, `Policy` → `policies`. */
28
+ export declare function pluralOf(name: string): string;
29
+ /** A JSDoc block, or nothing: the paragraphs given, each one kept. */
30
+ export declare function docOf(lines: readonly (string | null | undefined)[], pad: string): string;
31
+ /** The first lines of every generated file: what it is, where it came from, not to edit it. */
32
+ export declare function headerOf(what: string, metamodel: Metamodel): string;
33
+ /** What a deprecated operation says: since when it goes and what replaces it. */
34
+ export declare function deprecationOf(metamodel: Metamodel, operation: {
35
+ deprecated?: boolean;
36
+ sunset?: string | null;
37
+ replacement?: string | null;
38
+ }): string | undefined;
39
+ /** Refuses a second thing under a name already given, naming both. */
40
+ export declare function claimed(): (name: string, by: string) => void;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * How the generator names what the server names: a TypeScript identifier for a class, a method
3
+ * for an operation, a value for an entity, the key the workspace refers to an entity by.
4
+ *
5
+ * Context: every name here is derived, the same way every time, from what the contract already
6
+ * says — never chosen — so regenerating never renames by itself. Two things that come out with
7
+ * one name are refused by whoever writes them, naming both (`claimed`): a silent rename would
8
+ * break whoever imported the first.
9
+ */
10
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
11
+ /**
12
+ * What a generated file imports, built in parts. The build rewrites this package's own
13
+ * specifiers to relative paths (`tsc-alias`), and it reads `from "…"` inside a string too: written
14
+ * whole, the generated files came out importing `"../index.js"` and `"./domain.js"`.
15
+ */
16
+ export const FRAMEWORK = ["@sincpro", "web-framework"].join("/");
17
+ export const FRAMEWORK_CORE = [FRAMEWORK, "core"].join("/");
18
+ export const DOMAIN_MODULE = [".", "domain"].join("/");
19
+ /** A name of the server's as a TypeScript identifier: `shop__orders__Line` stays, `-` is `_`. */
20
+ export function identifierOf(name) {
21
+ const cleaned = name.replace(/[^A-Za-z0-9_$]/g, "_");
22
+ return /^[0-9]/.test(cleaned) ? `_${cleaned}` : cleaned;
23
+ }
24
+ /** A property key as TypeScript writes it: bare when it can be, quoted otherwise. */
25
+ export function keyOf(name) {
26
+ return IDENTIFIER.test(name) ? name : JSON.stringify(name);
27
+ }
28
+ export function sorted(record) {
29
+ return Object.entries(record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
30
+ }
31
+ /** `{ Issue: "issue_id" }`: a record of texts as TypeScript writes it, keys sorted. */
32
+ export function recordLiteral(record) {
33
+ const entries = sorted(record).map(([key, value]) => `${keyOf(key)}: ${JSON.stringify(value)}`);
34
+ return entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
35
+ }
36
+ /** The bounded context's own name: `bounded_context`, or `context` in a 3.32 contract. */
37
+ export function contextOf(metamodel) {
38
+ const name = metamodel.bounded_context ?? metamodel.context;
39
+ if (name === undefined)
40
+ throw new Error("the contract names no bounded context");
41
+ return name;
42
+ }
43
+ /** What a client names the context by: its `alias`, else its own name. */
44
+ export function aliasOf(metamodel) {
45
+ return metamodel.alias ?? contextOf(metamodel);
46
+ }
47
+ /** A model the contract names is an entity when it has an identity; else a value it holds. */
48
+ export function isEntity(metamodel, model) {
49
+ return metamodel.models[model]?.["x-sincpro"]?.identity !== undefined;
50
+ }
51
+ /** An operation's name in its context: its identity without `<bounded_context>.`. */
52
+ export function localOf(metamodel, identity) {
53
+ const prefix = `${contextOf(metamodel)}.`;
54
+ return identifierOf(identity.startsWith(prefix) ? identity.slice(prefix.length) : identity);
55
+ }
56
+ /** The method an operation is called by: `CommandSendIssue` → `sendIssue`. */
57
+ export function methodOf(local) {
58
+ const bare = local.replace(/^(Command|Query)(?=[A-Z])/, "");
59
+ return `${bare.charAt(0).toLowerCase()}${bare.slice(1)}`;
60
+ }
61
+ /** `Issue` → `issues`, `ProjectEvent` → `projectEvents`, `Policy` → `policies`. */
62
+ export function pluralOf(name) {
63
+ const value = `${name.charAt(0).toLowerCase()}${name.slice(1)}`;
64
+ if (/[^aeiou]y$/.test(value))
65
+ return `${value.slice(0, -1)}ies`;
66
+ if (/(s|x|z|ch|sh)$/.test(value))
67
+ return `${value}es`;
68
+ return `${value}s`;
69
+ }
70
+ /** A JSDoc block, or nothing: the paragraphs given, each one kept. */
71
+ export function docOf(lines, pad) {
72
+ const text = lines
73
+ .filter((one) => typeof one === "string" && one.trim() !== "")
74
+ .join("\n\n")
75
+ .replace(/\*\//g, "*\\/")
76
+ .trim();
77
+ if (text === "")
78
+ return "";
79
+ const parts = text.split("\n");
80
+ if (parts.length === 1)
81
+ return `${pad}/** ${parts[0]} */\n`;
82
+ const body = parts.map((one) => `${pad} *${one === "" ? "" : ` ${one}`}`).join("\n");
83
+ return `${pad}/**\n${body}\n${pad} */\n`;
84
+ }
85
+ /** The first lines of every generated file: what it is, where it came from, not to edit it. */
86
+ export function headerOf(what, metamodel) {
87
+ const alias = aliasOf(metamodel);
88
+ const own = contextOf(metamodel);
89
+ return [
90
+ `// ${what} of «${alias}»${alias === own ? "" : ` (${own})`}, generated by @sincpro/web-framework.`,
91
+ `// Version ${metamodel.version}.`,
92
+ `// Do not edit: regenerate it (\`sincpro-web generate\`).`,
93
+ ].join("\n");
94
+ }
95
+ /** What a deprecated operation says: since when it goes and what replaces it. */
96
+ export function deprecationOf(metamodel, operation) {
97
+ if (operation.deprecated !== true)
98
+ return undefined;
99
+ const sunset = operation.sunset ? ` It stops being served on ${operation.sunset}.` : "";
100
+ const replacement = operation.replacement
101
+ ? ` Use \`${localOf(metamodel, operation.replacement)}\`.`
102
+ : "";
103
+ return `@deprecated${sunset}${replacement}`;
104
+ }
105
+ /** Refuses a second thing under a name already given, naming both. */
106
+ export function claimed() {
107
+ const named = new Map();
108
+ return (name, by) => {
109
+ const before = named.get(name);
110
+ if (before !== undefined)
111
+ throw new Error(`${by} and ${before} are both "${name}" in TypeScript: rename one`);
112
+ named.set(name, by);
113
+ };
114
+ }
@@ -0,0 +1,31 @@
1
+ import type { Metamodel, Operation } from "./metamodel.js";
2
+ /**
3
+ * How REST reaches each operation of a contract, as the generated client and entities write it.
4
+ *
5
+ * Context: the export names each path whole (`/v1/issues/{issue_id}`), version included, while
6
+ * an application's transport already prepends it (`restTransport({ base: "/v1" })`). `base`
7
+ * takes it off every path, and a path outside it is refused — a client written with half its
8
+ * routes under the wrong base would fail one call at a time.
9
+ */
10
+ export type GenerateOptions = {
11
+ /** The first part of every entity's key: `project` makes `project:issue`. The contract's
12
+ * `alias` by default. */
13
+ domain?: string;
14
+ /** What every REST path starts with and the transport prepends: `/v1`. */
15
+ base?: string;
16
+ };
17
+ export type Reached = {
18
+ method: string;
19
+ /** The path under `base`, `{field}` where a field of the input goes. */
20
+ path: string;
21
+ /** The fields of the input the path carries. */
22
+ fields: readonly string[];
23
+ };
24
+ /** What a transport can send: GET is read by `list` (a page) or `one` (a record) only. */
25
+ export declare const WRITES: Set<string>;
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;
@@ -0,0 +1,27 @@
1
+ /** What a transport can send: GET is read by `list` (a page) or `one` (a record) only. */
2
+ export const WRITES = new Set(["POST", "PUT", "PATCH", "DELETE"]);
3
+ export function restOf(metamodel, identity, options) {
4
+ const binding = metamodel.bindings?.rest?.[identity];
5
+ if (binding === undefined)
6
+ return undefined;
7
+ const base = options.base ?? "";
8
+ const under = base === "" || binding.path === base || binding.path.startsWith(`${base}/`);
9
+ if (!under)
10
+ throw new Error(`${identity} is at ${binding.path}, outside the base ${base}`);
11
+ return {
12
+ method: binding.method.toUpperCase(),
13
+ path: binding.path.slice(base.length) || "/",
14
+ fields: binding.path_fields,
15
+ };
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
+ }
@@ -52,6 +52,13 @@ export function cachedTransport(transport, options = {}) {
52
52
  one(route, signal) {
53
53
  return remembered(`one ${route}`, () => transport.one(route, signal));
54
54
  },
55
+ // A read of the context's own (`GET /me`) is not an entity's: no write forgets it, so it is
56
+ // never kept — it goes to the server every time.
57
+ ...(transport.read === undefined
58
+ ? {}
59
+ : {
60
+ read: (route, signal) => transport.read(route, signal),
61
+ }),
55
62
  async send(method, route, body, signal, sending) {
56
63
  // A preview writes nothing; anything else may have changed what was read.
57
64
  const preview = route.endsWith("/preview");
@@ -0,0 +1,34 @@
1
+ import { type Contract, type Meta } from "@sincpro/criteria";
2
+ /**
3
+ * A bounded context's client contract, as the application keeps it: the snapshot
4
+ * `sincpro-web generate` writes (`contract.json`), or the document a service serves
5
+ * (`GET /client-contract/<context>.json`). Only its models are read here.
6
+ *
7
+ * Context: the generated entities are keyed `<domain>:<kind>` (`project:issue`) — the key the
8
+ * workspace refers to them by and the meta store keeps their definitions under —, so the rule
9
+ * that turns a model's name into its kind lives once, here, and both the generator and the
10
+ * preload read it.
11
+ */
12
+ export type ClientContract = {
13
+ models: Readonly<Record<string, Contract>>;
14
+ $defs?: Readonly<Record<string, Contract>>;
15
+ };
16
+ /** `ProjectEvent` → `project_event`: the kind in an entity's key. */
17
+ export declare function kindOf(model: string): string;
18
+ /** The key of a model's entity: `entityKeyOf("project", "ProjectEvent")` → `"project:project_event"`. */
19
+ export declare function entityKeyOf(domain: string, model: string): string;
20
+ /**
21
+ * The version of every entity of `contract`, by its model's name — what `restTransport`
22
+ * compares each answer with (`snapshot`) to say when the generated code is behind the server.
23
+ *
24
+ * restTransport({ base: "/v1", snapshot: versionsOf(contract), onVersionDrift: warn })
25
+ */
26
+ export declare function versionsOf(contract: ClientContract): Record<string, string>;
27
+ /**
28
+ * The definition of every model of `contract`, by its entity's key — what `FrameworkProvider
29
+ * metas` preloads, so the first screen draws its labels with no request at all. The transport
30
+ * still reads the live definition and asks again when an answer says another version.
31
+ *
32
+ * <FrameworkProvider transport={transport} metas={metasOf(contract, "project")}>
33
+ */
34
+ export declare function metasOf(contract: ClientContract, domain: string): Record<string, Meta>;
@@ -0,0 +1,41 @@
1
+ import { metaFromContract } from "@sincpro/criteria";
2
+ /** `ProjectEvent` → `project_event`: the kind in an entity's key. */
3
+ export function kindOf(model) {
4
+ return model
5
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
6
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1_$2")
7
+ .toLowerCase();
8
+ }
9
+ /** The key of a model's entity: `entityKeyOf("project", "ProjectEvent")` → `"project:project_event"`. */
10
+ export function entityKeyOf(domain, model) {
11
+ return `${domain}:${kindOf(model)}`;
12
+ }
13
+ /**
14
+ * The version of every entity of `contract`, by its model's name — what `restTransport`
15
+ * compares each answer with (`snapshot`) to say when the generated code is behind the server.
16
+ *
17
+ * restTransport({ base: "/v1", snapshot: versionsOf(contract), onVersionDrift: warn })
18
+ */
19
+ export function versionsOf(contract) {
20
+ return Object.fromEntries(Object.entries(contract.models).flatMap(([name, model]) => {
21
+ const version = model["x-sincpro"]?.version;
22
+ return model["x-sincpro"]?.identity != null && typeof version === "string"
23
+ ? [[name, version]]
24
+ : [];
25
+ }));
26
+ }
27
+ /**
28
+ * The definition of every model of `contract`, by its entity's key — what `FrameworkProvider
29
+ * metas` preloads, so the first screen draws its labels with no request at all. The transport
30
+ * still reads the live definition and asks again when an answer says another version.
31
+ *
32
+ * <FrameworkProvider transport={transport} metas={metasOf(contract, "project")}>
33
+ */
34
+ export function metasOf(contract, domain) {
35
+ // A related model, or a value a record holds, is pointed at by its name (`#/models/Run`).
36
+ const related = { ...(contract.$defs ?? {}), ...contract.models };
37
+ return Object.fromEntries(Object.entries(contract.models)
38
+ // Only an entity has a key of its own; a value it holds is described inside it.
39
+ .filter(([, model]) => model["x-sincpro"]?.identity != null)
40
+ .map(([name, model]) => [entityKeyOf(domain, name), metaFromContract(model, related)]));
41
+ }