@sincpro/web-framework 0.4.2 → 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 (70) hide show
  1. package/README.md +82 -41
  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/discovery.d.ts +47 -0
  22. package/dist/core/discovery.js +68 -0
  23. package/dist/core/edit.d.ts +35 -6
  24. package/dist/core/edit.js +57 -4
  25. package/dist/core/entity.d.ts +77 -9
  26. package/dist/core/entity.js +51 -6
  27. package/dist/core/index.d.ts +5 -4
  28. package/dist/core/index.js +5 -4
  29. package/dist/core/memory.d.ts +3 -0
  30. package/dist/core/memory.js +9 -0
  31. package/dist/core/meta.d.ts +7 -0
  32. package/dist/core/meta.js +1 -1
  33. package/dist/core/metas.d.ts +4 -5
  34. package/dist/core/relation.d.ts +11 -1
  35. package/dist/core/relation.js +30 -2
  36. package/dist/core/rest.d.ts +23 -0
  37. package/dist/core/rest.js +78 -3
  38. package/dist/core/schema.d.ts +5 -12
  39. package/dist/core/trail.js +1 -4
  40. package/dist/core/transport.d.ts +11 -0
  41. package/dist/core/transport.js +9 -0
  42. package/dist/react/index.d.ts +2 -1
  43. package/dist/react/index.js +1 -0
  44. package/dist/react/useCommand.d.ts +15 -5
  45. package/dist/react/useCommand.js +7 -4
  46. package/dist/react/useGroups.js +1 -2
  47. package/dist/react/useHistory.js +1 -1
  48. package/dist/react/useListing.d.ts +5 -4
  49. package/dist/react/useListing.js +9 -8
  50. package/dist/react/useLookup.js +2 -3
  51. package/dist/react/useNameOf.d.ts +13 -0
  52. package/dist/react/useNameOf.js +44 -0
  53. package/dist/react/usePivot.js +0 -1
  54. package/dist/react/useRecord.d.ts +2 -1
  55. package/dist/react/useRecord.js +15 -3
  56. package/dist/react/useRelated.js +2 -2
  57. package/dist/web/list/EntityList.d.ts +5 -4
  58. package/dist/web/list/EntityList.js +1 -1
  59. package/dist/web/list/EntitySearchBar.js +2 -2
  60. package/dist/web/list/presentation.d.ts +3 -3
  61. package/dist/web/list/presentation.js +1 -0
  62. package/dist/web/list/rowCommands.d.ts +16 -12
  63. package/dist/web/list/rowCommands.js +3 -2
  64. package/dist/web/list/search.js +1 -1
  65. package/dist/web/record/CommandButton.d.ts +9 -6
  66. package/dist/web/record/edit.js +19 -7
  67. package/dist/web/record/lines.js +23 -10
  68. package/dist/web/record/opening.js +1 -1
  69. package/dist/web/workspace/composer.js +1 -4
  70. package/package.json +18 -7
@@ -4,9 +4,10 @@
4
4
  * `make doctor` keeps it that way.
5
5
  */
6
6
  export { cachedTransport, } from "./cache.js";
7
+ export { entityKeyOf, metasOf, versionsOf, } from "./contract.js";
7
8
  export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
8
- export { adviceAt, changesOf, creationOf, defaultsOf, errorAt, errorsByField, fieldStateOf, lineStatesOf, missingOf, pathOf, } from "./edit.js";
9
- export { entity, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
9
+ export { adviceAt, changesOf, computedLocally, creationOf, defaultsOf, errorAt, errorsByField, fieldStateOf, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, } from "./edit.js";
10
+ export { bodyFor, entity, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
10
11
  export { formOf } from "./form.js";
11
12
  export { historyOf } from "./history.js";
12
13
  export { isEntityId, newEntityId } from "./ids.js";
@@ -20,10 +21,10 @@ export { metaStore } from "./metas.js";
20
21
  export { BOOKKEEPING, defaultFields, sortKeyOf, textOf, viewOf, } from "./present.js";
21
22
  export { relatedOf } from "./related.js";
22
23
  export { entityFor, relationFieldOf, } from "./relation.js";
23
- export { restTransport, urlOf } from "./rest.js";
24
+ export { restTransport, urlOf, } from "./rest.js";
24
25
  export { retryKeys, unanswered } from "./retry.js";
25
26
  export { completeMeta, metaFromSchema, } from "./schema.js";
26
27
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
27
28
  export { placeOf, stepIn } from "./trail.js";
28
- export { explain, TransportError, } from "./transport.js";
29
+ export { explain, readRoute, TransportError, } from "./transport.js";
29
30
  export { installTimeZone, instantOf, timeZoneNow, wallTimeOf, } from "./zone.js";
@@ -31,6 +31,9 @@ export type MemoryOptions = {
31
31
  * refuse. Without it, every Command is a 404.
32
32
  */
33
33
  handle?: (method: Method, route: string, body: unknown) => unknown;
34
+ /** Answer a read that is neither a page nor a record (`GET /me`), its route with its query.
35
+ * Without it, the transport has no `read`. */
36
+ read?: (route: string) => unknown;
34
37
  /** The draft this caller kept of a record, answered with it — sincpro_framework's `Drafts`. */
35
38
  draft?: (route: string) => Draft | null;
36
39
  /** Every list request, as it arrived: what a story or a test checks was really asked. */
@@ -95,5 +95,14 @@ export function memoryTransport(tables, options = {}) {
95
95
  answered.set(key, structuredClone(answer));
96
96
  return answer;
97
97
  },
98
+ ...(options.read === undefined
99
+ ? {}
100
+ : {
101
+ async read(route, signal) {
102
+ await check(route, signal);
103
+ // A copy, as every answer: over a wire nobody holds the server's object.
104
+ return structuredClone(await options.read(route));
105
+ },
106
+ }),
98
107
  };
99
108
  }
@@ -63,6 +63,13 @@ export declare const field: {
63
63
  visible_when?: Expression | null;
64
64
  sortable: boolean;
65
65
  ops: Operator[];
66
+ widget?: string;
67
+ affects?: string[];
68
+ judged_by?: string[];
69
+ holds?: Expression | null;
70
+ computes?: import("@sincpro/criteria").Formula | null;
71
+ navigable?: boolean;
72
+ total?: string | null;
66
73
  many?: boolean;
67
74
  relation?: string | null;
68
75
  identified_by?: string | null;
package/dist/core/meta.js CHANGED
@@ -109,7 +109,7 @@ function searchTemplate(fields) {
109
109
  });
110
110
  const [only] = fields;
111
111
  return {
112
- where: fields.length === 1 && only !== undefined ? like(only) : { any: fields.map(like) },
112
+ selection: fields.length === 1 && only !== undefined ? like(only) : { any: fields.map(like) },
113
113
  };
114
114
  }
115
115
  /** A whole definition, from its fields. See the file header. */
@@ -2,11 +2,10 @@ import type { Meta } from "@sincpro/criteria";
2
2
  /**
3
3
  * The model definitions already known, by entity key (`"billing:invoice"`).
4
4
  *
5
- * Context: sincpro_framework sends `entity_meta_data` with every answer that does not say
6
- * `meta: false`, and it is not small — forge's `Project` weighs ~97 KB even with zero rows.
7
- * A reading already asks for it only on its first page; this keeps it ACROSS readings, so the
8
- * second list of the same entity, the record opened from it and the select that points at it
9
- * ask with `meta: false` and draw their labels before the rows arrive.
5
+ * Context: sincpro_framework publishes each model once, in the discovery document the
6
+ * transport reads (`core/discovery`); an answer carries only its version. This keeps the
7
+ * definitions ACROSS readings, so the second list of the same entity, the record opened from it
8
+ * and the select that points at it draw their labels before the rows arrive.
10
9
  *
11
10
  * Seeded, it is the preload: definitions written at build time (a snapshot of the server's,
12
11
  * or `defineMeta`) reach the first screen with no request at all.
@@ -9,6 +9,11 @@ import type { Entity } from "./entity.js";
9
9
  * joined by `identified_by`. A form may name either; both mean «the customer». A relation
10
10
  * names the other side by its AGGREGATE («Cliente»), which says nothing about where it is read
11
11
  * — that is the entity the application declared (`entityFor`).
12
+ *
13
+ * A key may also stand alone: `tenant_id: EntityID[Tenant]` on the server is a scalar that says
14
+ * whose record it names (`relation: "auth.Tenant"`) with no relation field beside it. It is a
15
+ * many2one all the same — chosen with the picker of that entity — but only its key is in hand
16
+ * (`held: false`): nothing else is written beside it, and its name is asked for by key.
12
17
  */
13
18
  export type RelationField = {
14
19
  /** The relation field: `customer`. */
@@ -19,10 +24,15 @@ export type RelationField = {
19
24
  target: string;
20
25
  many: boolean;
21
26
  field: FieldMeta;
27
+ /** The record it points at comes with the record (a relation field the server expands), or
28
+ * only its key does (`EntityID[Tenant]`): then `relation` IS the key. */
29
+ held: boolean;
22
30
  };
23
31
  export declare function relationFieldOf(meta: Meta | null | undefined, name: string): RelationField | undefined;
24
32
  /**
25
33
  * The declared entity a relation points at: the one that says it is that aggregate, else the
26
- * one whose model definition is, else the one whose key it is (`"ventas:cliente"`).
34
+ * one whose model definition is, else the one whose key it is (`"ventas:cliente"`), else the one
35
+ * its model names (`"auth.Tenant"` → `auth:tenant`), else the only one of that kind — a context
36
+ * named by its own name (`sincpro-forge-auth.Tenant`) where the application keys it by alias.
27
37
  */
28
38
  export declare function entityFor(entities: readonly Entity[], target: string, metaOf?: (key: string) => Meta | undefined): Entity | undefined;
@@ -1,3 +1,4 @@
1
+ import { entityKeyOf, kindOf } from "./contract.js";
1
2
  export function relationFieldOf(meta, name) {
2
3
  if (!meta)
3
4
  return undefined;
@@ -9,6 +10,7 @@ export function relationFieldOf(meta, name) {
9
10
  target: field.relation,
10
11
  many: field.many === true,
11
12
  field,
13
+ held: true,
12
14
  };
13
15
  const own = meta.fields[name];
14
16
  if (own?.kind === "relation")
@@ -17,14 +19,40 @@ export function relationFieldOf(meta, name) {
17
19
  for (const [relation, field] of Object.entries(meta.fields))
18
20
  if (field.kind === "relation" && field.identified_by === name)
19
21
  return of(relation, field);
22
+ // A key alone that says whose record it names: the record is not in hand, its key is.
23
+ if (own !== undefined && own.kind !== "embedded" && own.relation)
24
+ return {
25
+ relation: name,
26
+ key: name,
27
+ target: own.relation,
28
+ many: own.many === true,
29
+ field: own,
30
+ held: false,
31
+ };
20
32
  return undefined;
21
33
  }
34
+ /**
35
+ * Whether `target` names `one` the way a key does — by its model, `auth.Tenant` in another
36
+ * context or `Tenant` in its own —: the name a generated entity's key is made of (`entityKeyOf`).
37
+ */
38
+ function namedBy(one, target) {
39
+ const dot = target.lastIndexOf(".");
40
+ if (dot === -1)
41
+ return one.key === entityKeyOf(one.domain, target);
42
+ return one.key === entityKeyOf(target.slice(0, dot), target.slice(dot + 1));
43
+ }
22
44
  /**
23
45
  * The declared entity a relation points at: the one that says it is that aggregate, else the
24
- * one whose model definition is, else the one whose key it is (`"ventas:cliente"`).
46
+ * one whose model definition is, else the one whose key it is (`"ventas:cliente"`), else the one
47
+ * its model names (`"auth.Tenant"` → `auth:tenant`), else the only one of that kind — a context
48
+ * named by its own name (`sincpro-forge-auth.Tenant`) where the application keys it by alias.
25
49
  */
26
50
  export function entityFor(entities, target, metaOf = () => undefined) {
51
+ const model = target.slice(target.lastIndexOf(".") + 1);
52
+ const ofKind = entities.filter((one) => one.kind === kindOf(model));
27
53
  return (entities.find((one) => one.aggregate === target) ??
28
54
  entities.find((one) => metaOf(one.key)?.aggregate === target) ??
29
- entities.find((one) => one.key === target));
55
+ entities.find((one) => one.key === target) ??
56
+ entities.find((one) => namedBy(one, target)) ??
57
+ (ofKind.length === 1 ? ofKind[0] : undefined));
30
58
  }
@@ -9,6 +9,11 @@ import { type Transport } from "./transport.js";
9
9
  * one record (`one()`), a write (`send()`, with its `Idempotency-Key`), and its refusals as a
10
10
  * `TransportError`, the one error every screen explains.
11
11
  *
12
+ * The definition of each model — what a list, a form and a select are built from — is read
13
+ * from the bounded context's discovery document (`document`, `/openapi.json` by default), once,
14
+ * and read again only when an answer says another version of its model (`model_version`); the
15
+ * document is revalidated with its `ETag`, so an unchanged one costs a `304`.
16
+ *
12
17
  * const transport = restTransport({
13
18
  * base: "/v1",
14
19
  * headers: () => ({ Authorization: `Bearer ${session.secret}` }),
@@ -21,6 +26,24 @@ export type RestOptions = {
21
26
  headers?: Record<string, string> | (() => Record<string, string>);
22
27
  /** Defaults to the global `fetch`. Inject one for tests. */
23
28
  fetch?: typeof fetch;
29
+ /** Where the bounded context's discovery document is: `"/openapi.json"` by default, at the
30
+ * origin of `base`. `null`: none is read, and the definitions come only from `metas`. */
31
+ document?: string | null;
32
+ /**
33
+ * The version of each model the application was written against — the snapshot it was
34
+ * generated from (`versionsOf(contract)`). With it, an answer of another version is told to
35
+ * `onVersionDrift`: the server moved, the generated code did not.
36
+ */
37
+ snapshot?: Readonly<Record<string, string>>;
38
+ /** Called once per model and version the server answers that the snapshot does not hold —
39
+ * never an error: the screen keeps working on the live definition. */
40
+ onVersionDrift?: (drift: VersionDrift) => void;
41
+ };
42
+ /** A model the server answers at another version than the snapshot the code came from. */
43
+ export type VersionDrift = {
44
+ model: string;
45
+ snapshot: string;
46
+ live: string;
24
47
  };
25
48
  export declare function urlOf<T>(base: string, route: string, criteria?: Criteria<T>): string;
26
49
  export declare function restTransport(options?: RestOptions): Transport;
package/dist/core/rest.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { readProblem } from "@sincpro/criteria";
2
2
  import { RestError, restSource } from "@sincpro/criteria/rest";
3
+ import { definitionOf, modelAt, } from "./discovery.js";
3
4
  import { TransportError, } from "./transport.js";
4
5
  /** The keys of an answer that are not the record: what is left is the record's own field. */
5
- const ENVELOPE = new Set(["cursor", "count", "entity_meta_data", "dropped", "draft"]);
6
+ const ENVELOPE = new Set(["cursor", "count", "model_version", "dropped", "draft", "missing"]);
6
7
  export function urlOf(base, route, criteria) {
7
8
  const url = `${base}${route}`;
8
9
  if (criteria === undefined)
@@ -10,10 +11,77 @@ export function urlOf(base, route, criteria) {
10
11
  const joiner = url.includes("?") ? "&" : "?";
11
12
  return `${url}${joiner}criteria=${encodeURIComponent(JSON.stringify(criteria))}`;
12
13
  }
14
+ /** The path a route is asked at, without its query: what a document path is matched with. */
15
+ function pathOf(url) {
16
+ const path = url.split("?")[0] ?? url;
17
+ return /^https?:\/\//.test(path) ? new URL(path).pathname : path;
18
+ }
19
+ /** Where the document is: `document` as given when absolute, else at the origin of `base`. */
20
+ function documentUrl(base, document) {
21
+ if (/^https?:\/\//.test(document) || !/^https?:\/\//.test(base))
22
+ return document;
23
+ return new URL(document, base).toString();
24
+ }
13
25
  export function restTransport(options = {}) {
14
26
  const base = options.base ?? "";
15
27
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
16
28
  const own = () => typeof options.headers === "function" ? options.headers() : (options.headers ?? {});
29
+ // The discovery document, read once; asked again — with its ETag — when an answer says a
30
+ // version of its model the document did not.
31
+ const located = options.document === null ? null : (options.document ?? "/openapi.json");
32
+ let held;
33
+ let tag = null;
34
+ function documentRead(fresh) {
35
+ if (located === null)
36
+ return Promise.resolve(null);
37
+ if (held !== undefined && !fresh)
38
+ return held;
39
+ const before = held;
40
+ held = (async () => {
41
+ try {
42
+ const response = await doFetch(documentUrl(base, located), {
43
+ headers: { ...own(), ...(tag === null ? {} : { "If-None-Match": tag }) },
44
+ });
45
+ if (response.status === 304 && before !== undefined)
46
+ return await before;
47
+ if (!response.ok)
48
+ return null;
49
+ tag = response.headers.get("etag");
50
+ return (await response.json());
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ })();
56
+ return held;
57
+ }
58
+ /** The definition of the model `url` answers; read again when `version` is not the one held. */
59
+ // Each drift is told once: a list read every few seconds would say it on every page.
60
+ const told = new Set();
61
+ function noticeDrift(model, live) {
62
+ const snapshot = options.snapshot?.[model];
63
+ if (snapshot === undefined || !live || live === snapshot)
64
+ return;
65
+ const key = `${model}\u0000${live}`;
66
+ if (told.has(key))
67
+ return;
68
+ told.add(key);
69
+ options.onVersionDrift?.({ model, snapshot, live });
70
+ }
71
+ async function definitionAt(url, method, version) {
72
+ const published = await documentRead(false);
73
+ if (published === null)
74
+ return null;
75
+ const name = modelAt(published, pathOf(url), method);
76
+ if (name === undefined)
77
+ return null;
78
+ noticeDrift(name, version);
79
+ const known = definitionOf(published, name);
80
+ if (known === undefined || !version || known.version === version)
81
+ return known?.meta ?? null;
82
+ const again = await documentRead(true);
83
+ return (again === null ? undefined : definitionOf(again, name))?.meta ?? known.meta;
84
+ }
17
85
  async function get(route, url, signal, write) {
18
86
  const headers = write
19
87
  ? {
@@ -36,7 +104,11 @@ export function restTransport(options = {}) {
36
104
  async list(route, criteria, signal) {
37
105
  const source = restSource(`${base}${route}`, { headers: own, fetch: doFetch });
38
106
  try {
39
- return await source.read(criteria, signal);
107
+ const page = await source.read(criteria, signal);
108
+ return {
109
+ ...page,
110
+ meta: page.meta ?? (await definitionAt(`${base}${route}`, "get", page.version)),
111
+ };
40
112
  }
41
113
  catch (error) {
42
114
  if (error instanceof RestError)
@@ -44,6 +116,9 @@ export function restTransport(options = {}) {
44
116
  throw error;
45
117
  }
46
118
  },
119
+ async read(route, signal) {
120
+ return (await get(route, urlOf(base, route), signal));
121
+ },
47
122
  async one(route, signal) {
48
123
  const answer = (await get(route, urlOf(base, route), signal));
49
124
  const own = Object.keys(answer).filter((key) => !ENVELOPE.has(key));
@@ -52,7 +127,7 @@ export function restTransport(options = {}) {
52
127
  throw new TransportError(route, 200, null, `${route} answered ${own.length} fields of its own (${own.join(", ")}); a record answers one`);
53
128
  return {
54
129
  record: answer[key],
55
- meta: answer["entity_meta_data"] ?? null,
130
+ meta: await definitionAt(urlOf(base, route), "get", answer["model_version"]),
56
131
  dropped: answer["dropped"] ?? [],
57
132
  draft: answer["draft"] ?? null,
58
133
  };
@@ -2,19 +2,12 @@ import type { Meta } from "@sincpro/criteria";
2
2
  /**
3
3
  * A model definition read from a JSON Schema — what an OpenAPI document holds.
4
4
  *
5
- * Context: what sincpro_framework's OpenAPI 3.1 describes and what it does not, checked
6
- * against a running forge:
5
+ * Context: a model a READ answers is published by sincpro_framework as its contract — JSON
6
+ * Schema with `x-sincpro` — and read by the transport (`metaFromContract`, `core/discovery`).
7
+ * What has no `x-sincpro` is a plain JSON Schema: a COMMAND's body, a value object it carries.
7
8
  *
8
- * - the records a READ answers are invisible: the framework serialises them with its own
9
- * envelope, so `GET /projects` and `GET /projects/{id}` answer schema `{}` and no
10
- * `Project` schema exists. A list's definition comes from `entity_meta_data`, at runtime
11
- * or preloaded (`FrameworkProvider metas`) — not from here;
12
- * - the COMMANDS and the value objects are described well, and better than the meta in one
13
- * place: inside a value object `entity_meta_data` sends a `Literal` and a `list[str]` as
14
- * `unknown`, where the schema says `enum: ["es", "en"]` and `array<string>`.
15
- *
16
- * So this reads a component schema into a `Meta` — the form of a Command, a value object — and
17
- * `completeMeta` fills, from it, what the server's meta left `unknown`.
9
+ * So this reads such a component schema into a `Meta` — the form of a Command, a value object —
10
+ * and `completeMeta` fills, from it, what a definition left `unknown`.
18
11
  *
19
12
  * const spec = metaFromSchema("ProjectSpecification", doc.components.schemas);
20
13
  * const fixed = completeMeta(project.fields.specification.definition, spec);
@@ -12,10 +12,7 @@ async function page(transport, trail, cursor) {
12
12
  ...trail.question,
13
13
  pagination: { ...trail.question.pagination, limit: trail.size },
14
14
  };
15
- const answer = await transport.list(trail.route, {
16
- ...resumingFrom(sized, cursor),
17
- meta: false,
18
- });
15
+ const answer = await transport.list(trail.route, resumingFrom(sized, cursor));
19
16
  return {
20
17
  ids: answer.rows.map((row) => String(row[trail.key] ?? "")),
21
18
  after: answer.cursor,
@@ -18,7 +18,18 @@ export interface Transport {
18
18
  one<T>(route: string, signal?: AbortSignal): Promise<One<T>>;
19
19
  /** A Command — a write, an action, a preview: `method` and a JSON body, its answer back. */
20
20
  send<T>(method: Method, route: string, body: unknown, signal?: AbortSignal, options?: SendOptions): Promise<T>;
21
+ /**
22
+ * A read that is neither a page nor one record — a Query of the context's own, `GET /me` —:
23
+ * the route with its parameters already in it (`listRoute`), its answer as it came. Optional,
24
+ * so a transport written before it keeps compiling; call it through `readRoute`.
25
+ */
26
+ read?<T>(route: string, signal?: AbortSignal): Promise<T>;
21
27
  }
28
+ /**
29
+ * A read through `transport.read`, or the reason it cannot be: a transport that has no `read`
30
+ * is said so by name, never a `TypeError` from somewhere inside a screen.
31
+ */
32
+ export declare function readRoute<T>(transport: Transport, route: string, signal?: AbortSignal): Promise<T>;
22
33
  export type Method = "POST" | "PUT" | "PATCH" | "DELETE";
23
34
  /**
24
35
  * How a Command travels besides its body.
@@ -1,4 +1,13 @@
1
1
  import { frameworkCopy } from "./copy.js";
2
+ /**
3
+ * A read through `transport.read`, or the reason it cannot be: a transport that has no `read`
4
+ * is said so by name, never a `TypeError` from somewhere inside a screen.
5
+ */
6
+ export function readRoute(transport, route, signal) {
7
+ if (transport.read === undefined)
8
+ return Promise.reject(new Error(`this transport has no read(): it cannot ask GET ${route} — give it one`));
9
+ return transport.read(route, signal);
10
+ }
2
11
  /**
3
12
  * A refusal, from any wire. `problem` is what the server said about it (RFC 9457 plus the
4
13
  * engine's `kind`, `next_step`, `guidance`) or `null` when it said nothing readable — a proxy's
@@ -5,11 +5,12 @@
5
5
  */
6
6
  export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
7
  export { type ListScope, ListScopeProvider, useListScope, } from "./scope.js";
8
- export { type CommandState, type Rehearsal, useCommand, } from "./useCommand.js";
8
+ export { type AnswerOf, type CommandState, type Rehearsal, useCommand, } from "./useCommand.js";
9
9
  export { type Groups, useGroups } from "./useGroups.js";
10
10
  export { useHistory } from "./useHistory.js";
11
11
  export { type Listing, type ListingOptions, type Paging, useListing, } from "./useListing.js";
12
12
  export { excluding, type Lookup, useLookup } from "./useLookup.js";
13
+ export { useNameOf } from "./useNameOf.js";
13
14
  export { type PivotAxes, type PivotReading, usePivot, } from "./usePivot.js";
14
15
  export { type Editing, type RecordReading, type RecordState, useRecord, } from "./useRecord.js";
15
16
  export { useRelated } from "./useRelated.js";
@@ -10,6 +10,7 @@ export { useGroups } from "./useGroups.js";
10
10
  export { useHistory } from "./useHistory.js";
11
11
  export { useListing, } from "./useListing.js";
12
12
  export { excluding, useLookup } from "./useLookup.js";
13
+ export { useNameOf } from "./useNameOf.js";
13
14
  export { usePivot, } from "./usePivot.js";
14
15
  export { useRecord, } from "./useRecord.js";
15
16
  export { useRelated } from "./useRelated.js";
@@ -1,5 +1,5 @@
1
1
  import type { AnyRecord } from "@sincpro/criteria";
2
- import { type Entity } from "../core/entity.js";
2
+ import { type CommandAnswers, type CommandBodies, type Entity } from "../core/entity.js";
3
3
  /**
4
4
  * One Command of an entity: run it, or ask first what it would do.
5
5
  *
@@ -12,19 +12,29 @@ import { type Entity } from "../core/entity.js";
12
12
  * One at a time: `busy` turns the button off, because a payment sent twice is two payments. And
13
13
  * once sent, the same gesture keeps its `Idempotency-Key` until the server answers: a retry
14
14
  * after a dropped request is the same payment, never a second one (`retryKeys`).
15
+ *
16
+ * A typed entity (`entity<Issue, { send: { message: string } }>`) gets its names and bodies
17
+ * checked: `useCommand(issues, "send").run(id, { mesage })` does not compile. TypeScript infers
18
+ * that only when no type argument is written — `useCommand<Issue, Answer>(…)` stays loose.
15
19
  */
16
20
  export type Rehearsal = {
17
21
  text: string;
18
22
  data: Record<string, unknown>;
19
23
  };
20
- export type CommandState<R> = {
21
- run: (id?: string, body?: AnyRecord) => Promise<R | undefined>;
24
+ export type CommandState<R, B extends AnyRecord = AnyRecord> = {
25
+ /** Without a body, an empty one: the route may name everything. A body given is checked. */
26
+ run: (id?: string, body?: B) => Promise<R | undefined>;
22
27
  /** The dry run: what it would do, nothing touched. */
23
- rehearse: (id?: string, body?: AnyRecord) => Promise<Rehearsal | undefined>;
28
+ rehearse: (id?: string, body?: B) => Promise<Rehearsal | undefined>;
24
29
  busy: boolean;
25
30
  error: unknown;
26
31
  /** The last dry run's answer, until `reset`. */
27
32
  rehearsal: Rehearsal | null;
28
33
  reset: () => void;
29
34
  };
30
- export declare function useCommand<T extends AnyRecord, R = unknown>(entity: Entity<T>, name: string): CommandState<R>;
35
+ /**
36
+ * What a Command answers: `R` when the screen writes it, else what its entity says the Command
37
+ * answers (`CommandAnswers`), else `unknown`.
38
+ */
39
+ export type AnswerOf<R, A, N> = unknown extends R ? (N extends keyof A ? A[N] : unknown) : R;
40
+ export declare function useCommand<T extends AnyRecord, R = unknown, C extends CommandBodies = CommandBodies, N extends keyof C & string = keyof C & string, A extends CommandAnswers = CommandAnswers>(entity: Entity<T, C, A>, name: N): CommandState<AnswerOf<R, A, N>, C[N]>;
@@ -1,10 +1,11 @@
1
1
  "use client";
2
- import { pathFor } from "../core/entity.js";
2
+ import { bodyFor, pathFor, } from "../core/entity.js";
3
3
  import { retryKeys } from "../core/retry.js";
4
4
  import { useFramework } from "./context.js";
5
5
  import { useCallback, useEffect, useRef, useState } from "react";
6
6
  export function useCommand(entity, name) {
7
7
  const { transport } = useFramework();
8
+ // A name outside the declared ones still reaches here from untyped code: say which.
8
9
  const route = entity.commands[name];
9
10
  if (route === undefined)
10
11
  throw new Error(`${entity.key} declares no command "${name}"`);
@@ -25,8 +26,10 @@ export function useCommand(entity, name) {
25
26
  setBusy(true);
26
27
  setError(null);
27
28
  const idempotencyKey = gesture.keyFor({ id, body });
29
+ // A Command whose body names its record (`target`) gets the id there.
30
+ const sent = bodyFor(route, id, body);
28
31
  try {
29
- const answer = await transport.send(route.method, pathFor(route, id, body), body, undefined, { idempotencyKey });
32
+ const answer = await transport.send(route.method, pathFor(route, id, sent), sent, undefined, { idempotencyKey });
30
33
  gesture.settle(null);
31
34
  return answer;
32
35
  }
@@ -42,8 +45,8 @@ export function useCommand(entity, name) {
42
45
  }
43
46
  }, [transport, route]);
44
47
  return {
45
- run: (id, body = {}) => send(id, body, keys.current),
46
- rehearse: async (id, body = {}) => {
48
+ run: (id, body) => send(id, body ?? {}, keys.current),
49
+ rehearse: async (id, body) => {
47
50
  const answer = await send(id, { ...body, dry_run: true }, retryKeys());
48
51
  if (answer !== undefined && mounted.current)
49
52
  setRehearsal(answer);
@@ -38,7 +38,6 @@ export function useGroups(listing, options = {}) {
38
38
  return () => aborter.abort();
39
39
  const criteria = {
40
40
  ...JSON.parse(question),
41
- meta: false,
42
41
  grouping: {
43
42
  group_by: levels.map((level) => ({ ...level })),
44
43
  ...(sums === "" ? {} : { measures: measuresOf(sums.split(",")) }),
@@ -63,7 +62,7 @@ export function useGroups(listing, options = {}) {
63
62
  return;
64
63
  reading.current.add(key);
65
64
  const { grouping: _grouping, pagination: _pagination, ...own } = bucket.criteria;
66
- const first = { ...own, meta: false, pagination: { limit: pageSize } };
65
+ const first = { ...own, pagination: { limit: pageSize } };
67
66
  void transport.list(route, after === null ? first : resumingFrom(first, after)).then((page) => {
68
67
  reading.current.delete(key);
69
68
  setRows((now) => {
@@ -24,7 +24,7 @@ export function useHistory(entity, id, deps = []) {
24
24
  return;
25
25
  const aborter = new AbortController();
26
26
  const criteria = {
27
- where: {
27
+ selection: {
28
28
  all: [
29
29
  { field: "entity_type", operator: "=", value: history.type },
30
30
  { field: "entity_id", operator: "=", value: id },
@@ -1,5 +1,5 @@
1
1
  import { type AnyRecord, type Count, type Criteria, type Dropped, type Expression, type Meta, type ReadingStatus, type Sort } from "@sincpro/criteria";
2
- import { type Entity } from "../core/entity.js";
2
+ import { type CommandBodies, type Entity } from "../core/entity.js";
3
3
  import { type ListDefinition } from "../core/list.js";
4
4
  /**
5
5
  * N records of an entity, live: what a list draws and the gestures that drive it.
@@ -17,8 +17,9 @@ import { type ListDefinition } from "../core/list.js";
17
17
  * All three refine the same reading instead of starting another. It holds state and draws
18
18
  * nothing: `EntityList` draws it, and a screen that needs another shape draws it itself.
19
19
  */
20
- export type Listing<T> = {
21
- entity: Entity<T & AnyRecord>;
20
+ export type Listing<T, C extends CommandBodies = CommandBodies> = {
21
+ /** Its entity, with the Commands it types (`entity<T, C>`): what `useRowCommands` checks. */
22
+ entity: Entity<T & AnyRecord, C>;
22
23
  /** The named list it reads, when it was handed one (`defineList`): what `EntityList` draws
23
24
  * by default — its columns, filters, faces, title — and how `useGroups` starts. */
24
25
  definition?: ListDefinition<T & AnyRecord>;
@@ -94,4 +95,4 @@ export type ListingOptions<T> = {
94
95
  /** `more` mode: the most rows ever on screen. 500 by default. */
95
96
  maxRows?: number;
96
97
  };
97
- export declare function useListing<T extends AnyRecord>(given: Entity<T> | ListDefinition<T>, own?: ListingOptions<T>): Listing<T>;
98
+ export declare function useListing<T extends AnyRecord, C extends CommandBodies = CommandBodies>(given: Entity<T, C> | ListDefinition<T>, own?: ListingOptions<T>): Listing<T, C>;
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { merge, resource, resumingFrom, searchOver, } from "@sincpro/criteria";
3
3
  import { useReading } from "@sincpro/criteria-react";
4
- import { listRoute } from "../core/entity.js";
4
+ import { listRoute, } from "../core/entity.js";
5
5
  import { isList, scopeOf } from "../core/list.js";
6
6
  import { useFramework } from "./context.js";
7
7
  import { useListScope } from "./scope.js";
@@ -12,12 +12,13 @@ export function useListing(given, own = {}) {
12
12
  const { transport, locale, metas } = useFramework();
13
13
  // A named list is its entity under a fixed scope: the scope ANDs under the caller's own.
14
14
  const definition = isList(given) ? given : undefined;
15
- const entity = definition?.entity ?? given;
15
+ // A named list's entity has no typed Commands of its own: the default, as `C` then is.
16
+ const entity = (definition?.entity ?? given);
16
17
  // The screen's cut for this entity (a chooser's, `ListScopeProvider`) ANDs like a scope.
17
18
  const cut = useListScope(entity.key);
18
19
  const scopes = [
19
20
  ...(definition === undefined ? [] : [scopeOf(definition)]),
20
- ...(cut === undefined ? [] : [{ where: cut }]),
21
+ ...(cut === undefined ? [] : [{ selection: cut }]),
21
22
  ];
22
23
  const options = scopes.length === 0
23
24
  ? own
@@ -27,8 +28,8 @@ export function useListing(given, own = {}) {
27
28
  };
28
29
  const route = listRoute(entity.list, options.params);
29
30
  const source = useMemo(() => resource((criteria, signal) => transport.list(route, criteria, signal)), [transport, route]);
30
- // Decided once, at mount: a definition already known means the server is not asked for it
31
- // again. Deciding it later would change the criteria and restart the reading.
31
+ // A definition already known draws the columns before the first page arrives; the one the
32
+ // transport reads from the discovery document comes with it.
32
33
  const [preloaded] = useState(() => metas.get(entity.key));
33
34
  const paging = options.paging ?? "pages";
34
35
  const size = options.pageSize ?? options.criteria?.pagination?.limit ?? 50;
@@ -37,7 +38,7 @@ export function useListing(given, own = {}) {
37
38
  ...options.criteria,
38
39
  pagination: { ...options.criteria?.pagination, limit: size },
39
40
  };
40
- const base = preloaded ? { ...asked, meta: false } : asked;
41
+ const base = asked;
41
42
  const reading = useReading(source, base);
42
43
  // `pages` mode: the cursor that opens each page walked so far — page 0 opens with none.
43
44
  const [cursors, setCursors] = useState([null]);
@@ -59,9 +60,9 @@ export function useListing(given, own = {}) {
59
60
  let criteria = base;
60
61
  const found = searchOver(meta, next.text);
61
62
  if (found !== undefined)
62
- criteria = merge(criteria, { where: found });
63
+ criteria = merge(criteria, { selection: found });
63
64
  if (next.where !== undefined)
64
- criteria = merge(criteria, { where: next.where });
65
+ criteria = merge(criteria, { selection: next.where });
65
66
  if (next.order.length > 0)
66
67
  criteria = merge(criteria, { order: [...next.order] });
67
68
  return criteria;