@sincpro/web-framework 1.0.0 → 2.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 (104) hide show
  1. package/README.md +207 -71
  2. package/dist/core/cache.d.ts +1 -2
  3. package/dist/core/cache.js +14 -4
  4. package/dist/core/explain.d.ts +15 -0
  5. package/dist/core/{transport.js → explain.js} +4 -17
  6. package/dist/core/form.d.ts +1 -1
  7. package/dist/core/form.js +1 -0
  8. package/dist/core/index.d.ts +9 -14
  9. package/dist/core/index.js +8 -13
  10. package/dist/core/list.d.ts +5 -4
  11. package/dist/core/list.js +1 -0
  12. package/dist/core/lookup.d.ts +1 -1
  13. package/dist/core/lookup.js +1 -0
  14. package/dist/core/present.js +1 -1
  15. package/dist/core/relation.d.ts +12 -2
  16. package/dist/core/relation.js +30 -2
  17. package/dist/core/summary.d.ts +1 -6
  18. package/dist/core/trail.d.ts +1 -1
  19. package/dist/core/trail.js +1 -0
  20. package/dist/errors/index.d.ts +48 -0
  21. package/dist/errors/index.js +56 -0
  22. package/dist/react/context.d.ts +1 -3
  23. package/dist/react/context.js +1 -2
  24. package/dist/react/index.d.ts +4 -1
  25. package/dist/react/index.js +3 -0
  26. package/dist/react/scope.d.ts +1 -1
  27. package/dist/react/scope.js +1 -1
  28. package/dist/react/useCommand.d.ts +15 -5
  29. package/dist/react/useCommand.js +7 -5
  30. package/dist/react/useContextValues.d.ts +15 -0
  31. package/dist/react/useContextValues.js +19 -0
  32. package/dist/react/useHistory.d.ts +1 -1
  33. package/dist/react/useHistory.js +1 -0
  34. package/dist/react/useListing.d.ts +8 -7
  35. package/dist/react/useListing.js +8 -7
  36. package/dist/react/useLookup.d.ts +1 -1
  37. package/dist/react/useLookup.js +1 -0
  38. package/dist/react/useNameOf.d.ts +13 -0
  39. package/dist/react/useNameOf.js +44 -0
  40. package/dist/react/useRecord.d.ts +1 -2
  41. package/dist/react/useRecord.js +1 -4
  42. package/dist/react/useRelated.d.ts +1 -1
  43. package/dist/react/useRelated.js +1 -0
  44. package/dist/react/useService.d.ts +38 -0
  45. package/dist/react/useService.js +66 -0
  46. package/dist/react/useSummary.d.ts +1 -1
  47. package/dist/react/useSummary.js +1 -0
  48. package/dist/telemetry/index.d.ts +45 -0
  49. package/dist/telemetry/index.js +55 -0
  50. package/dist/web/Refused.js +1 -1
  51. package/dist/web/list/EntityList.d.ts +5 -4
  52. package/dist/web/list/EntityList.js +3 -3
  53. package/dist/web/list/EntitySearchBar.d.ts +2 -1
  54. package/dist/web/list/EntitySearchBar.js +17 -11
  55. package/dist/web/list/presentation.d.ts +3 -3
  56. package/dist/web/list/presentation.js +2 -0
  57. package/dist/web/list/rowCommands.d.ts +16 -12
  58. package/dist/web/list/rowCommands.js +3 -3
  59. package/dist/web/record/CommandButton.d.ts +9 -6
  60. package/dist/web/record/CommandButton.js +1 -0
  61. package/dist/web/record/EntityPicker.d.ts +1 -1
  62. package/dist/web/record/EntityPicker.js +1 -0
  63. package/dist/web/record/EntityTags.d.ts +1 -1
  64. package/dist/web/record/EntityTags.js +1 -0
  65. package/dist/web/record/RelatedList.d.ts +1 -1
  66. package/dist/web/record/RelatedList.js +1 -0
  67. package/dist/web/record/control.d.ts +1 -1
  68. package/dist/web/record/control.js +1 -1
  69. package/dist/web/record/edit.js +20 -7
  70. package/dist/web/record/lines.js +7 -1
  71. package/dist/web/record/opening.d.ts +1 -1
  72. package/dist/web/record/opening.js +1 -0
  73. package/dist/web/workspace/SincproApp.d.ts +1 -2
  74. package/dist/web/workspace/SincproApp.js +1 -0
  75. package/dist/web/workspace/composer.d.ts +1 -2
  76. package/dist/web/workspace/composer.js +2 -2
  77. package/dist/web/workspace/open.d.ts +1 -1
  78. package/dist/web/workspace/open.js +1 -0
  79. package/dist/web/workspace/record.d.ts +1 -1
  80. package/dist/web/workspace/record.js +1 -1
  81. package/dist/web/workspace/workspace.d.ts +1 -1
  82. package/dist/web/workspace/workspace.js +1 -0
  83. package/package.json +48 -7
  84. package/dist/core/discovery.d.ts +0 -47
  85. package/dist/core/discovery.js +0 -68
  86. package/dist/core/entity.d.ts +0 -159
  87. package/dist/core/entity.js +0 -142
  88. package/dist/core/ids.d.ts +0 -17
  89. package/dist/core/ids.js +0 -52
  90. package/dist/core/memory.d.ts +0 -43
  91. package/dist/core/memory.js +0 -99
  92. package/dist/core/meta.d.ts +0 -121
  93. package/dist/core/meta.js +0 -130
  94. package/dist/core/metas.d.ts +0 -17
  95. package/dist/core/metas.js +0 -7
  96. package/dist/core/rest.d.ts +0 -34
  97. package/dist/core/rest.js +0 -127
  98. package/dist/core/retry.d.ts +0 -24
  99. package/dist/core/retry.js +0 -25
  100. package/dist/core/schema.d.ts +0 -39
  101. package/dist/core/schema.js +0 -128
  102. package/dist/core/transport.d.ts +0 -79
  103. package/dist/core/zone.d.ts +0 -27
  104. package/dist/core/zone.js +0 -75
@@ -1,142 +0,0 @@
1
- import { readExpression } from "@sincpro/criteria";
2
- /**
3
- * The params that say what a reference without an id is for: `new` is the form of a record
4
- * that does not exist yet, `pick` is the list opened to choose one. Params, because they are
5
- * what a composer reference carries and survives a reload with.
6
- */
7
- export const NEW_PARAM = "new";
8
- export const PICK_PARAM = "pick";
9
- /** What was typed where the chooser was asked for: its list opens on that search. */
10
- export const QUERY_PARAM = "q";
11
- /** The list a record was opened from (its `Trail`): «3 / 64» and the arrows to its neighbours. */
12
- export const TRAIL_PARAM = "from";
13
- /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
14
- * a number), where a param per field would turn all of them into text. */
15
- export const WITH_PARAM = "with";
16
- /** What a chooser may offer at all, as JSON: the picker's cut — its criteria, the keys it
17
- * excludes, its named list's scope — that the list it opens ANDs under everything. */
18
- export const SCOPE_PARAM = "scope";
19
- /**
20
- * What a new record's reference says it starts with (`newRef(values)`), or nothing.
21
- *
22
- * Context: a reference survives a reload and a link, so its params can be anything a person
23
- * typed in the address bar — a value that is not a JSON object is not a start, never an error.
24
- */
25
- export function startingValuesOf(ref) {
26
- const written = ref.params?.[WITH_PARAM];
27
- if (written === undefined)
28
- return {};
29
- try {
30
- const read = JSON.parse(written);
31
- return read !== null && typeof read === "object" && !Array.isArray(read)
32
- ? read
33
- : {};
34
- }
35
- catch {
36
- return {};
37
- }
38
- }
39
- /**
40
- * The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
41
- *
42
- * Context: a picker that may offer only some records — the contacts of the chosen customer, the
43
- * tenants a project is not shared with yet — opened the workspace's chooser on the WHOLE
44
- * entity, and offered the rest. The cut travels in the reference, so it survives a reload; read
45
- * from an address bar it is untyped, so it is read the way criteria reads a filter from outside
46
- * (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
47
- * OFFERED; the server still decides what may be stored.
48
- */
49
- export function scopeOfRef(ref) {
50
- const written = ref.params?.[SCOPE_PARAM];
51
- if (written === undefined)
52
- return undefined;
53
- try {
54
- return readExpression(JSON.parse(written));
55
- }
56
- catch {
57
- return undefined;
58
- }
59
- }
60
- const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
61
- /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
62
- export function writeRoute(text) {
63
- const [method, path] = text.trim().split(/\s+/, 2);
64
- if (!METHODS.has(method) || path === undefined)
65
- throw new Error(`"${text}" is not "METHOD /path": a write says how it is sent`);
66
- return { method: method, path };
67
- }
68
- const PATH_KEY = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
69
- /**
70
- * The path with the record's key in place of `{id}`, and every other `{name}` taken from the
71
- * body's field of that name: `POST /projects/{id}/shares/{tenant_id}/revoke` with
72
- * `{ tenant_id: "acme" }`.
73
- *
74
- * Context: sincpro_framework reads a path parameter as a field of the use case's DTO (its
75
- * wire merges `{...body, ...path_params}`), so the body already names every key a route
76
- * needs — a second argument for them would say the same thing twice. A key the body lacks is
77
- * the screen's bug, said before anything is sent. Without an `id`, `{id}` stays: a create or a
78
- * preview of a new record has none.
79
- */
80
- export function pathFor(route, id, body) {
81
- return route.path.replace(PATH_KEY, (whole, name) => {
82
- if (name === "id")
83
- return id === undefined ? whole : encodeURIComponent(id);
84
- const value = body?.[name];
85
- if (value === undefined || value === null || value === "")
86
- throw new Error(`"${route.method} ${route.path}" needs "${name}" in the body`);
87
- return encodeURIComponent(String(value));
88
- });
89
- }
90
- /** A list's route with its own parameters: `{ tenant_id: "acme" }` → `/projects?tenant_id=acme`.
91
- * An empty value is no parameter — a filter left blank. */
92
- export function listRoute(list, params) {
93
- const query = new URLSearchParams(Object.entries(params ?? {}).filter(([, value]) => value !== "")).toString();
94
- if (query === "")
95
- return list;
96
- return `${list}${list.includes("?") ? "&" : "?"}${query}`;
97
- }
98
- export function entity(key, routes) {
99
- if (!/^[^:\s]+:[^:\s]+$/.test(key))
100
- throw new Error(`entity key "${key}" is not domain:kind`);
101
- const list = routes.list.split("?")[0] ?? routes.list;
102
- const template = routes.one ?? `${list}/{id}`;
103
- const [domain = "", kind = ""] = key.split(":");
104
- return {
105
- key,
106
- domain,
107
- kind,
108
- ref: (id) => ({ domain, kind, ...(id === undefined || id === "" ? {} : { id }) }),
109
- newRef: (values) => ({
110
- domain,
111
- kind,
112
- params: {
113
- [NEW_PARAM]: "1",
114
- ...(values === undefined || Object.keys(values).length === 0
115
- ? {}
116
- : { [WITH_PARAM]: JSON.stringify(values) }),
117
- },
118
- }),
119
- chooserRef: (query, scope) => ({
120
- domain,
121
- kind,
122
- params: {
123
- [PICK_PARAM]: "1",
124
- ...(query === undefined || query.trim() === ""
125
- ? {}
126
- : { [QUERY_PARAM]: query.trim() }),
127
- ...(scope === undefined ? {} : { [SCOPE_PARAM]: JSON.stringify(scope) }),
128
- },
129
- }),
130
- list: routes.list,
131
- one: (id) => template.replace("{id}", encodeURIComponent(id)),
132
- commands: Object.fromEntries(Object.entries(routes.commands ?? {}).map(([name, text]) => [name, writeRoute(text)])),
133
- ...(routes.create === undefined ? {} : { create: writeRoute(routes.create) }),
134
- ...(routes.save === undefined ? {} : { save: writeRoute(routes.save) }),
135
- ...(routes.preview === undefined ? {} : { preview: writeRoute(routes.preview) }),
136
- ...(routes.draft === undefined ? {} : { draft: writeRoute(routes.draft) }),
137
- ...(routes.edit === undefined ? {} : { edit: writeRoute(routes.edit) }),
138
- ...(routes.history === undefined ? {} : { history: routes.history }),
139
- summary: routes.summary ?? {},
140
- ...(routes.aggregate === undefined ? {} : { aggregate: routes.aggregate }),
141
- };
142
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * A new record's key, minted where the record is born: a UUID v7 as 32 hex characters —
3
- * sincpro_framework's `new_entity_id`.
4
- *
5
- * Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
6
- * UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
7
- * A form that waited for the server to name it could neither keep a draft of a new record nor
8
- * reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path). The layout
9
- * is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
10
- * within the millisecond, the variant and 62 random bits — so ids minted here sort by when
11
- * they were minted, like the server's, and ordering by `id` is still ordering by creation.
12
- *
13
- * newEntityId() // "019a4c2e7f1074a8b13fa739ccbdcd53"
14
- */
15
- export declare function newEntityId(now?: number): string;
16
- /** A key that is a UUID v7 as sincpro_framework writes it: 32 hex, version 7, variant `10`. */
17
- export declare function isEntityId(text: string): boolean;
package/dist/core/ids.js DELETED
@@ -1,52 +0,0 @@
1
- /**
2
- * A new record's key, minted where the record is born: a UUID v7 as 32 hex characters —
3
- * sincpro_framework's `new_entity_id`.
4
- *
5
- * Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
6
- * UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
7
- * A form that waited for the server to name it could neither keep a draft of a new record nor
8
- * reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path). The layout
9
- * is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
10
- * within the millisecond, the variant and 62 random bits — so ids minted here sort by when
11
- * they were minted, like the server's, and ordering by `id` is still ordering by creation.
12
- *
13
- * newEntityId() // "019a4c2e7f1074a8b13fa739ccbdcd53"
14
- */
15
- const COUNTER_MAX = 0xfff;
16
- let lastMillis = -1;
17
- let counter = 0;
18
- function randomBytes(count) {
19
- return globalThis.crypto.getRandomValues(new Uint8Array(count));
20
- }
21
- function hex(value, digits) {
22
- return value.toString(16).padStart(digits, "0");
23
- }
24
- export function newEntityId(now = Date.now()) {
25
- // The clock never runs backwards for these ids: the same millisecond (or an earlier one, a
26
- // clock moved back) counts up; a full counter borrows the next millisecond.
27
- let millis = now;
28
- if (millis <= lastMillis) {
29
- millis = lastMillis;
30
- counter += 1;
31
- if (counter > COUNTER_MAX) {
32
- millis += 1;
33
- counter = 0;
34
- }
35
- }
36
- else {
37
- // A fresh millisecond starts the counter at a random point of its lower half: room to count.
38
- const [high = 0, low = 0] = randomBytes(2);
39
- counter = ((high << 8) | low) & 0x7ff;
40
- }
41
- lastMillis = millis;
42
- const tail = randomBytes(8);
43
- tail[0] = ((tail[0] ?? 0) & 0x3f) | 0x80; // the variant, `10`
44
- return (hex(millis, 12) +
45
- "7" + // the version
46
- hex(counter, 3) +
47
- Array.from(tail, (byte) => hex(byte, 2)).join(""));
48
- }
49
- /** A key that is a UUID v7 as sincpro_framework writes it: 32 hex, version 7, variant `10`. */
50
- export function isEntityId(text) {
51
- return /^[0-9a-f]{12}7[0-9a-f]{3}[89ab][0-9a-f]{15}$/.test(text);
52
- }
@@ -1,43 +0,0 @@
1
- import type { AnyRecord, Criteria, Meta, Problem } from "@sincpro/criteria";
2
- import { type Draft, type Method, type Transport } from "./transport.js";
3
- /**
4
- * A server held in memory: tables of rows with their definition, answered with the same
5
- * engine sincpro_framework's criteria runs on.
6
- *
7
- * Context: not a test double. It is what a screen runs against before its server exists,
8
- * what Storybook and the tests run against, and what a domain with no server at all uses —
9
- * rows a screen already holds. It filters, orders, pages and counts
10
- * exactly as the server would (`answer` from `@sincpro/criteria/engine`), drops what the
11
- * model cannot answer and reports it, and refuses what the server would refuse. So the day a
12
- * real server answers, only the transport changes.
13
- *
14
- * A record is found at `<list route>/<id>`, by the field the model fetches by (`get_id`, else
15
- * the identity) — the convention sincpro_framework's REST routes follow.
16
- *
17
- * const transport = memoryTransport({
18
- * "/invoices": { meta: invoiceMeta, rows: invoices },
19
- * }, { latency: 300 });
20
- */
21
- export type MemoryTable = {
22
- meta: Meta;
23
- rows: readonly AnyRecord[];
24
- };
25
- export type MemoryOptions = {
26
- /** Milliseconds every answer waits, so a screen's «loading» can be seen and tested. */
27
- latency?: number;
28
- /**
29
- * Answer a Command — a write, an action, a preview — the way the service would. It may
30
- * change the tables' rows (they are read on every request) and throw a `TransportError` to
31
- * refuse. Without it, every Command is a 404.
32
- */
33
- handle?: (method: Method, route: string, body: unknown) => unknown;
34
- /** The draft this caller kept of a record, answered with it — sincpro_framework's `Drafts`. */
35
- draft?: (route: string) => Draft | null;
36
- /** Every list request, as it arrived: what a story or a test checks was really asked. */
37
- observe?: (route: string, criteria: Criteria) => void;
38
- /** Refuse a route the way a server would: return the problem it answers with. */
39
- refuse?: (route: string) => (Problem & {
40
- status?: number;
41
- }) | undefined;
42
- };
43
- export declare function memoryTransport(tables: Readonly<Record<string, MemoryTable>>, options?: MemoryOptions): Transport;
@@ -1,99 +0,0 @@
1
- import { answer, answerGroups } from "@sincpro/criteria/engine";
2
- import { TransportError, } from "./transport.js";
3
- function wait(ms, signal) {
4
- if (ms <= 0)
5
- return Promise.resolve();
6
- return new Promise((done, failed) => {
7
- const timer = setTimeout(done, ms);
8
- signal?.addEventListener("abort", () => {
9
- clearTimeout(timer);
10
- failed(signal.reason);
11
- });
12
- });
13
- }
14
- export function memoryTransport(tables, options = {}) {
15
- const answered = new Map();
16
- async function check(route, signal) {
17
- await wait(options.latency ?? 0, signal);
18
- const refused = options.refuse?.(route);
19
- if (refused !== undefined)
20
- throw new TransportError(route, refused.status ?? 400, refused);
21
- }
22
- function tableAt(route) {
23
- const path = route.split("?")[0] ?? route;
24
- const table = tables[path];
25
- if (table === undefined)
26
- throw new TransportError(route, 404, {
27
- kind: "not_found",
28
- reason: "ROUTE_NOT_FOUND",
29
- next_step: "fix_request",
30
- retryable: false,
31
- errors: [],
32
- extensions: {},
33
- detail: `No table answers ${path}.`,
34
- });
35
- return table;
36
- }
37
- return {
38
- async list(route, criteria, signal) {
39
- options.observe?.(route, criteria);
40
- await check(route, signal);
41
- const table = tableAt(route);
42
- // A grouped question is answered with the groups — counted over EVERY row that matches,
43
- // each with the criteria that opens it — the way the server's aggregation answers it.
44
- const grouped = (criteria.grouping?.group_by?.length ?? 0) > 0;
45
- const page = grouped
46
- ? answerGroups(table.rows, criteria, table.meta)
47
- : answer(table.rows, criteria, table.meta);
48
- // A copy, as over a wire: a screen holding a row must not see the server change it.
49
- return { ...page, rows: structuredClone(page.rows) };
50
- },
51
- async one(route, signal) {
52
- await check(route, signal);
53
- const slash = route.lastIndexOf("/");
54
- const table = tableAt(route.slice(0, slash));
55
- const id = decodeURIComponent(route.slice(slash + 1));
56
- const key = table.meta.get_id || table.meta.identity;
57
- const record = table.rows.find((row) => String(row[key]) === id);
58
- if (record === undefined)
59
- throw new TransportError(route, 404, {
60
- kind: "not_found",
61
- reason: "AGGREGATE_NOT_FOUND",
62
- next_step: "do_not_retry",
63
- retryable: false,
64
- errors: [],
65
- extensions: {},
66
- detail: `${table.meta.aggregate} ${id} does not exist.`,
67
- });
68
- return {
69
- record: structuredClone(record),
70
- meta: table.meta,
71
- dropped: [],
72
- draft: options.draft?.(route) ?? null,
73
- };
74
- },
75
- async send(method, route, body, signal, sending) {
76
- await check(route, signal);
77
- // A key already answered is answered again, without running the Command twice — what
78
- // sincpro_framework's `@idempotency` does with a repeated `Idempotency-Key`.
79
- const key = sending?.idempotencyKey;
80
- if (key !== undefined && answered.has(key))
81
- return structuredClone(answered.get(key));
82
- if (options.handle === undefined)
83
- throw new TransportError(route, 404, {
84
- kind: "not_found",
85
- reason: "ROUTE_NOT_FOUND",
86
- next_step: "fix_request",
87
- retryable: false,
88
- errors: [],
89
- extensions: {},
90
- detail: `Nothing answers ${method} ${route}.`,
91
- });
92
- // A deep copy: what the caller sent is not what the server keeps.
93
- const answer = await options.handle(method, route, structuredClone(body));
94
- if (key !== undefined)
95
- answered.set(key, structuredClone(answer));
96
- return answer;
97
- },
98
- };
99
- }
@@ -1,121 +0,0 @@
1
- import type { Expression, FieldMeta, FieldType, Meta, Operator } from "@sincpro/criteria";
2
- /**
3
- * A model definition written by hand, in the shape sincpro_framework publishes.
4
- *
5
- * Context: everything in this package reads a `Meta` — the labels, the columns, the controls,
6
- * the search box. A service built with sincpro_framework sends one with every answer. A domain
7
- * that has none (another backend, rows a screen already holds, a prototype
8
- * with no server yet) declares it here, and from then on it is indistinguishable: the same
9
- * list, the same record, the same criteria. `describeRows` from `@sincpro/criteria` guesses
10
- * one from rows; this one is written on purpose, with the words a person reads.
11
- *
12
- * const tickets = defineMeta({
13
- * aggregate: "Ticket", identity: "id", display: "title", search: ["title"],
14
- * name: { es: "Tickets" },
15
- * fields: {
16
- * id: field.text({ readonly: true }),
17
- * title: field.text({ label: { es: "Título" }, required: true }),
18
- * stage: field.choice(["new", "done"], { labels: { new: { es: "Nuevo" } } }),
19
- * opened_at: field.datetime({ label: { es: "Abierto" } }),
20
- * },
21
- * });
22
- */
23
- /** A word in several languages, `{default?, es?, en?, …}`; a bare string is the default. */
24
- export type Words = string | Readonly<Record<string, string>>;
25
- export type FieldOptions = {
26
- label?: Words;
27
- help?: Words;
28
- required?: boolean;
29
- readonly?: boolean;
30
- /** Holds no value sometimes. A nullable field is never sortable: keyset paging over it
31
- * loses the rows that hold NULL, which is why the framework refuses to order by one. */
32
- nullable?: boolean;
33
- default?: unknown;
34
- /** Form hints over the record, as sincpro_framework's `Presentation` publishes them. */
35
- readonlyWhen?: Expression;
36
- requiredWhen?: Expression;
37
- visibleWhen?: Expression;
38
- };
39
- /** The field builders: one per type the framework publishes. */
40
- export declare const field: {
41
- text: (options?: FieldOptions) => FieldMeta;
42
- integer: (options?: FieldOptions) => FieldMeta;
43
- /** A decimal travels as text so no digit is lost (`"10.50"`): pass `exact: true`. */
44
- number: (options?: FieldOptions & {
45
- exact?: boolean;
46
- }) => {
47
- exact?: boolean;
48
- type: FieldType;
49
- nullable: boolean;
50
- choices?: unknown[];
51
- choice_labels?: Record<string, Record<string, string>>;
52
- label?: Record<string, string>;
53
- help?: Record<string, string>;
54
- groupable?: boolean;
55
- aggregates?: string[];
56
- computed?: boolean;
57
- owner?: string | null;
58
- readonly?: boolean;
59
- required?: boolean;
60
- default?: unknown;
61
- readonly_when?: Expression | null;
62
- required_when?: Expression | null;
63
- visible_when?: Expression | null;
64
- sortable: boolean;
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;
73
- many?: boolean;
74
- relation?: string | null;
75
- identified_by?: string | null;
76
- parent_field?: string | null;
77
- related_field?: string | null;
78
- definition?: Meta | null;
79
- kind: import("@sincpro/criteria").FieldKind;
80
- };
81
- boolean: (options?: FieldOptions) => FieldMeta;
82
- date: (options?: FieldOptions) => FieldMeta;
83
- datetime: (options?: FieldOptions) => FieldMeta;
84
- tags: (options?: FieldOptions) => FieldMeta;
85
- /** An enum: the values in order, and the word each one is read as. */
86
- choice: (values: readonly string[], options?: FieldOptions & {
87
- labels?: Readonly<Record<string, Words>>;
88
- }) => FieldMeta;
89
- /** Points at ONE record of another aggregate, by the scalar key this record holds. */
90
- many2one: (relation: string, keys: {
91
- identifiedBy: string;
92
- definition?: Meta;
93
- }, options?: FieldOptions) => FieldMeta;
94
- /** The records of another aggregate that point back here, by THEIR key. */
95
- one2many: (relation: string, keys: {
96
- identifiedBy: string;
97
- definition?: Meta;
98
- }, options?: FieldOptions) => FieldMeta;
99
- many2many: (relation: string, keys: {
100
- identifiedBy: string;
101
- definition?: Meta;
102
- }, options?: FieldOptions) => FieldMeta;
103
- /** A value object kept inside the record — an address, a specification. No identity. */
104
- embedded: (definition: Meta, options?: FieldOptions & {
105
- many?: boolean;
106
- }) => FieldMeta;
107
- };
108
- export type MetaSpec = {
109
- aggregate: string;
110
- identity: string;
111
- fields: Record<string, FieldMeta>;
112
- name?: Words;
113
- /** The field shown beside the identity: what a select and a many2one show. */
114
- display?: string;
115
- /** `"-created_at"`, the way a URL writes it. Without it, the identity ascending. */
116
- defaultOrder?: string;
117
- /** The text fields a typed text is looked for in — the entity's search template. */
118
- search?: readonly string[];
119
- };
120
- /** A whole definition, from its fields. See the file header. */
121
- export declare function defineMeta(spec: MetaSpec): Meta;
package/dist/core/meta.js DELETED
@@ -1,130 +0,0 @@
1
- function hints(options) {
2
- return {
3
- ...(options.readonlyWhen ? { readonly_when: options.readonlyWhen } : {}),
4
- ...(options.requiredWhen ? { required_when: options.requiredWhen } : {}),
5
- ...(options.visibleWhen ? { visible_when: options.visibleWhen } : {}),
6
- };
7
- }
8
- /** The comparisons each type takes — the same table sincpro_framework publishes. */
9
- const OPS = {
10
- text: ["=", "!=", "like", "starts with", "in", "not in"],
11
- integer: ["=", "!=", ">", ">=", "<", "<=", "between", "in", "not in"],
12
- number: ["=", "!=", ">", ">=", "<", "<=", "between", "in", "not in"],
13
- date: ["=", "!=", ">", ">=", "<", "<=", "between"],
14
- datetime: ["=", "!=", ">", ">=", "<", "<=", "between"],
15
- boolean: ["="],
16
- "text[]": ["contains", "not contains", "=", "!="],
17
- };
18
- function words(value) {
19
- if (value === undefined)
20
- return undefined;
21
- return typeof value === "string" ? { default: value } : { ...value };
22
- }
23
- function scalar(type, options = {}) {
24
- const nullable = options.nullable ?? false;
25
- const ops = [...(OPS[type] ?? [])];
26
- if (nullable && type !== "text[]" && type !== "boolean")
27
- ops.push("is null");
28
- const listed = type === "text[]";
29
- return {
30
- type,
31
- kind: "scalar",
32
- nullable,
33
- sortable: !nullable && !listed,
34
- groupable: !listed,
35
- ops,
36
- ...(options.label === undefined ? {} : { label: words(options.label) }),
37
- ...(options.help === undefined ? {} : { help: words(options.help) }),
38
- ...(options.required === undefined ? {} : { required: options.required }),
39
- ...(options.readonly === undefined ? {} : { readonly: options.readonly }),
40
- ...(options.default === undefined ? {} : { default: options.default }),
41
- ...hints(options),
42
- };
43
- }
44
- function relational(type, relation, keys, options = {}) {
45
- return {
46
- type,
47
- kind: "relation",
48
- nullable: options.nullable ?? type === "many2one",
49
- sortable: false,
50
- ops: [],
51
- many: type !== "many2one",
52
- relation,
53
- identified_by: keys.identifiedBy,
54
- ...(keys.definition === undefined ? {} : { definition: keys.definition }),
55
- ...(options.label === undefined ? {} : { label: words(options.label) }),
56
- ...(options.help === undefined ? {} : { help: words(options.help) }),
57
- ...(options.readonly === undefined ? {} : { readonly: options.readonly }),
58
- };
59
- }
60
- /** The field builders: one per type the framework publishes. */
61
- export const field = {
62
- text: (options) => scalar("text", options),
63
- integer: (options) => scalar("integer", options),
64
- /** A decimal travels as text so no digit is lost (`"10.50"`): pass `exact: true`. */
65
- number: (options) => ({
66
- ...scalar("number", options),
67
- ...(options?.exact ? { exact: true } : {}),
68
- }),
69
- boolean: (options) => scalar("boolean", options),
70
- date: (options) => scalar("date", options),
71
- datetime: (options) => scalar("datetime", options),
72
- tags: (options) => scalar("text[]", options),
73
- /** An enum: the values in order, and the word each one is read as. */
74
- choice: (values, options = {}) => ({
75
- ...scalar("text", options),
76
- ops: ["=", "!=", "in", "not in", ...(options.nullable ? ["is null"] : [])],
77
- choices: [...values],
78
- ...(options.labels === undefined
79
- ? {}
80
- : {
81
- choice_labels: Object.fromEntries(Object.entries(options.labels).map(([value, said]) => [value, words(said) ?? {}])),
82
- }),
83
- }),
84
- /** Points at ONE record of another aggregate, by the scalar key this record holds. */
85
- many2one: (relation, keys, options) => relational("many2one", relation, keys, options),
86
- /** The records of another aggregate that point back here, by THEIR key. */
87
- one2many: (relation, keys, options) => relational("one2many", relation, keys, options),
88
- many2many: (relation, keys, options) => relational("many2many", relation, keys, options),
89
- /** A value object kept inside the record — an address, a specification. No identity. */
90
- embedded: (definition, options = {}) => ({
91
- type: "embedded",
92
- kind: "embedded",
93
- nullable: options.nullable ?? false,
94
- sortable: false,
95
- ops: [],
96
- definition,
97
- ...(options.many ? { many: true } : {}),
98
- ...(options.label === undefined ? {} : { label: words(options.label) }),
99
- }),
100
- };
101
- /** The template a typed text fills: `like` over each field, any of them matching. */
102
- function searchTemplate(fields) {
103
- if (fields.length === 0)
104
- return null;
105
- const like = (name) => ({
106
- field: name,
107
- operator: "like",
108
- value: { $: "param", name: "text" },
109
- });
110
- const [only] = fields;
111
- return {
112
- selection: fields.length === 1 && only !== undefined ? like(only) : { any: fields.map(like) },
113
- };
114
- }
115
- /** A whole definition, from its fields. See the file header. */
116
- export function defineMeta(spec) {
117
- const missing = [spec.identity, spec.display, ...(spec.search ?? [])].filter((name) => name !== undefined && name !== "" && !(name in spec.fields));
118
- if (missing.length > 0)
119
- throw new Error(`${spec.aggregate}: ${missing.join(", ")} named but not declared`);
120
- return {
121
- aggregate: spec.aggregate,
122
- identity: spec.identity,
123
- default_order: spec.defaultOrder ?? spec.identity,
124
- fields: spec.fields,
125
- get_id: spec.identity,
126
- ...(spec.name === undefined ? {} : { name: words(spec.name) }),
127
- ...(spec.display === undefined ? {} : { display: spec.display }),
128
- search: searchTemplate(spec.search ?? []),
129
- };
130
- }
@@ -1,17 +0,0 @@
1
- import type { Meta } from "@sincpro/criteria";
2
- /**
3
- * The model definitions already known, by entity key (`"billing:invoice"`).
4
- *
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.
9
- *
10
- * Seeded, it is the preload: definitions written at build time (a snapshot of the server's,
11
- * or `defineMeta`) reach the first screen with no request at all.
12
- */
13
- export type MetaStore = {
14
- get(key: string): Meta | undefined;
15
- set(key: string, meta: Meta): void;
16
- };
17
- export declare function metaStore(seed?: Readonly<Record<string, Meta>>): MetaStore;
@@ -1,7 +0,0 @@
1
- export function metaStore(seed = {}) {
2
- const known = new Map(Object.entries(seed));
3
- return {
4
- get: (key) => known.get(key),
5
- set: (key, meta) => void known.set(key, meta),
6
- };
7
- }
@@ -1,34 +0,0 @@
1
- import { type Criteria } from "@sincpro/criteria";
2
- import { type Transport } from "./transport.js";
3
- /**
4
- * The REST wire of sincpro_framework (`FastApiGateway`).
5
- *
6
- * Context: a list is criteria's `restSource` (0.3.1 sends the criteria as plain JSON and joins
7
- * a route that carries its own query, `/projects?tenant_id=acme` — the two things forge's
8
- * console found wrong in 0.3.0, fixed there). What this adds is what criteria does not know:
9
- * one record (`one()`), a write (`send()`, with its `Idempotency-Key`), and its refusals as a
10
- * `TransportError`, the one error every screen explains.
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
- *
17
- * const transport = restTransport({
18
- * base: "/v1",
19
- * headers: () => ({ Authorization: `Bearer ${session.secret}` }),
20
- * });
21
- */
22
- export type RestOptions = {
23
- /** Prepended to every route: `"/v1"`, `"https://forge.sincpro.com.bo/v1"`. */
24
- base?: string;
25
- /** Sent with every request. A function is called fresh each time — a token that rotates. */
26
- headers?: Record<string, string> | (() => Record<string, string>);
27
- /** Defaults to the global `fetch`. Inject one for tests. */
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
- export declare function urlOf<T>(base: string, route: string, criteria?: Criteria<T>): string;
34
- export declare function restTransport(options?: RestOptions): Transport;