@sincpro/client-framework 1.12.0 → 2.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.
package/README.md CHANGED
@@ -670,6 +670,7 @@ await forge.sendIssue({ issue_id: "acme-3", message: "hola" }); // ResponseSendI
670
670
  | `jsonRpcOperations({ endpoint })` | over JSON-RPC 2.0: one `POST`, the operation's method, its input as named params |
671
671
  | `restTransport({ base })` | REST over `fetch`: `Idempotency-Key`, the server's `Problem`, model versions, Parquet |
672
672
  | `memoryTransport(tables)` | the same REST contract in memory, copying by the wire's rules — for tests and demos |
673
+ | `assignableValues(route, values)` | an `Edit`'s values as the server reads them, for a memory `handle` |
673
674
  | `entity(key, routes)` | a model's routes and Commands, typed — what a generated `entities.ts` declares |
674
675
  | `retryKeys()` | one `Idempotency-Key` per gesture, kept while a retry may repeat it |
675
676
  | `guardedTransport(t, breaker)` | every call of a transport through a circuit breaker |
@@ -687,7 +688,7 @@ Its generated method mints one when the input names none (`newEntityId`, a UUID
687
688
  server would), so `forge.editProject({ values, action: "save" })` creates a project over any
688
689
  wire, REST's `PUT /projects/{id}/edit` included. A screen that keeps a draft of a new record
689
690
  names its key once, so every save of the draft reaches the same record. A Command that answers
690
- nothing — a `DELETE`'s 204 — resolves `null`, never `undefined`.
691
+ nothing — a `DELETE`'s 204 — resolves `null`, never `undefined`, over REST and in memory alike.
691
692
 
692
693
  A `DELETE` — the backend's `Delete`, role `delete`, an entity's `delete` route — is read from its
693
694
  URL, never from a body. `restTransport` sends its fields in the query string, as the server decodes
@@ -695,6 +696,13 @@ them (plain values as text, anything else as JSON): `DELETE /projects/acme?dry_r
695
696
  the `Preview` of what would go, and `origin_version` refuses a delete of a record that moved on.
696
697
  Sent in a body they are dropped, and a rehearsal would run the real delete.
697
698
 
699
+ A trash — the backend's `Archive`, `Restore` and `Purge`, roles `archive`, `restore` and `purge` —
700
+ is three more routes of an entity: `archive` and `restore` by the record's key, `purge` over the
701
+ whole collection (`older_than`, a duration as the contract writes it: `"P30D"`). Each answers
702
+ nothing — `null` — or, with `dry_run: true`, the `Preview` of what it would do; a purge's says how
703
+ many would go (`data: { count }`). The trash itself is the entity's list asked for what is
704
+ archived (`archived_at` not null), which every other reading leaves out.
705
+
698
706
  Which of the ways a screen reaches the backend fits a call — an entity's screens, the generated
699
707
  client over the screens transport, or a Command and its Feature — is in
700
708
  [docs/WEB.md](docs/WEB.md#which-way-a-screen-reaches-the-backend).
@@ -771,7 +779,7 @@ each file in the layer it belongs to, under the bounded context's folder (`--out
771
779
  | `domain/generated/events.ts` | the domain events and `DomainEvent`, their union — when the contract carries them |
772
780
  | `domain/generated/index.ts` | the three, re-exported: `import type * as remote from "../domain/generated"` |
773
781
  | `adapters/generated/client.ts` | `clientOf(operations)`: a method per operation, over any wire; `operations` and `events` data |
774
- | `adapters/generated/entities.ts` | each entity's list, record, edit, delete, export, Commands and history, for screens |
782
+ | `adapters/generated/entities.ts` | each entity's list, record, edit, delete, trash, export, Commands and history, for screens |
775
783
 
776
784
  The backend keeps them apart — the domain's words, the application layer's DTOs, the facts, the
777
785
  adapters to another system —, and so does the application: each beside its own code of that layer.
@@ -805,6 +813,17 @@ function subjectOf(event: remote.DomainEvent): string {
805
813
  `events` in `adapters/generated/client.ts` says, per event, its wire name and whether the bounded context records it
806
814
  (its aggregates' own) or handles it (a Feature subscribes).
807
815
 
816
+ The words of each event's fields are in the contract too (sincpro_framework 3.37.1 or later):
817
+ `eventMetasOf(contract)` reads the snapshot (`domain/generated/contract.json`) into one
818
+ definition per event, by its wire name, as `metasOf` does for the entities. What one occurrence
819
+ says — what happened, the record, who — travels in the event itself (`label`, `entity_display`,
820
+ `actor`).
821
+
822
+ ```ts
823
+ const metas = eventMetasOf(contract);
824
+ labelOf(metas["project.issue.v1.closed"], "reason", "es"); // "Motivo"
825
+ ```
826
+
808
827
  ### Types, not classes
809
828
 
810
829
  What is generated is the remote service's contract and an adapter over it, so it is written as
@@ -851,6 +870,7 @@ needs them.
851
870
  | Day | `"2026-10-02"`, never an instant | `isDay`, `dayOf` |
852
871
  | Instant | ISO text | `wallTimeOf`, `instantOf`, `timeZoneOf` |
853
872
  | ID | UUID v7 as 32 hex | `newEntityId`, `isEntityId`, `momentOf` |
873
+ | Entity ref | `"billing.Invoice:0192…"` | `EntityRef`, `parseEntityRef`, `entityRefOf` |
854
874
  | Bytes | `{ "$bytes": "<base64>" }` | `valuesOf`, `readValues` |
855
875
  | Collection | items, count and cursor | `collectionOf`, `isPartial`, `relatedCriteria` |
856
876
  | Export | Parquet, Arrow or JSON Lines | `downloadRoute`, `exportRoute` |
@@ -860,6 +880,15 @@ never a `Date`. `valuesOf`/`pack` write; `readValues` reads tagged values back;
860
880
  use a reader given explicitly. Cycles, functions and non-finite numbers are refused. How a value
861
881
  is shown, typed or stored is the platform's.
862
882
 
883
+ An entity ref — the backend's `EntityRef` — names a record of any bounded context by one text,
884
+ `bounded_context.Entity:key`: what a payment's metadata, a webhook or a notification carries to
885
+ say which record it is about. It is a text on the wire, so it is a text here, typed by its form:
886
+ the generator types a field published as `format: "entity-ref"` as `EntityRef`, `parseEntityRef`
887
+ reads one (refusing what the backend refuses), `isEntityRef` checks a string read from outside,
888
+ and `entityRefOf({ boundedContext, entity, key })` writes one. Resolving it is the backend's
889
+ `Resolve` — `GET …/refs?refs=[…]` — a generated operation of whichever bounded context publishes
890
+ it, never a route of this package.
891
+
863
892
  ## An application's layout
864
893
 
865
894
  An application is laid out as a sincpro_framework service is — the entrypoints call the bus, the
@@ -29,7 +29,9 @@ export type MemoryOptions = {
29
29
  /**
30
30
  * Answer a Command — a write, an action, a preview — the way the service would. It may
31
31
  * change the tables' rows (they are read on every request) and throw a `TransportError` to
32
- * refuse. Without it, every Command is a 404.
32
+ * refuse. Without it, every Command is a 404. What it returns is the answer; nothing — a
33
+ * Command that answers nothing — is `null`, as REST's 204. An `Edit`'s `values` are read as the
34
+ * server reads them with `assignableValues`.
33
35
  *
34
36
  * Its `body` is the Command's fields whatever the method — a `DELETE`'s too, which REST sends
35
37
  * in its query string (`restTransport`): this stands for the service, which reads a DTO, not a
@@ -52,3 +54,47 @@ export type MemoryOptions = {
52
54
  changes?: ChangeFeed;
53
55
  };
54
56
  export declare function memoryTransport(tables: Readonly<Record<string, MemoryTable>>, options?: MemoryOptions): Transport;
57
+ export type AssignableOptions = {
58
+ /** The key of the record the edit names — its `Edit`'s `id`: an identity in the values other
59
+ * than it is refused. */
60
+ id?: string;
61
+ /** The record's definition: a name it does not declare is refused, and its `identity` is the
62
+ * field checked against `id`. */
63
+ meta?: Meta;
64
+ /** What the framework writes on the record — left out at every level, a nested record keeping
65
+ * its `id`. By default `Entity`'s (`id`, `version`, `created_at`, `updated_at`) and its
66
+ * mixins' (`created_by`, `updated_by`, `archived_at`); a project's own framework base names
67
+ * its own. */
68
+ framework?: readonly string[];
69
+ };
70
+ /**
71
+ * The values of an `Edit` its record may be assigned, read as sincpro_framework 3.37 reads them
72
+ * (`assignable`, `form_values`, `apply_values`) — for a `memoryTransport`'s `handle` that stands
73
+ * for a service's `Edit`:
74
+ *
75
+ * handle(method, route, body) {
76
+ * const sent = body as { id: string; values?: AnyRecord; action?: string };
77
+ * const values = assignableValues(route, sent.values, { id: sent.id, meta: invoiceMeta });
78
+ * …
79
+ * }
80
+ *
81
+ * 1. The values are an object of fields (none is `{}`); anything else is refused.
82
+ * 2. An identity other than the record's (`id`) is refused: it would put one record's values on
83
+ * another.
84
+ * 3. What the framework writes is the record's echo — a form reads a record whole and sends it
85
+ * back whole —: left out, never assigned and never refused. In a record a list holds (a line),
86
+ * all of it but its `id`, the way a form names the line it edits.
87
+ * 4. A name the definition does not declare is refused.
88
+ * 5. A list of records goes whole: the collection a reading answered is read as its records, each
89
+ * as in 3; a page of it is refused (`heldValue`). A record held as one object (a many2one
90
+ * sent expanded) is passed as it came: which fields of it are the record's is the service's.
91
+ * Final: the values to assign. Each refusal is a `TransportError` 422 — `invalid`,
92
+ * `INVALID_VALUE` — pointing at the value (`#/values/lines/l1/parts`): a nested record by its
93
+ * `id`, by its position when it has none, as the server's `InvalidValue` points.
94
+ *
95
+ * Context: opt-in, and generic. A fake server that took whatever came hid that a form sent the
96
+ * record whole — the framework's echo, a relation read as a page — while the real `Edit` refused
97
+ * it: stories passed, and a stored record could not be edited against the real backend. A `handle`
98
+ * that does not call it reads `values` as it likes.
99
+ */
100
+ export declare function assignableValues(route: string, values: unknown, options?: AssignableOptions): AnyRecord;
@@ -105,8 +105,9 @@ export function memoryTransport(tables, options = {}) {
105
105
  extensions: {},
106
106
  detail: `Nothing answers ${method} ${route}.`,
107
107
  });
108
- // A deep copy: what the caller sent is not what the server keeps.
109
- const answer = await options.handle(method, route, copyOf(body));
108
+ // A deep copy: what the caller sent is not what the server keeps. A Command that
109
+ // answers nothing is `null`, as REST's 204 is — never `undefined`.
110
+ const answer = (await options.handle(method, route, copyOf(body))) ?? null;
110
111
  if (key !== undefined)
111
112
  answered.set(key, copyOf(answer));
112
113
  return answer;
@@ -123,3 +124,138 @@ export function memoryTransport(tables, options = {}) {
123
124
  }),
124
125
  });
125
126
  }
127
+ /**
128
+ * What sincpro_framework writes on a record — `Entity`'s fields and its mixins' (`AuditedMixin`'s
129
+ * `created_by` / `updated_by`, `ArchivableMixin`'s `archived_at`): in a form's values only as the
130
+ * record's echo. A record without a mixin never holds its fields, so a form never sends them.
131
+ */
132
+ const FRAMEWORK_FIELDS = [
133
+ "id",
134
+ "version",
135
+ "created_at",
136
+ "updated_at",
137
+ "created_by",
138
+ "updated_by",
139
+ "archived_at",
140
+ ];
141
+ /** A refusal of a value, as the server's `InvalidValue` answers it: a 422 pointing at it. */
142
+ function invalidValue(route, path, detail) {
143
+ const pointer = ["values", ...path]
144
+ .map((one) => String(one).replaceAll("~", "~0").replaceAll("/", "~1"))
145
+ .join("/");
146
+ return new TransportError(route, 422, {
147
+ kind: "invalid",
148
+ reason: "INVALID_VALUE",
149
+ status: 422,
150
+ detail,
151
+ next_step: "fix_request",
152
+ retryable: false,
153
+ errors: [{ pointer: `#/${pointer}`, detail }],
154
+ extensions: {},
155
+ });
156
+ }
157
+ function isFields(value) {
158
+ return value !== null && typeof value === "object" && !Array.isArray(value);
159
+ }
160
+ /** Each record of a list as a form sends it — its echo left out, its `id` kept —, named by its
161
+ * `id` where a refusal inside it points, by its position when it has none. */
162
+ function recordsOf(route, records, path, framework) {
163
+ return records.map((one, index) => {
164
+ if (!isFields(one))
165
+ return one;
166
+ const named = one["id"];
167
+ const at = named === undefined || named === null || named === "" ? index : String(named);
168
+ return formValues(route, one, [...path, at], framework, true);
169
+ });
170
+ }
171
+ /**
172
+ * A list of records as a form sends it — sincpro_framework's `_sent_whole`: the list, or the
173
+ * collection a reading answered (`{items, count, cursor}`) sent back whole, as its records. A page
174
+ * of it — a cursor, or a count that is only a floor — is refused: written back, it would remove
175
+ * every record it did not bring. An exact count above what it holds is a whole collection a form
176
+ * edited (a record removed), not a page — the server's rule, not `isPartial`'s.
177
+ */
178
+ function heldValue(route, value, path, framework) {
179
+ if (Array.isArray(value))
180
+ return recordsOf(route, value, path, framework);
181
+ if (!isFields(value) || !("items" in value))
182
+ return value;
183
+ const name = String(path[path.length - 1]);
184
+ const items = value["items"];
185
+ if (!Array.isArray(items))
186
+ throw invalidValue(route, path, `${name} holds records: send them as a list`);
187
+ const count = isFields(value["count"]) ? value["count"] : {};
188
+ const floor = count["exact"] === false;
189
+ if ((value["cursor"] !== undefined && value["cursor"] !== null) || floor) {
190
+ const total = typeof count["value"] === "number" ? count["value"] : items.length;
191
+ throw invalidValue(route, path, `${name} was sent as a page — ${items.length} of ${floor ? "at least " : ""}${total} — ` +
192
+ "and a page written back would remove every record it did not bring: send all of them");
193
+ }
194
+ return recordsOf(route, items, path, framework);
195
+ }
196
+ /** A record's values without what the framework writes — a nested one keeping its `id`. */
197
+ function formValues(route, values, path, framework, nested) {
198
+ const read = {};
199
+ for (const [name, value] of Object.entries(values)) {
200
+ if (framework.has(name) && !(nested && name === "id"))
201
+ continue;
202
+ read[name] = heldValue(route, value, [...path, name], framework);
203
+ }
204
+ return read;
205
+ }
206
+ /**
207
+ * The values of an `Edit` its record may be assigned, read as sincpro_framework 3.37 reads them
208
+ * (`assignable`, `form_values`, `apply_values`) — for a `memoryTransport`'s `handle` that stands
209
+ * for a service's `Edit`:
210
+ *
211
+ * handle(method, route, body) {
212
+ * const sent = body as { id: string; values?: AnyRecord; action?: string };
213
+ * const values = assignableValues(route, sent.values, { id: sent.id, meta: invoiceMeta });
214
+ * …
215
+ * }
216
+ *
217
+ * 1. The values are an object of fields (none is `{}`); anything else is refused.
218
+ * 2. An identity other than the record's (`id`) is refused: it would put one record's values on
219
+ * another.
220
+ * 3. What the framework writes is the record's echo — a form reads a record whole and sends it
221
+ * back whole —: left out, never assigned and never refused. In a record a list holds (a line),
222
+ * all of it but its `id`, the way a form names the line it edits.
223
+ * 4. A name the definition does not declare is refused.
224
+ * 5. A list of records goes whole: the collection a reading answered is read as its records, each
225
+ * as in 3; a page of it is refused (`heldValue`). A record held as one object (a many2one
226
+ * sent expanded) is passed as it came: which fields of it are the record's is the service's.
227
+ * Final: the values to assign. Each refusal is a `TransportError` 422 — `invalid`,
228
+ * `INVALID_VALUE` — pointing at the value (`#/values/lines/l1/parts`): a nested record by its
229
+ * `id`, by its position when it has none, as the server's `InvalidValue` points.
230
+ *
231
+ * Context: opt-in, and generic. A fake server that took whatever came hid that a form sent the
232
+ * record whole — the framework's echo, a relation read as a page — while the real `Edit` refused
233
+ * it: stories passed, and a stored record could not be edited against the real backend. A `handle`
234
+ * that does not call it reads `values` as it likes.
235
+ */
236
+ export function assignableValues(route, values, options = {}) {
237
+ if (values === undefined || values === null)
238
+ return {};
239
+ if (!isFields(values))
240
+ throw invalidValue(route, [], "values is the record's fields, as an object");
241
+ const { meta, id } = options;
242
+ const aggregate = meta?.aggregate ?? "The record";
243
+ const identity = meta?.identity ?? "id";
244
+ const echoed = values[identity];
245
+ // Only where the record is found by its identity: a key of its own is another field.
246
+ const byIdentity = meta === undefined || (meta.get_id || meta.identity) === identity;
247
+ if (id !== undefined &&
248
+ byIdentity &&
249
+ echoed !== undefined &&
250
+ echoed !== null &&
251
+ String(echoed) !== id)
252
+ throw invalidValue(route, [identity], `${aggregate} ${id} was sent the values of ${aggregate} ${String(echoed)}`);
253
+ const framework = new Set(options.framework ?? FRAMEWORK_FIELDS);
254
+ if (meta !== undefined) {
255
+ const unknown = Object.keys(values).filter((name) => !framework.has(name) && !(name in meta.fields));
256
+ const [first] = unknown;
257
+ if (first !== undefined)
258
+ throw invalidValue(route, [first], `${aggregate} has no field ${unknown.join(", ")} to assign`);
259
+ }
260
+ return formValues(route, values, [], framework, false);
261
+ }
@@ -1,8 +1,9 @@
1
1
  import { type Contract, type Meta } from "@sincpro/criteria";
2
2
  /**
3
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.
4
+ * `sincpro-client generate` writes (`contract.json`), or the document a service serves
5
+ * (`GET /client-contract/<context>.json`). Its models are read here, and its events when it
6
+ * carries them.
6
7
  *
7
8
  * Context: the generated entities are keyed `<domain>:<kind>` (`project:issue`) — the key the
8
9
  * workspace refers to them by and the meta store keeps their definitions under —, so the rule
@@ -12,6 +13,10 @@ import { type Contract, type Meta } from "@sincpro/criteria";
12
13
  export type ClientContract = {
13
14
  models: Readonly<Record<string, Contract>>;
14
15
  $defs?: Readonly<Record<string, Contract>>;
16
+ /** Its domain events by wire name, when it was exported with them (`--events`). */
17
+ events?: Readonly<Record<string, {
18
+ schema: Contract;
19
+ }>>;
15
20
  };
16
21
  /** `ProjectEvent` → `project_event`: the kind in an entity's key. */
17
22
  export declare function kindOf(model: string): string;
@@ -32,3 +37,14 @@ export declare function versionsOf(contract: ClientContract): Record<string, str
32
37
  * <FrameworkProvider transport={transport} metas={metasOf(contract, "project")}>
33
38
  */
34
39
  export declare function metasOf(contract: ClientContract, domain: string): Record<string, Meta>;
40
+ /**
41
+ * The definition of every domain event of `contract`, by its wire name: what each field it
42
+ * carries is called, for a history to draw it. Empty for a contract exported without its events.
43
+ *
44
+ * labelOf(eventMetasOf(contract)["desk.ticket.v1.closed"], "reason", "es") -> "Motivo"
45
+ *
46
+ * Context: what one occurrence says — what happened, the record, who — travels in the event
47
+ * itself (`label`, `entity_display`, `actor`), in the words of its day. The words of its fields
48
+ * are the contract's, as sincpro_framework publishes them since 3.37.1.
49
+ */
50
+ export declare function eventMetasOf(contract: ClientContract): Record<string, Meta>;
@@ -24,6 +24,10 @@ export function versionsOf(contract) {
24
24
  : [];
25
25
  }));
26
26
  }
27
+ /** What a definition points at by name (`#/models/Run`): a related model, a value it holds. */
28
+ function relatedOf(contract) {
29
+ return { ...(contract.$defs ?? {}), ...contract.models };
30
+ }
27
31
  /**
28
32
  * The definition of every model of `contract`, by its entity's key — what `FrameworkProvider
29
33
  * metas` preloads, so the first screen draws its labels with no request at all. The transport
@@ -32,10 +36,26 @@ export function versionsOf(contract) {
32
36
  * <FrameworkProvider transport={transport} metas={metasOf(contract, "project")}>
33
37
  */
34
38
  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 };
39
+ const related = relatedOf(contract);
37
40
  return Object.fromEntries(Object.entries(contract.models)
38
41
  // Only an entity has a key of its own; a value it holds is described inside it.
39
42
  .filter(([, model]) => model["x-sincpro"]?.identity != null)
40
43
  .map(([name, model]) => [entityKeyOf(domain, name), metaFromContract(model, related)]));
41
44
  }
45
+ /**
46
+ * The definition of every domain event of `contract`, by its wire name: what each field it
47
+ * carries is called, for a history to draw it. Empty for a contract exported without its events.
48
+ *
49
+ * labelOf(eventMetasOf(contract)["desk.ticket.v1.closed"], "reason", "es") -> "Motivo"
50
+ *
51
+ * Context: what one occurrence says — what happened, the record, who — travels in the event
52
+ * itself (`label`, `entity_display`, `actor`), in the words of its day. The words of its fields
53
+ * are the contract's, as sincpro_framework publishes them since 3.37.1.
54
+ */
55
+ export function eventMetasOf(contract) {
56
+ const related = relatedOf(contract);
57
+ return Object.fromEntries(Object.entries(contract.events ?? {}).map(([name, event]) => [
58
+ name,
59
+ metaFromContract(event.schema, related),
60
+ ]));
61
+ }
@@ -36,9 +36,10 @@ export type CommandAnswers = Readonly<Record<string, unknown>>;
36
36
  * Everything a screen needs to know about where an entity lives on the server, declared once.
37
37
  *
38
38
  * Context: a screen should not know a URL. It names the entity, and the entity says where its
39
- * list is, where one record is, which Commands it takes, how it is saved, previewed and deleted,
40
- * where a draft is kept and where its history is. `key` is how the workspace refers to it
41
- * (`domain:kind`, the shape of a composer `ResourceRef`).
39
+ * list is, where one record is, which Commands it takes, how it is saved, previewed and deleted
40
+ * — or put in a trash, brought back and purged —, where a draft is kept and where its history
41
+ * is. `key` is how the workspace refers to it (`domain:kind`, the shape of a composer
42
+ * `ResourceRef`).
42
43
  *
43
44
  * The routes are declared, not guessed: sincpro_framework publishes a route per use case and
44
45
  * its model definition does not list them (yet). A route is `"METHOD /path/{id}"` for a write.
@@ -49,6 +50,9 @@ export type CommandAnswers = Readonly<Record<string, unknown>>;
49
50
  * save: "PUT /invoices/{id}",
50
51
  * preview: "POST /invoices/preview",
51
52
  * delete: "DELETE /invoices/{id}",
53
+ * archive: "POST /invoices/{id}/archive",
54
+ * restore: "POST /invoices/{id}/restore",
55
+ * purge: "POST /invoices/purge",
52
56
  * commands: { confirm: "POST /invoices/{id}/confirm", cancel: "POST /invoices/{id}/cancel" },
53
57
  * history: "/invoices/{id}/events",
54
58
  * });
@@ -66,15 +70,21 @@ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = Co
66
70
  kind: string;
67
71
  /** Where the workspace finds it: the list without an id, one record with it — the shape of a
68
72
  * composer `ResourceRef`, built here so no screen writes `{ domain, kind, id }` by hand. */
69
- ref: (id?: string) => EntityRef;
73
+ ref: (id?: string) => ResourceRef;
70
74
  /** A record that does not exist yet — the form that creates one. Its view is the record's.
71
75
  * With `values`, the form starts with them over the model's defaults: an invoice created
72
76
  * from its customer starts with that customer (`startingValuesOf`). */
73
- newRef: (values?: AnyRecord) => EntityRef;
77
+ newRef: (values?: AnyRecord) => ResourceRef;
74
78
  /** Its list opened to CHOOSE one: a row answers whoever asked (composer's `api.pick`). With
75
79
  * `query`, the list opens on that literal search — what was typed in the picker; with
76
80
  * `scope`, it offers only what the picker may choose (`scopeOfRef`). */
77
- chooserRef: (query?: string, scope?: Expression) => EntityRef;
81
+ chooserRef: (query?: string, scope?: Expression) => ResourceRef;
82
+ /** Its list opened under a cut — «this member's payments», what a smart button opens. With
83
+ * `name`, the list says whose it is («Payments · María»): a cut that travels without one
84
+ * reads as the whole list. The cut travels as a chooser's does (`scopeOfRef`), the name
85
+ * under `SCOPE_NAME_PARAM` (`scopeNameOf`). A method, so an `Entity<Invoice>` is still an
86
+ * `Entity`. */
87
+ listRef(cut: Expression<T>, name?: string): ResourceRef;
78
88
  /** The route of its list. */
79
89
  list: string;
80
90
  /** The route of one record. */
@@ -99,6 +109,23 @@ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = Co
99
109
  * nothing, and `origin_version` refuses it when the record moved past the version read. Over
100
110
  * REST those fields travel in the query string — a `DELETE` is read from its URL. */
101
111
  delete?: WriteRoute;
112
+ /** sincpro_framework's `Archive`: the record put in the trash by its key, `{id}` in the path —
113
+ * left out of every reading, nothing lost. It answers nothing (`null`); with `dry_run: true`
114
+ * it answers the `Preview` of what would be archived and archives nothing, and
115
+ * `origin_version` refuses it when the record moved past the version read. The trash itself
116
+ * is the entity's list asked for what is archived (`archived_at` not null), which every other
117
+ * reading leaves out. */
118
+ archive?: WriteRoute;
119
+ /** sincpro_framework's `Restore`: an archived record brought back by its key, `{id}` in the
120
+ * path — into every reading again. It answers as `archive` does, `dry_run` and
121
+ * `origin_version` included. */
122
+ restore?: WriteRoute;
123
+ /** sincpro_framework's `Purge`: every record archived longer ago than `older_than` — a
124
+ * duration as the contract writes it (`"P30D"`) — deleted for good. The route of the whole
125
+ * collection, no `{id}`. It answers nothing; with `dry_run: true`, the `Preview` of how many
126
+ * would go (`data: { count }`), deleting nothing. The backend never purges on its own: a cron
127
+ * of the project runs it, or a screen's «empty the trash». */
128
+ purge?: WriteRoute;
102
129
  /** Its business events: where ONE record's events are read (sincpro_framework's
103
130
  * `DomainEvents`), `{id}` where its key goes — a page of them, as a list answers. */
104
131
  history?: string;
@@ -117,8 +144,15 @@ export type Entity<T extends AnyRecord = AnyRecord, C extends CommandBodies = Co
117
144
  /** Only carries what each Command answers; never read. */
118
145
  readonly _answers?: A;
119
146
  };
120
- /** A composer `ResourceRef`, structurally: `core/` does not import the composer. */
121
- export type EntityRef = {
147
+ /**
148
+ * Where the workspace opens an entity — its list, one record, a new one, a chooser —: a composer
149
+ * `ResourceRef`, structurally, since nothing here imports the composer.
150
+ *
151
+ * Context: named as composer names it. `EntityRef` is sincpro_framework's word for something
152
+ * else — a record of any bounded context written as one text (`billing.Invoice:01a1…`), what a
153
+ * payload carries —, and two types of one name cannot both be public.
154
+ */
155
+ export type ResourceRef = {
122
156
  domain: string;
123
157
  kind: string;
124
158
  id?: string;
@@ -138,16 +172,19 @@ export declare const TRAIL_PARAM = "from";
138
172
  /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
139
173
  * a number), where a param per field would turn all of them into text. */
140
174
  export declare const WITH_PARAM = "with";
141
- /** What a chooser may offer at all, as JSON: the picker's cut — its criteria, the keys it
142
- * excludes, its named list's scope — that the list it opens ANDs under everything. */
175
+ /** What a chooser may offer at all, or what a list opened under a cut shows (`listRef`), as
176
+ * JSON: the cut — its criteria, the keys it excludes, its named list's scope — that the list
177
+ * it opens ANDs under everything. */
143
178
  export declare const SCOPE_PARAM = "scope";
179
+ /** Whose a list opened under a cut is (`listRef(cut, name)`): «María» of «Payments · María». */
180
+ export declare const SCOPE_NAME_PARAM = "of";
144
181
  /**
145
182
  * What a new record's reference says it starts with (`newRef(values)`), or nothing.
146
183
  *
147
184
  * Context: a reference survives a reload and a link, so its params can be anything a person
148
185
  * typed in the address bar — a value that is not a JSON object is not a start, never an error.
149
186
  */
150
- export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRecord;
187
+ export declare function startingValuesOf(ref: Pick<ResourceRef, "params">): AnyRecord;
151
188
  /**
152
189
  * The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
153
190
  *
@@ -158,7 +195,16 @@ export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRec
158
195
  * (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
159
196
  * OFFERED; the server still decides what may be stored.
160
197
  */
161
- export declare function scopeOfRef(ref: Pick<EntityRef, "params">): Expression | undefined;
198
+ export declare function scopeOfRef(ref: Pick<ResourceRef, "params">): Expression | undefined;
199
+ /**
200
+ * Whose a list opened under a cut is (`listRef(cut, name)`), or nothing: what its heading, its
201
+ * tab and its breadcrumb say beside the list's name.
202
+ *
203
+ * Context: a cut that travels without a name reads as the whole list — «Payments» showing one
204
+ * member's. The name travels beside the cut, in the reference, so a reload and a link keep it;
205
+ * an empty one is none.
206
+ */
207
+ export declare function scopeNameOf(ref: Pick<ResourceRef, "params">): string | undefined;
162
208
  /**
163
209
  * A write: its method and its path, `{id}` where the record's key goes. A Command may also say
164
210
  * which field of its body names the record it runs on (`target`: `issue_id`), and then the
@@ -198,6 +244,12 @@ export type EntityRoutes<C extends CommandBodies = CommandBodies> = CommandRoute
198
244
  edit?: string;
199
245
  /** `"DELETE /invoices/{id}"`: the use case that answers sincpro_framework's `Delete`. */
200
246
  delete?: string;
247
+ /** `"POST /invoices/{id}/archive"`: the use case that answers sincpro_framework's `Archive`. */
248
+ archive?: string;
249
+ /** `"POST /invoices/{id}/restore"`: the use case that answers sincpro_framework's `Restore`. */
250
+ restore?: string;
251
+ /** `"POST /invoices/purge"`: the use case that answers sincpro_framework's `Purge`. */
252
+ purge?: string;
201
253
  /** `"/invoices/{id}/events"`: a record's events (`DomainEvents[Invoice, …]`), oldest first. */
202
254
  history?: string;
203
255
  /** `"/invoices/export"`: every record of a criteria as a file (`Export[Invoice, Streamed]`),
@@ -13,9 +13,12 @@ export const TRAIL_PARAM = "from";
13
13
  /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
14
14
  * a number), where a param per field would turn all of them into text. */
15
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. */
16
+ /** What a chooser may offer at all, or what a list opened under a cut shows (`listRef`), as
17
+ * JSON: the cut — its criteria, the keys it excludes, its named list's scope — that the list
18
+ * it opens ANDs under everything. */
18
19
  export const SCOPE_PARAM = "scope";
20
+ /** Whose a list opened under a cut is (`listRef(cut, name)`): «María» of «Payments · María». */
21
+ export const SCOPE_NAME_PARAM = "of";
19
22
  /**
20
23
  * What a new record's reference says it starts with (`newRef(values)`), or nothing.
21
24
  *
@@ -57,6 +60,18 @@ export function scopeOfRef(ref) {
57
60
  return undefined;
58
61
  }
59
62
  }
63
+ /**
64
+ * Whose a list opened under a cut is (`listRef(cut, name)`), or nothing: what its heading, its
65
+ * tab and its breadcrumb say beside the list's name.
66
+ *
67
+ * Context: a cut that travels without a name reads as the whole list — «Payments» showing one
68
+ * member's. The name travels beside the cut, in the reference, so a reload and a link keep it;
69
+ * an empty one is none.
70
+ */
71
+ export function scopeNameOf(ref) {
72
+ const name = ref.params?.[SCOPE_NAME_PARAM];
73
+ return name === undefined || name === "" ? undefined : name;
74
+ }
60
75
  const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
61
76
  /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
62
77
  export function writeRoute(text) {
@@ -182,6 +197,14 @@ export function entity(key, routes) {
182
197
  ...(scope === undefined ? {} : { [SCOPE_PARAM]: JSON.stringify(scope) }),
183
198
  },
184
199
  }),
200
+ listRef: (cut, name) => ({
201
+ domain,
202
+ kind,
203
+ params: {
204
+ [SCOPE_PARAM]: JSON.stringify(cut),
205
+ ...(name === undefined || name.trim() === "" ? {} : { [SCOPE_NAME_PARAM]: name }),
206
+ },
207
+ }),
185
208
  list: routes.list,
186
209
  one: (id) => template.replace("{id}", encodeURIComponent(id)),
187
210
  // Built from exactly the names `routes.commands` was typed with.
@@ -195,6 +218,9 @@ export function entity(key, routes) {
195
218
  ...(routes.draft === undefined ? {} : { draft: writeRoute(routes.draft) }),
196
219
  ...(routes.edit === undefined ? {} : { edit: writeRoute(routes.edit) }),
197
220
  ...(routes.delete === undefined ? {} : { delete: writeRoute(routes.delete) }),
221
+ ...(routes.archive === undefined ? {} : { archive: writeRoute(routes.archive) }),
222
+ ...(routes.restore === undefined ? {} : { restore: writeRoute(routes.restore) }),
223
+ ...(routes.purge === undefined ? {} : { purge: writeRoute(routes.purge) }),
198
224
  ...(routes.history === undefined ? {} : { history: routes.history }),
199
225
  ...(routes.export === undefined ? {} : { export: routes.export }),
200
226
  summary: routes.summary ?? {},
@@ -9,12 +9,12 @@
9
9
  * process's change feed (`processChanges`)
10
10
  */
11
11
  export { JsonRpcError, jsonRpcOperations, type JsonRpcOptions, } from "./adapters/json-rpc.js";
12
- export { type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
12
+ export { type AssignableOptions, assignableValues, type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
13
13
  export { type RestOptions, restTransport, urlOf, type VersionDrift, } from "./adapters/rest.js";
14
14
  export { restOperations } from "./adapters/rest-operations.js";
15
15
  export { type Change, type ChangeFeed, changeOf, } from "./domain/changes.js";
16
- export { type ClientContract, entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
17
- export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type EntityRef, type EntityRoutes, type ExportFormat, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, type SummaryFields, type SummaryPart, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./domain/entity.js";
16
+ export { type ClientContract, entityKeyOf, eventMetasOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
17
+ export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type EntityRoutes, type ExportFormat, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, type ResourceRef, SCOPE_NAME_PARAM, SCOPE_PARAM, scopeNameOf, scopeOfRef, startingValuesOf, type SummaryFields, type SummaryPart, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./domain/entity.js";
18
18
  export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
19
19
  export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, markedAs, type Method, type One, readRoute, SCREENS, type SendOptions, type Transport, TransportError, } from "./domain/transport.js";
20
20
  export { announced, changeFeed, processChanges, } from "./services/changes.js";
@@ -9,12 +9,12 @@
9
9
  * process's change feed (`processChanges`)
10
10
  */
11
11
  export { JsonRpcError, jsonRpcOperations, } from "./adapters/json-rpc.js";
12
- export { memoryTransport, } from "./adapters/memory.js";
12
+ export { assignableValues, memoryTransport, } from "./adapters/memory.js";
13
13
  export { restTransport, urlOf, } from "./adapters/rest.js";
14
14
  export { restOperations } from "./adapters/rest-operations.js";
15
15
  export { changeOf, } from "./domain/changes.js";
16
- export { entityKeyOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
17
- export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./domain/entity.js";
16
+ export { entityKeyOf, eventMetasOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
17
+ export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_NAME_PARAM, SCOPE_PARAM, scopeNameOf, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./domain/entity.js";
18
18
  export { OperationNotPublished, } from "./domain/operation.js";
19
19
  export { downloadRoute, markedAs, readRoute, SCREENS, TransportError, } from "./domain/transport.js";
20
20
  export { announced, changeFeed, processChanges, } from "./services/changes.js";
@@ -16,7 +16,8 @@ import { scaffoldFilesOf } from "../services/scaffold.js";
16
16
  * - `domain/generated/events.ts`: the domain events and `DomainEvent`, their union — when the
17
17
  * contract was exported with them (`export-client-contract --events`);
18
18
  * - `domain/generated/index.ts`: the three, re-exported;
19
- * - `domain/generated/contract.json`: the snapshot they were written from, for `metasOf`;
19
+ * - `domain/generated/contract.json`: the snapshot they were written from, for `metasOf` and
20
+ * `eventMetasOf`;
20
21
  * - `adapters/generated/client.ts`: every operation (and event) as data, and
21
22
  * `clientOf(operations)` over any wire;
22
23
  * - `adapters/generated/entities.ts`: an `entity<T, C>()` per model a screen can list.
@@ -30,7 +30,9 @@ import { aliasOf, answerOf, claimed, contextOf, deprecationOf, docOf, headerOf,
30
30
  * name is claimed once across the files: `index.ts` re-exports them side by side.
31
31
  *
32
32
  * criteria's grammar comes with every metamodel (`$defs.Criteria`); `@sincpro/criteria` already
33
- * types it, so it is imported, never written a second time.
33
+ * types it, so it is imported, never written a second time. So is a text whose `format` this
34
+ * package types: a ref to a record of any bounded context (`format: "entity-ref"`) is an
35
+ * `EntityRef`, never a bare `string`.
34
36
  *
35
37
  * domainFilesOf(JSON.parse(readFileSync("project.contract.json", "utf8")))
36
38
  * -> { "models.ts": "…", "commands.ts": "…", "index.ts": "…" }
@@ -43,6 +45,13 @@ const IMPORTED = {
43
45
  Download: { name: "Download", from: "@sincpro/client-framework" },
44
46
  EntityCollection: { name: "EntityCollection", from: "@sincpro/client-framework" },
45
47
  };
48
+ /** A text whose `format` a package of the stack already types — the backend's `EntityRef`,
49
+ * `bounded_context.Entity:key` —: the field is that type, imported. */
50
+ const FORMATS = {
51
+ "entity-ref": { name: "EntityRef", from: "@sincpro/client-framework" },
52
+ };
53
+ /** Everything a file may import from the stack, by the name it imports. */
54
+ const STACK = new Map([...Object.values(IMPORTED), ...Object.values(FORMATS)].map((one) => [one.name, one]));
46
55
  /** A relation that holds several records: a reading answers it as a page of them. */
47
56
  const TO_MANY = new Set(["one2many", "many2many"]);
48
57
  /** The field types whose value is the record itself, not a key that names it. */
@@ -170,8 +179,13 @@ function typeOf(schema, scope, depth, record) {
170
179
  if (types.length > 1)
171
180
  return union(types.map((one) => typeOf({ ...schema, type: one }, scope, depth, record)));
172
181
  switch (types[0]) {
173
- case "string":
174
- return "string";
182
+ case "string": {
183
+ const typed = schema.format === undefined ? undefined : FORMATS[schema.format];
184
+ if (typed === undefined)
185
+ return "string";
186
+ scope.imports.add(typed.name);
187
+ return typed.name;
188
+ }
175
189
  case "integer":
176
190
  case "number":
177
191
  return "number";
@@ -241,7 +255,7 @@ function definitionsOf(metamodel, scope, elsewhere) {
241
255
  function importsOf(scope, siblings) {
242
256
  const byPackage = new Map();
243
257
  for (const name of [...scope.imports].sort()) {
244
- const imported = IMPORTED[name];
258
+ const imported = STACK.get(name);
245
259
  byPackage.set(imported.from, [...(byPackage.get(imported.from) ?? []), imported.name]);
246
260
  }
247
261
  const packages = [...byPackage.keys()]
@@ -5,9 +5,10 @@ import { type GenerateOptions } from "./rest.js";
5
5
  *
6
6
  * 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
7
7
  * several) — none, and the model gets no entity, said in the file's own doc.
8
- * 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`;
9
- * its `events` — a record's `DomainEvents` — as `history`, the same way; and its `export` —
10
- * every record of a criteria as a file — by its path.
8
+ * 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`,
9
+ * and its trash's — `archive`, `restore` and `purge`, this one by its path —; its `events` — a
10
+ * record's `DomainEvents` — as `history`, the same way; and its `export` — every record of a
11
+ * criteria as a file — by its path.
11
12
  * 3. Every write of role `command` that concerns it: with `target` when its body names the
12
13
  * record, as it is when it creates one; its body typed without that field.
13
14
  * Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
@@ -78,8 +78,9 @@ function entitySourceOf(metamodel, model, domain, options, claim) {
78
78
  }
79
79
  else if (one !== undefined)
80
80
  missing.push(`one: ${one.missing}`);
81
- // sincpro_framework's `Delete` (role `delete`) is the record's own route too, never a Command.
82
- for (const role of ["edit", "preview", "delete"]) {
81
+ // sincpro_framework's `Delete` (role `delete`) is the record's own route too, never a Command;
82
+ // so are its trash's `Archive` and `Restore`, and `Purge`, the route of the whole collection.
83
+ for (const role of ["edit", "preview", "delete", "archive", "restore", "purge"]) {
83
84
  const write = oneOf(reads(role, isWrite), role);
84
85
  if (write === undefined)
85
86
  continue;
@@ -156,9 +157,10 @@ function entitySourceOf(metamodel, model, domain, options, claim) {
156
157
  *
157
158
  * 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
158
159
  * several) — none, and the model gets no entity, said in the file's own doc.
159
- * 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`;
160
- * its `events` — a record's `DomainEvents` — as `history`, the same way; and its `export` —
161
- * every record of a criteria as a file — by its path.
160
+ * 2. Its `get`, `edit`, `preview` and `delete` the same way, the record's field written `{id}`,
161
+ * and its trash's — `archive`, `restore` and `purge`, this one by its path —; its `events` — a
162
+ * record's `DomainEvents` — as `history`, the same way; and its `export` — every record of a
163
+ * criteria as a file — by its path.
162
164
  * 3. Every write of role `command` that concerns it: with `target` when its body names the
163
165
  * record, as it is when it creates one; its body typed without that field.
164
166
  * Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A record of any bounded context, named by one text — sincpro_framework's `EntityRef`:
3
+ * `billing.Invoice:01a1e6f2c0b37a4e9b1d2c3e4f5a6b7c`.
4
+ *
5
+ * parseEntityRef("billing.Invoice:F:7") -> { boundedContext: "billing", entity: "Invoice", key: "F:7" }
6
+ * entityRefOf({ boundedContext: "billing", entity: "Invoice", key: "F:7" }) -> "billing.Invoice:F:7"
7
+ * isEntityRef("Invoice:F:7") -> false: no bounded context
8
+ *
9
+ * Context: what travels in a payload that comes back later — a payment's metadata, a webhook, a
10
+ * notification — says which record it is about this way, and whoever receives it reads the
11
+ * record by its own `Get` (the backend's `Resolve`, an operation of whichever bounded context
12
+ * publishes it) without knowing its route. On the wire a ref is always its text, published as
13
+ * `{"type": "string", "format": "entity-ref"}`, so here it is a text too, typed by its form: the
14
+ * generator types a field of that format as `EntityRef`, a literal in the form type-checks, and
15
+ * any other string is read with `parseEntityRef` or checked with `isEntityRef` first. The bounded
16
+ * context and the entity are named as a `Reference` names a relation (`auth.Tenant`) — the
17
+ * entity by its class's name, never a workspace's `kind` —, and the key is the one its `Get`
18
+ * finds it by.
19
+ *
20
+ * The rule is the backend's `EntityRef.parse`: the key is everything after the FIRST `:` (a key
21
+ * may hold one), the entity what follows the LAST `.` before it (a bounded context may hold one),
22
+ * and none of the three empty. The entity is checked as the contract's `pattern` publishes it
23
+ * (`[A-Za-z_][A-Za-z0-9_]*`), so a ref the client accepts is one the published schema accepts.
24
+ */
25
+ export type EntityRef = `${string}.${string}:${string}`;
26
+ /** What a ref names: its bounded context, its entity — the class's name — and its key. */
27
+ export type EntityRefParts = {
28
+ readonly boundedContext: string;
29
+ readonly entity: string;
30
+ readonly key: string;
31
+ };
32
+ /**
33
+ * What a ref names — refused when `text` is not one, as the backend refuses it (a `422` on a DTO
34
+ * field).
35
+ *
36
+ * parseEntityRef("billing.Invoice:0192…") -> { boundedContext: "billing", entity: "Invoice", key: "0192…" }
37
+ * parseEntityRef("Invoice:0192…") -> throws: no bounded context
38
+ */
39
+ export declare function parseEntityRef(text: string): EntityRefParts;
40
+ /** Whether `value` is a text in a ref's form — what a string read from outside is checked with. */
41
+ export declare function isEntityRef(value: unknown): value is EntityRef;
42
+ /**
43
+ * The text of a ref — the backend's `str(ref)`: `<bounded context>.<Entity>:<key>`. Refused when
44
+ * the parts would not read back as themselves: a bounded context holding a `:`, an entity that is
45
+ * not a name, an empty part.
46
+ *
47
+ * entityRefOf({ boundedContext: "billing", entity: "Invoice", key: "0192…" }) -> "billing.Invoice:0192…"
48
+ */
49
+ export declare function entityRefOf(parts: EntityRefParts): EntityRef;
@@ -0,0 +1,55 @@
1
+ /** How a ref is written, as a refusal names it — the backend's `FORMAT`. */
2
+ const FORMAT = "bounded_context.Entity:key";
3
+ /** An entity's name, as the contract's `pattern` publishes it. */
4
+ const ENTITY = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
+ /** The parts `text` writes, or `undefined` when it is no ref. */
6
+ function partsOf(text) {
7
+ const colon = text.indexOf(":");
8
+ if (colon < 0)
9
+ return undefined;
10
+ const named = text.slice(0, colon);
11
+ const key = text.slice(colon + 1);
12
+ const dot = named.lastIndexOf(".");
13
+ if (dot < 0)
14
+ return undefined;
15
+ const boundedContext = named.slice(0, dot);
16
+ const entity = named.slice(dot + 1);
17
+ if (boundedContext === "" || !ENTITY.test(entity) || key === "")
18
+ return undefined;
19
+ return { boundedContext, entity, key };
20
+ }
21
+ /**
22
+ * What a ref names — refused when `text` is not one, as the backend refuses it (a `422` on a DTO
23
+ * field).
24
+ *
25
+ * parseEntityRef("billing.Invoice:0192…") -> { boundedContext: "billing", entity: "Invoice", key: "0192…" }
26
+ * parseEntityRef("Invoice:0192…") -> throws: no bounded context
27
+ */
28
+ export function parseEntityRef(text) {
29
+ const parts = partsOf(text);
30
+ if (parts === undefined)
31
+ throw new Error(`${JSON.stringify(text)} is no entity ref: write ${FORMAT}`);
32
+ return parts;
33
+ }
34
+ /** Whether `value` is a text in a ref's form — what a string read from outside is checked with. */
35
+ export function isEntityRef(value) {
36
+ return typeof value === "string" && partsOf(value) !== undefined;
37
+ }
38
+ /**
39
+ * The text of a ref — the backend's `str(ref)`: `<bounded context>.<Entity>:<key>`. Refused when
40
+ * the parts would not read back as themselves: a bounded context holding a `:`, an entity that is
41
+ * not a name, an empty part.
42
+ *
43
+ * entityRefOf({ boundedContext: "billing", entity: "Invoice", key: "0192…" }) -> "billing.Invoice:0192…"
44
+ */
45
+ export function entityRefOf(parts) {
46
+ const text = `${parts.boundedContext}.${parts.entity}:${parts.key}`;
47
+ const read = partsOf(text);
48
+ if (read === undefined ||
49
+ read.boundedContext !== parts.boundedContext ||
50
+ read.entity !== parts.entity ||
51
+ read.key !== parts.key)
52
+ throw new Error(`${JSON.stringify(parts)} writes no entity ref: ${FORMAT}, the bounded context without «:» ` +
53
+ "and the entity a name");
54
+ return text;
55
+ }
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * The values of the wire, as the backend writes them: ids, a day and an instant, `Decimal`,
3
- * `Money`, a to-many as a page of its records, and how any value is written and read.
3
+ * `Money`, a to-many as a page of its records, a ref to a record of any bounded context, and how
4
+ * any value is written and read.
4
5
  */
5
6
  export { collectionOf, type EntityCollection, type HeldCollection, isCollection, isPartial, relatedCriteria, type RelationKeys, totalOf, } from "./collection.js";
6
7
  export { Decimal, type DecimalLike } from "./decimal.js";
8
+ export { type EntityRef, entityRefOf, type EntityRefParts, isEntityRef, parseEntityRef, } from "./entity-ref.js";
7
9
  export { type DeclaredFailure, type Failure, failureOf, kindOfGrpcCode, kindOfHttpStatus, kindOfJsonRpcCode, PERMANENT_KINDS, } from "./failures.js";
8
10
  export { isEntityId, momentOf, newEntityId } from "./ids.js";
9
11
  export { Money } from "./money.js";
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * The values of the wire, as the backend writes them: ids, a day and an instant, `Decimal`,
3
- * `Money`, a to-many as a page of its records, and how any value is written and read.
3
+ * `Money`, a to-many as a page of its records, a ref to a record of any bounded context, and how
4
+ * any value is written and read.
4
5
  */
5
6
  export { collectionOf, isCollection, isPartial, relatedCriteria, totalOf, } from "./collection.js";
6
7
  export { Decimal } from "./decimal.js";
8
+ export { entityRefOf, isEntityRef, parseEntityRef, } from "./entity-ref.js";
7
9
  export { failureOf, kindOfGrpcCode, kindOfHttpStatus, kindOfJsonRpcCode, PERMANENT_KINDS, } from "./failures.js";
8
10
  export { isEntityId, momentOf, newEntityId } from "./ids.js";
9
11
  export { Money } from "./money.js";
@@ -35,6 +35,15 @@ export type FieldOptions = {
35
35
  readonlyWhen?: Expression;
36
36
  requiredWhen?: Expression;
37
37
  visibleWhen?: Expression;
38
+ /** How a form shows the field, when not the way its kind is shown: any name a client
39
+ * registers a component under (`"textarea"`) — what sincpro_framework's `presentation`
40
+ * publishes as the field's `widget`. A name, never a component: which component answers it
41
+ * is the platform's. */
42
+ widget?: string;
43
+ /** `false`: a grouping never splits by it — an identity, a trace id, each value its own
44
+ * group —, as sincpro_framework publishes a field declared `groupable: False` (3.37). It only
45
+ * turns grouping off: a list of tags is never grouped. */
46
+ groupable?: boolean;
38
47
  };
39
48
  /** The field builders: one per type the framework publishes. */
40
49
  export declare const field: {
@@ -1,3 +1,11 @@
1
+ /** What a scalar and a relation both say of themselves: their words and their widget. */
2
+ function common(options) {
3
+ return {
4
+ ...(options.label === undefined ? {} : { label: words(options.label) }),
5
+ ...(options.help === undefined ? {} : { help: words(options.help) }),
6
+ ...(options.widget === undefined ? {} : { widget: options.widget }),
7
+ };
8
+ }
1
9
  function hints(options) {
2
10
  return {
3
11
  ...(options.readonlyWhen ? { readonly_when: options.readonlyWhen } : {}),
@@ -31,10 +39,9 @@ function scalar(type, options = {}) {
31
39
  kind: "scalar",
32
40
  nullable,
33
41
  sortable: !listed,
34
- groupable: !listed,
42
+ groupable: !listed && options.groupable !== false,
35
43
  ops,
36
- ...(options.label === undefined ? {} : { label: words(options.label) }),
37
- ...(options.help === undefined ? {} : { help: words(options.help) }),
44
+ ...common(options),
38
45
  ...(options.required === undefined ? {} : { required: options.required }),
39
46
  ...(options.readonly === undefined ? {} : { readonly: options.readonly }),
40
47
  ...(options.default === undefined ? {} : { default: options.default }),
@@ -52,8 +59,7 @@ function relational(type, relation, keys, options = {}) {
52
59
  relation,
53
60
  identified_by: keys.identifiedBy,
54
61
  ...(keys.definition === undefined ? {} : { definition: keys.definition }),
55
- ...(options.label === undefined ? {} : { label: words(options.label) }),
56
- ...(options.help === undefined ? {} : { help: words(options.help) }),
62
+ ...common(options),
57
63
  ...(options.readonly === undefined ? {} : { readonly: options.readonly }),
58
64
  };
59
65
  }
@@ -96,6 +102,7 @@ export const field = {
96
102
  definition,
97
103
  ...(options.many ? { many: true } : {}),
98
104
  ...(options.label === undefined ? {} : { label: words(options.label) }),
105
+ ...(options.widget === undefined ? {} : { widget: options.widget }),
99
106
  }),
100
107
  };
101
108
  /** The template a typed text fills: `like` over each field, any of them matching. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "1.12.0",
3
+ "version": "2.1.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",