@zveltio/sdk 3.0.0-beta.110 → 3.0.0-beta.113

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.
@@ -0,0 +1,367 @@
1
+ /**
2
+ * `@zveltio/sdk/view` — the `zveltio.view/2` specification (ADR 0042).
3
+ *
4
+ * - `VIEW_SCHEMA`: the JSON Schema (also published as
5
+ * `@zveltio/sdk/view/schema.json`), the single source of the types below.
6
+ * - `validateView`: what `zveltio extension validate` and `pack` run; the
7
+ * engine checks the same schema when it loads an extension.
8
+ * - `viewNameIssues`: a view names only its extension's collections and
9
+ * actions, and a dependency's action.
10
+ * - `view`, `$`: a typed builder that emits the JSON.
11
+ * - `readActionResult`: an action's result, checked against `ActionResult`.
12
+ * - `resolveValue`, `toFilter`, `matches`, `defaultView`, ...: what every
13
+ * renderer does the same way (`runtime.ts`).
14
+ *
15
+ * Dependency-free: the validator interprets the subset of JSON Schema that
16
+ * `VIEW_SCHEMA` uses, so a front end can validate in the browser.
17
+ */
18
+ import { VIEW_SCHEMA, VIEW_SPEC } from './schema.js';
19
+ export { VIEW_SCHEMA, VIEW_SPEC } from './schema.js';
20
+ export * from './runtime.js';
21
+ /** A `view/2` file declares itself; anything else (a `view/1` schema) is not one. */
22
+ export function isViewDocument(input) {
23
+ return isObj(input) && input.spec === VIEW_SPEC;
24
+ }
25
+ export function validateView(input) {
26
+ if (!isViewDocument(input)) {
27
+ return { ok: false, issues: [{ path: '/spec', message: `must be "${VIEW_SPEC}"` }] };
28
+ }
29
+ const issues = [];
30
+ check(VIEW_SCHEMA, input, '', issues);
31
+ if (issues.length === 0)
32
+ crossChecks(input, '', issues);
33
+ return issues.length === 0 ? { ok: true, view: input } : { ok: false, issues };
34
+ }
35
+ const CONDITION_LISTS = new Set(['filter', 'when', 'emphasisWhen']);
36
+ /**
37
+ * What the schema cannot say, checked across keys:
38
+ * - the data API takes one value per field and operator (`{"f":{"gt":1,"lt":9}}`),
39
+ * so a condition list that gives the same pair twice cannot be sent whole: one
40
+ * of the two would be dropped and the list would answer wider than written;
41
+ * - a button's `prompt` never names an input its `input` already binds.
42
+ */
43
+ function crossChecks(v, path, out) {
44
+ if (Array.isArray(v)) {
45
+ v.forEach((x, i) => crossChecks(x, `${path}/${i}`, out));
46
+ return;
47
+ }
48
+ if (!isObj(v))
49
+ return;
50
+ // A button's `prompt` asks for what its `input` left open: never a bound key.
51
+ if (Array.isArray(v.prompt) && isObj(v.input)) {
52
+ v.prompt.forEach((name, i) => {
53
+ if (typeof name === 'string' && Object.hasOwn(v.input, name)) {
54
+ out.push({
55
+ path: `${path}/prompt/${i}`,
56
+ message: 'names an input the button already sets',
57
+ });
58
+ }
59
+ });
60
+ }
61
+ for (const [k, x] of Object.entries(v)) {
62
+ if (CONDITION_LISTS.has(k) && Array.isArray(x)) {
63
+ const seen = new Set();
64
+ x.forEach((c, i) => {
65
+ const key = isObj(c) ? `${String(c.field)}\0${String(c.op)}` : '';
66
+ if (seen.has(key)) {
67
+ out.push({ path: `${path}/${k}/${i}`, message: 'repeats a field and operator' });
68
+ }
69
+ seen.add(key);
70
+ });
71
+ }
72
+ crossChecks(x, `${path}/${k}`, out);
73
+ }
74
+ }
75
+ const ACTION_RESULT = { $ref: '#/$defs/ActionResult' };
76
+ export function readActionResult(result) {
77
+ const issues = [];
78
+ check(ACTION_RESULT, result, '', issues);
79
+ if (issues.length === 0 && isObj(result) && isObj(result.view)) {
80
+ crossChecks(result.view, '/view', issues);
81
+ }
82
+ if (issues.length > 0)
83
+ return { kind: 'invalid', issues };
84
+ const r = result;
85
+ if (isObj(r) && 'view' in r) {
86
+ return typeof r.view === 'string'
87
+ ? { kind: 'navigate', view: r.view, params: ('params' in r && r.params) || {} }
88
+ : { kind: 'view', view: r.view };
89
+ }
90
+ if (isObj(r) && 'file' in r && typeof r.file === 'string')
91
+ return { kind: 'file', file: r.file };
92
+ if (isObj(r) && 'reveal' in r && typeof r.reveal === 'string') {
93
+ return { kind: 'reveal', value: r.reveal };
94
+ }
95
+ return { kind: 'values', values: result };
96
+ }
97
+ /** Keys that name one field of the bound collection, by view kind (`*`: any). */
98
+ const ONE_FIELD = {
99
+ board: ['groupBy'],
100
+ timeline: ['start', 'end', 'groupBy'],
101
+ tree: ['parent', 'label', 'order'],
102
+ matrix: ['row', 'column', 'value'],
103
+ map: ['location', 'label'],
104
+ // `lines` of a form and a `stat` source carry no `type`.
105
+ '': ['fk', 'order', 'field'],
106
+ };
107
+ /** The field names an object bound to a collection uses, by path. */
108
+ function fieldRefs(v) {
109
+ const out = [];
110
+ const add = (at, x) => typeof x === 'string' && out.push([at, x]);
111
+ const fieldList = (x, at) => Array.isArray(x) &&
112
+ x.forEach((f, i) => (isObj(f) ? add(`${at}/${i}/field`, f.field) : add(`${at}/${i}`, f)));
113
+ const conditions = (x, at) => Array.isArray(x) && x.forEach((c, i) => isObj(c) && add(`${at}/${i}/field`, c.field));
114
+ for (const k of ONE_FIELD[typeof v.type === 'string' ? v.type : ''] ?? [])
115
+ add(`/${k}`, v[k]);
116
+ fieldList(v.fields, '/fields');
117
+ fieldList(v.card, '/card');
118
+ if (Array.isArray(v.sections)) {
119
+ v.sections.forEach((s, i) => isObj(s) && fieldList(s.fields, `/sections/${i}/fields`));
120
+ }
121
+ conditions(v.filter, '/filter');
122
+ conditions(v.emphasisWhen, '/emphasisWhen');
123
+ const sort = typeof v.sort === 'string' ? [v.sort] : v.sort;
124
+ if (Array.isArray(sort)) {
125
+ sort.forEach((x, i) => add(typeof v.sort === 'string' ? '/sort' : `/sort/${i}`, typeof x === 'string' ? x.replace(/^-/, '') : x));
126
+ }
127
+ return out;
128
+ }
129
+ /** Maps of values by name: their keys are the caller's, not references. */
130
+ const VALUE_MAPS = new Set(['input', 'params']);
131
+ const TEXT_SLOTS = new Set(['title', 'label', 'confirm']);
132
+ /** The same rule as `looksLikeMessageKey` in `@zveltio/sdk/validate`. */
133
+ const MESSAGE_KEY = /^[a-z][a-z0-9]*(\.[a-z0-9_]+)+$/i;
134
+ /**
135
+ * What the schema cannot see in a (valid) view: a collection or action its
136
+ * extension does not own, a `$selected` that names no earlier pane, a pane id
137
+ * used twice, a `navigate`/`open` to no view of the extension, a message key
138
+ * the extension does not ship, a field its collection does not have. (`fallback` is an inline view, not a reference.)
139
+ */
140
+ export function viewNameIssues(view, names) {
141
+ const collections = new Set(names.collections);
142
+ const actions = new Set(names.actions);
143
+ const deps = new Set(names.dependencies ?? []);
144
+ const views = names.views && new Set(names.views);
145
+ const keys = names.messageKeys && new Set(names.messageKeys);
146
+ const fields = names.fields && new Map([...names.fields].map(([c, f]) => [c, new Set(f)]));
147
+ const ids = new Set();
148
+ const out = [];
149
+ const issue = (path, message) => out.push({ path, message });
150
+ // `panes`: the pane ids a `$selected` here may name. `valuesOnly`: inside an
151
+ // input or params map, where only references are references.
152
+ const walk = (v, path, panes, valuesOnly) => {
153
+ if (Array.isArray(v)) {
154
+ v.forEach((x, i) => walk(x, `${path}/${i}`, panes, valuesOnly));
155
+ return;
156
+ }
157
+ if (!isObj(v))
158
+ return;
159
+ let scope = panes;
160
+ if (!valuesOnly && v.type === 'split' && Array.isArray(v.panes)) {
161
+ const earlier = new Set(panes);
162
+ v.panes.forEach((pane, i) => {
163
+ walk(pane, `${path}/panes/${i}`, new Set(earlier), false);
164
+ if (isObj(pane) && typeof pane.id === 'string')
165
+ earlier.add(pane.id);
166
+ });
167
+ scope = earlier;
168
+ }
169
+ const known = !valuesOnly && typeof v.collection === 'string' && fields?.get(v.collection);
170
+ if (known) {
171
+ for (const [at, f] of fieldRefs(v)) {
172
+ if (!known.has(f))
173
+ issue(`${path}${at}`, `field "${f}" is not a field of "${v.collection}"`);
174
+ }
175
+ }
176
+ for (const [k, x] of Object.entries(v)) {
177
+ const at = `${path}/${k}`;
178
+ if (k === '$selected') {
179
+ if (typeof x === 'string' && !panes.has(x)) {
180
+ issue(at, `"${x}" is not an earlier pane of an enclosing split`);
181
+ }
182
+ continue;
183
+ }
184
+ if (valuesOnly) {
185
+ walk(x, at, panes, true);
186
+ continue;
187
+ }
188
+ if (k === 'panes' && v.type === 'split')
189
+ continue;
190
+ if (k === 'tones')
191
+ continue;
192
+ if (VALUE_MAPS.has(k)) {
193
+ walk(x, at, scope, true);
194
+ }
195
+ else if (typeof x !== 'string') {
196
+ walk(x, at, scope, false);
197
+ }
198
+ else if (k === 'collection' && !collections.has(x)) {
199
+ issue(at, `collection "${x}" is not declared by this extension`);
200
+ }
201
+ else if (k === 'action') {
202
+ const dot = x.lastIndexOf('.');
203
+ if (dot < 0 ? !actions.has(x) : !deps.has(x.slice(0, dot))) {
204
+ issue(at, dot < 0
205
+ ? `action "${x}" is not declared by this extension`
206
+ : `action "${x}" names "${x.slice(0, dot)}", which is not a dependency`);
207
+ }
208
+ }
209
+ else if (k === 'id' && path !== '') {
210
+ if (ids.has(x))
211
+ issue(at, `pane id "${x}" is used twice`);
212
+ ids.add(x);
213
+ }
214
+ else if ((k === 'navigate' || k === 'open') && views && !views.has(x)) {
215
+ issue(at, `"${x}" is not the id of a view of this extension`);
216
+ }
217
+ else if (keys &&
218
+ TEXT_SLOTS.has(k) &&
219
+ !(k === 'label' && (v.type === 'map' || v.type === 'tree')) &&
220
+ !keys.has(x) &&
221
+ MESSAGE_KEY.test(x)) {
222
+ issue(at, `"${x}" is not a message key of this extension (studio/messages/en.json)`);
223
+ }
224
+ }
225
+ };
226
+ walk(view, '', new Set(), false);
227
+ return out;
228
+ }
229
+ /** Drops `undefined` keys (`sort: cond ? 'a' : undefined`) at every depth, as the file would. */
230
+ const clean = (v) => JSON.parse(JSON.stringify(v));
231
+ const kind = (type) => (props) => clean({ type, ...props });
232
+ /**
233
+ * Typed constructors: `view.list({ collection: 'invoices', fields: ['number'] })`.
234
+ * `view.document(v)` stamps `spec` on the top-level view; `JSON.stringify` it
235
+ * into the file the manifest names.
236
+ */
237
+ export const view = {
238
+ list: kind('list'),
239
+ form: kind('form'),
240
+ detail: kind('detail'),
241
+ board: kind('board'),
242
+ timeline: kind('timeline'),
243
+ tree: kind('tree'),
244
+ matrix: kind('matrix'),
245
+ map: kind('map'),
246
+ stat: kind('stat'),
247
+ split: kind('split'),
248
+ tabs: kind('tabs'),
249
+ document: (v, id) => clean({ ...v, spec: VIEW_SPEC, id }),
250
+ };
251
+ /** References and conditions: `$.record('id')`, `$.where('status', 'eq', 'open')`. */
252
+ export const $ = {
253
+ record: (field) => ({ $record: field }),
254
+ selected: (pane) => ({ $selected: pane }),
255
+ selection: (field) => ({ $selection: field }),
256
+ param: (name) => ({ $param: name }),
257
+ user: () => ({ $user: 'id' }),
258
+ today: () => ({ $today: true }),
259
+ where: (field, op, value) => (value === undefined ? { field, op } : { field, op, value }),
260
+ };
261
+ function isObj(v) {
262
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
263
+ }
264
+ function resolve(s) {
265
+ let cur = s;
266
+ while (typeof cur.$ref === 'string') {
267
+ const name = cur.$ref.replace('#/$defs/', '');
268
+ cur = VIEW_SCHEMA.$defs[name];
269
+ }
270
+ return cur;
271
+ }
272
+ function typeOf(v) {
273
+ if (v === null)
274
+ return 'null';
275
+ if (Array.isArray(v))
276
+ return 'array';
277
+ if (typeof v === 'number' && Number.isInteger(v))
278
+ return 'integer';
279
+ return typeof v;
280
+ }
281
+ const show = (v) => JSON.stringify(v);
282
+ /** The values a schema (or a union of them) accepts for `key`: a view's `type`, a condition's `op`. */
283
+ function accepts(schema, key) {
284
+ const s = resolve(schema);
285
+ if (Array.isArray(s.anyOf))
286
+ return s.anyOf.flatMap((b) => accepts(b, key));
287
+ const p = s.properties?.[key];
288
+ return p ? (Array.isArray(p.enum) ? p.enum : [p.const]) : [];
289
+ }
290
+ function check(schema, v, path, out) {
291
+ const s = resolve(schema);
292
+ const at = (message) => out.push({ path, message });
293
+ if (isObj(s.not)) {
294
+ const inner = [];
295
+ check(s.not, v, path, inner);
296
+ if (inner.length === 0)
297
+ return void at('is not allowed here');
298
+ }
299
+ if ('const' in s && v !== s.const)
300
+ return void at(`must be ${show(s.const)}`);
301
+ if (Array.isArray(s.enum) && !s.enum.includes(v)) {
302
+ return void at(`must be one of ${s.enum.map(show).join(', ')}`);
303
+ }
304
+ if (s.type !== undefined) {
305
+ const want = Array.isArray(s.type) ? s.type : [s.type];
306
+ const t = typeOf(v);
307
+ if (!want.includes(t) && !(t === 'integer' && want.includes('number'))) {
308
+ return void at(`must be ${want.join(' or ')}`);
309
+ }
310
+ }
311
+ const branches = s.anyOf;
312
+ if (branches) {
313
+ const results = branches.map((b) => {
314
+ const errs = [];
315
+ check(b, v, path, errs);
316
+ return errs;
317
+ });
318
+ if (results.some((r) => r.length === 0))
319
+ return;
320
+ // Report the closest form: among those whose `type` or `op` matches if any, the
321
+ // one whose shape the value has (its issues sit deeper), else the fewest.
322
+ const named = results.filter((_, i) => isObj(v) &&
323
+ ['type', 'op'].some((k) => typeof v[k] === 'string' && accepts(branches[i], k).includes(v[k])));
324
+ const score = (r) => r.filter((i) => i.path === path).length * 1000 + r.length;
325
+ out.push(...(named.length > 0 ? named : results).reduce((a, b) => (score(b) < score(a) ? b : a)));
326
+ return;
327
+ }
328
+ if (typeof v === 'string') {
329
+ if (typeof s.pattern === 'string' && !new RegExp(s.pattern).test(v)) {
330
+ at(`${show(v)} must match ${s.pattern}`);
331
+ }
332
+ if (typeof s.minLength === 'number' && v.length < s.minLength)
333
+ at('must not be empty');
334
+ if (typeof s.maxLength === 'number' && v.length > s.maxLength) {
335
+ at(`must be at most ${s.maxLength} characters`);
336
+ }
337
+ }
338
+ if (typeof v === 'number') {
339
+ if (typeof s.minimum === 'number' && v < s.minimum)
340
+ at(`must be at least ${s.minimum}`);
341
+ if (typeof s.maximum === 'number' && v > s.maximum)
342
+ at(`must be at most ${s.maximum}`);
343
+ }
344
+ if (Array.isArray(v)) {
345
+ if (typeof s.minItems === 'number' && v.length < s.minItems) {
346
+ at(`must have at least ${s.minItems} item(s)`);
347
+ }
348
+ if (isObj(s.items))
349
+ v.forEach((x, i) => check(s.items, x, `${path}/${i}`, out));
350
+ }
351
+ if (isObj(v)) {
352
+ const props = (s.properties ?? {});
353
+ for (const r of (s.required ?? [])) {
354
+ if (!Object.hasOwn(v, r))
355
+ at(`needs "${r}"`);
356
+ }
357
+ for (const [k, x] of Object.entries(v)) {
358
+ const p = `${path}/${k}`;
359
+ if (Object.hasOwn(props, k))
360
+ check(props[k], x, p, out);
361
+ else if (s.additionalProperties === false)
362
+ out.push({ path: p, message: 'is not part of view/2' });
363
+ else if (isObj(s.additionalProperties))
364
+ check(s.additionalProperties, x, p, out);
365
+ }
366
+ }
367
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * What every `view/2` renderer does the same way, in plain TypeScript, so a
3
+ * Svelte, React or Vue front end draws a view and only draws it (ADR 0042
4
+ * decision 8): fill in references, turn conditions into a data API filter,
5
+ * check a `when`, generate the default list, form and detail of a collection,
6
+ * and read an action's result.
7
+ *
8
+ * Nothing here evaluates an expression or reaches a URL a view carries: a view
9
+ * carries none. The data API and action paths below are the engine's, named by
10
+ * the front end; the engine's rules decide every call.
11
+ */
12
+ import type { Conditions, Field, Fields, Input, Sort, Value, View } from './types.generated.js';
13
+ /** What references read. Anything missing leaves the reference unresolved. */
14
+ export interface ViewScope {
15
+ /** The current record (`$record`). */
16
+ record?: Record<string, unknown>;
17
+ /** Pane id → the id of the record selected in it (`$selected`). */
18
+ selected?: Record<string, unknown>;
19
+ /** The selected rows of a list (`$selection`). */
20
+ selection?: Record<string, unknown>[];
21
+ /** The parameters the view was opened with (`$param`). */
22
+ params?: Record<string, unknown>;
23
+ /** The signed-in user's id (`$user`). */
24
+ user?: string;
25
+ /** `YYYY-MM-DD` (`$today`); defaults to the local date. */
26
+ today?: string;
27
+ }
28
+ /** A value with its references filled in; `undefined` when one cannot be. */
29
+ export declare function resolveValue(v: Value, s: ViewScope): unknown;
30
+ /** An action's input or a view's parameters, resolved; `null` when a reference is not. */
31
+ export declare function resolveInput(input: Input | undefined, s: ViewScope): Record<string, unknown> | null;
32
+ /**
33
+ * Conditions as the data API's JSON `filter` (`{"field":{"op":value}}`); `null`
34
+ * while a reference has no value yet (no row selected in the pane it names).
35
+ */
36
+ export declare function toFilter(conds: Conditions | undefined, s: ViewScope): Record<string, Record<string, unknown>> | null;
37
+ /** Whether a row meets every condition (`when`, `emphasisWhen`). No conditions: true. */
38
+ export declare function matches(conds: Conditions | undefined, row: Record<string, unknown>, s: ViewScope): boolean;
39
+ /** The data API's `sort` and `order` for a view's `sort` (its first field). */
40
+ export declare function toSort(sort: Sort | undefined): {
41
+ sort: string;
42
+ order: 'asc' | 'desc';
43
+ } | null;
44
+ export declare const fieldName: (f: Field) => string;
45
+ /** A field as the data API describes it (`GET /api/data`, `GET /api/collections/:name`). */
46
+ export interface SchemaField {
47
+ name: string;
48
+ type: string;
49
+ is_system?: boolean;
50
+ [key: string]: unknown;
51
+ }
52
+ /** Whether a form may write the field: not a system, computed or read-only one. */
53
+ export declare function isEditable(f: SchemaField): boolean;
54
+ /**
55
+ * The fields a generated view shows: no system or computed field; a list
56
+ * stops at eight columns so a wide collection stays readable.
57
+ */
58
+ export declare function defaultFields<F extends SchemaField>(fields: readonly F[], kind: 'list' | 'form' | 'detail'): F[];
59
+ /** The generated default of a collection: a view writes only what differs from it. */
60
+ export declare function defaultView(kind: 'list' | 'form' | 'detail', collection: string, fields: readonly SchemaField[]): View;
61
+ /** A view's fields, or the collection's default ones when it names none. */
62
+ export declare function viewFields(fields: Fields | undefined, schema: readonly SchemaField[], kind: 'list' | 'form' | 'detail'): Fields;
63
+ /**
64
+ * What a front end that does not draw `view.type` draws instead: the view's own
65
+ * `fallback`, else the generated list of its collection (ADR 0042 decision 6).
66
+ * `null` when there is neither (a container it does not know).
67
+ */
68
+ export declare function fallbackFor(view: View, drawn: ReadonlySet<string>): View | null;
69
+ /** The engine path that runs an action: its own extension's, or `<dependency>.<action>`. */
70
+ export declare function actionPath(extension: string, action: string): string;
71
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
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C5F,wBAAgB,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAQpE"}
@@ -0,0 +1,185 @@
1
+ /**
2
+ * What every `view/2` renderer does the same way, in plain TypeScript, so a
3
+ * Svelte, React or Vue front end draws a view and only draws it (ADR 0042
4
+ * decision 8): fill in references, turn conditions into a data API filter,
5
+ * check a `when`, generate the default list, form and detail of a collection,
6
+ * and read an action's result.
7
+ *
8
+ * Nothing here evaluates an expression or reaches a URL a view carries: a view
9
+ * carries none. The data API and action paths below are the engine's, named by
10
+ * the front end; the engine's rules decide every call.
11
+ */
12
+ const isRef = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v)[0]?.startsWith('$');
13
+ function localToday() {
14
+ const d = new Date();
15
+ const p = (n) => String(n).padStart(2, '0');
16
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
17
+ }
18
+ /** A value with its references filled in; `undefined` when one cannot be. */
19
+ export function resolveValue(v, s) {
20
+ if (Array.isArray(v)) {
21
+ const out = v.map((x) => resolveValue(x, s));
22
+ return out.some((x) => x === undefined) ? undefined : out;
23
+ }
24
+ if (!isRef(v))
25
+ return v;
26
+ if ('$record' in v)
27
+ return s.record?.[v.$record];
28
+ if ('$selected' in v)
29
+ return s.selected?.[v.$selected];
30
+ if ('$selection' in v)
31
+ return s.selection?.map((r) => r[v.$selection]);
32
+ if ('$param' in v)
33
+ return s.params?.[v.$param];
34
+ if ('$user' in v)
35
+ return s.user;
36
+ return s.today ?? localToday();
37
+ }
38
+ /** An action's input or a view's parameters, resolved; `null` when a reference is not. */
39
+ export function resolveInput(input, s) {
40
+ const out = {};
41
+ for (const [k, v] of Object.entries(input ?? {})) {
42
+ const r = resolveValue(v, s);
43
+ if (r === undefined)
44
+ return null;
45
+ out[k] = r;
46
+ }
47
+ return out;
48
+ }
49
+ /**
50
+ * Conditions as the data API's JSON `filter` (`{"field":{"op":value}}`); `null`
51
+ * while a reference has no value yet (no row selected in the pane it names).
52
+ */
53
+ export function toFilter(conds, s) {
54
+ const out = {};
55
+ for (const c of conds ?? []) {
56
+ let value = true;
57
+ if ('value' in c) {
58
+ value = resolveValue(c.value, s);
59
+ if (value === undefined)
60
+ return null;
61
+ }
62
+ // The data API takes one value per field and operator; `validateView` refuses the pair twice.
63
+ if (out[c.field] && c.op in out[c.field]) {
64
+ throw new Error(`view/2: "${c.field}" ${c.op} is given twice in one condition list`);
65
+ }
66
+ out[c.field] = { ...out[c.field], [c.op]: value };
67
+ }
68
+ return out;
69
+ }
70
+ const cmp = (a, b) => typeof a === 'number' && typeof b === 'number'
71
+ ? a - b
72
+ : String(a ?? '').localeCompare(String(b ?? ''));
73
+ function holds(c, row, s) {
74
+ const have = row[c.field];
75
+ if (!('value' in c))
76
+ return c.op === 'null' ? have == null : have != null;
77
+ const want = resolveValue(c.value, s);
78
+ if (want === undefined)
79
+ return false;
80
+ const text = String(have ?? '').toLowerCase();
81
+ const w = String(want).toLowerCase();
82
+ switch (c.op) {
83
+ case 'eq':
84
+ return have === want || String(have) === String(want);
85
+ case 'neq':
86
+ return !(have === want || String(have) === String(want));
87
+ case 'in':
88
+ case 'not_in': {
89
+ const list = (Array.isArray(want) ? want : [want]).map(String);
90
+ return list.includes(String(have)) === (c.op === 'in');
91
+ }
92
+ case 'lt':
93
+ return cmp(have, want) < 0;
94
+ case 'lte':
95
+ return cmp(have, want) <= 0;
96
+ case 'gt':
97
+ return cmp(have, want) > 0;
98
+ case 'gte':
99
+ return cmp(have, want) >= 0;
100
+ case 'like':
101
+ case 'ilike':
102
+ return text.includes(w);
103
+ case 'not_contains':
104
+ return !text.includes(w);
105
+ case 'starts_with':
106
+ return text.startsWith(w);
107
+ case 'ends_with':
108
+ return text.endsWith(w);
109
+ default:
110
+ // `near`, `within`: the engine answers them; a row on screen cannot.
111
+ return false;
112
+ }
113
+ }
114
+ /** Whether a row meets every condition (`when`, `emphasisWhen`). No conditions: true. */
115
+ export function matches(conds, row, s) {
116
+ return (conds ?? []).every((c) => holds(c, row, s));
117
+ }
118
+ /** The data API's `sort` and `order` for a view's `sort` (its first field). */
119
+ export function toSort(sort) {
120
+ const first = Array.isArray(sort) ? sort[0] : sort;
121
+ if (!first)
122
+ return null;
123
+ return first.startsWith('-')
124
+ ? { sort: first.slice(1), order: 'desc' }
125
+ : { sort: first, order: 'asc' };
126
+ }
127
+ export const fieldName = (f) => (typeof f === 'string' ? f : f.field);
128
+ /** Field types a generated form does not offer: the engine computes them. */
129
+ const NOT_EDITABLE = new Set(['computed']);
130
+ /** Whether a form may write the field: not a system, computed or read-only one. */
131
+ export function isEditable(f) {
132
+ return !f.is_system && !NOT_EDITABLE.has(f.type) && f.readonly !== true;
133
+ }
134
+ /**
135
+ * The fields a generated view shows: no system or computed field; a list
136
+ * stops at eight columns so a wide collection stays readable.
137
+ */
138
+ export function defaultFields(fields, kind) {
139
+ const own = fields.filter((f) => !f.is_system && !NOT_EDITABLE.has(f.type));
140
+ if (kind === 'list')
141
+ return own.slice(0, 8);
142
+ if (kind === 'form')
143
+ return own.filter(isEditable);
144
+ return own;
145
+ }
146
+ /** The generated default of a collection: a view writes only what differs from it. */
147
+ export function defaultView(kind, collection, fields) {
148
+ const names = defaultFields(fields, kind).map((f) => f.name);
149
+ if (kind === 'list')
150
+ return { type: 'list', collection, fields: names, search: true };
151
+ if (kind === 'form')
152
+ return { type: 'form', collection, fields: names };
153
+ return { type: 'detail', collection, record: { $param: 'id' }, fields: names };
154
+ }
155
+ /** A view's fields, or the collection's default ones when it names none. */
156
+ export function viewFields(fields, schema, kind) {
157
+ return fields?.length ? fields : defaultFields(schema, kind).map((f) => f.name);
158
+ }
159
+ /**
160
+ * What a front end that does not draw `view.type` draws instead: the view's own
161
+ * `fallback`, else the generated list of its collection (ADR 0042 decision 6).
162
+ * `null` when there is neither (a container it does not know).
163
+ */
164
+ export function fallbackFor(view, drawn) {
165
+ let v = view;
166
+ while (v && !drawn.has(v.type))
167
+ v = v.fallback;
168
+ if (v)
169
+ return v;
170
+ return 'collection' in view ? { type: 'list', collection: view.collection } : null;
171
+ }
172
+ /** The engine path that runs an action: its own extension's, or `<dependency>.<action>`. */
173
+ export function actionPath(extension, action) {
174
+ const dot = action.indexOf('.');
175
+ const [ext, name] = dot < 0 ? [extension, action] : [action.slice(0, dot), action.slice(dot + 1)];
176
+ // The manifest's rules (`ActionName`): no `.`/`..` segment, nothing to encode.
177
+ if (!EXTENSION_NAME.test(ext) || !ACTION.test(name)) {
178
+ throw new Error(`view/2: "${action}" is not an action of "${extension}" or a dependency`);
179
+ }
180
+ return `/ext/${ext}/actions/${name}`;
181
+ }
182
+ /** An extension name (`finance/quotes`): segments that start with a letter. */
183
+ const EXTENSION_NAME = /^[a-z][a-z0-9-]*(\/[a-z][a-z0-9-]*)*$/;
184
+ /** An action name, as the manifest's `actions[].name`. */
185
+ const ACTION = /^[a-z][a-zA-Z0-9]*$/;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `zveltio.view/2` — the specification of an extension's views (ADR 0042).
3
+ *
4
+ * THE SINGLE SOURCE. `scripts/gen-view-spec.ts` derives from this object the
5
+ * TypeScript types (`types.generated.ts`) and the published JSON Schema
6
+ * (`packages/sdk/schemas/view-2.schema.json`); `bun run check:view-spec` fails
7
+ * when either is stale. Edit here, then run `bun run scripts/gen-view-spec.ts`.
8
+ *
9
+ * A view is semantic: it names collections, fields and actions, never a URL,
10
+ * an HTTP verb, a CSS class, an icon or an expression. Every object is closed
11
+ * (`additionalProperties: false`), so a key the vocabulary does not have — a
12
+ * `dataSource`, an `endpoint`, a `class` — is refused rather than ignored.
13
+ * Additions inside `view/2` are new optional keys or view kinds; removing or
14
+ * narrowing anything is `view/3`.
15
+ */
16
+ export declare const VIEW_SPEC = "zveltio.view/2";
17
+ type Schema = Record<string, unknown>;
18
+ export declare const VIEW_SCHEMA: Schema;
19
+ export {};
20
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/view/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,eAAO,MAAM,SAAS,mBAAmB,CAAC;AA8B1C,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAkatC,eAAO,MAAM,WAAW,EAAE,MAQzB,CAAC"}