@zveltio/sdk 3.0.0-beta.127 → 3.0.0-beta.133

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.
@@ -23,6 +23,7 @@
23
23
  * - Building the Studio bundle. Too slow; pair with `zveltio extension build`
24
24
  * which can call validate as a sub-step.
25
25
  */
26
+ import { z } from 'zod';
26
27
  import { parseMigrationSql } from './migration-parse.js';
27
28
  export { SHARED_MESSAGE_KEYS } from './shared-message-keys.js';
28
29
  /** Headers the engine keeps from a worker-isolated extension unless `forwardCredentials` names them. */
@@ -140,8 +141,7 @@ export function validateManifest(input) {
140
141
  }
141
142
  }
142
143
  // Actions and jobs: the engine's manifest schema refuses the whole extension
143
- // on any of these. Whether `input` compiles as a JSON Schema needs Zod, so
144
- // that one is left to the engine.
144
+ // on any of these (parity: engine tests/unit/manifest-validate-parity.test.ts).
145
145
  const NAME = /^[a-z][a-zA-Z0-9]*$/;
146
146
  const strings = (v) => v === undefined || (Array.isArray(v) && v.every((s) => typeof s === 'string'));
147
147
  const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -164,6 +164,8 @@ export function validateManifest(input) {
164
164
  seen.add(e.name);
165
165
  if (!isObject(e.input))
166
166
  out.push(err(code, `"${e.name}": "input" must be a JSON Schema object`));
167
+ else if (!compileInput(e.input))
168
+ out.push(err(code, `"${e.name}": "input" is not a JSON Schema the engine can compile`));
167
169
  for (const k of ['reads', 'writes', 'enqueues', 'calls', 'fromPublicRoutes']) {
168
170
  if (!strings(e[k]))
169
171
  out.push(err(code, `"${e.name}": "${k}" must be an array of names`));
@@ -316,8 +318,7 @@ export function validateManifest(input) {
316
318
  }
317
319
  const egress = j.egress;
318
320
  const egressOk = egress === undefined ||
319
- (Array.isArray(egress) &&
320
- egress.every((e) => typeof e === 'string' && /^[a-z0-9.\-[\]:]+$/.test(e)));
321
+ (Array.isArray(egress) && egress.every((e) => typeof e === 'string' && isEgressEntry(e)));
321
322
  if (!egressOk) {
322
323
  out.push(err('MANIFEST_BAD_JOB', `job "${j.name}": "egress" lists lower-case host names or host:port, no scheme, path or wildcard`));
323
324
  }
@@ -355,12 +356,15 @@ export function validateManifest(input) {
355
356
  }
356
357
  // ADR 0048 d1: a clock that enqueues the job, five cron fields in UTC, as the engine reads them.
357
358
  if (j.schedule !== undefined) {
358
- if (typeof j.schedule !== 'string' || !isCron(j.schedule)) {
359
- out.push(err('MANIFEST_BAD_JOB', `job "${j.name}": schedule "${String(j.schedule)}" is not a five-field cron expression (minute hour day-of-month month day-of-week; *, n, a-b, a,b and /step; in UTC)`));
359
+ if (typeof j.schedule !== 'string' || !cronFires(j.schedule)) {
360
+ out.push(err('MANIFEST_BAD_JOB', `job "${j.name}": schedule "${String(j.schedule)}" is not a five-field cron expression that fires (minute hour day-of-month month day-of-week; *, n, a-b, a,b and /step; in UTC)`));
360
361
  }
361
362
  else if (!(Array.isArray(obj.permissions) && obj.permissions.includes('data:system'))) {
362
363
  out.push(err('MANIFEST_BAD_JOB', `job "${j.name}": a scheduled job runs with no caller, which needs the data:system capability`));
363
364
  }
365
+ else if (compileInput(j.input)?.safeParse({}).success === false) {
366
+ out.push(err('MANIFEST_BAD_JOB', `job "${j.name}": a scheduled job is enqueued with input {}, which its input schema must accept`));
367
+ }
364
368
  }
365
369
  const hasEgress = (Array.isArray(egress) && egress.length > 0) || (Array.isArray(slots) && slots.length > 0);
366
370
  if (!int(j.timeoutSeconds, 1, hasEgress ? 900 : 60)) {
@@ -540,8 +544,84 @@ function columnLevelUniqueColumns(sql) {
540
544
  }
541
545
  return out;
542
546
  }
547
+ /**
548
+ * The SQL that runs: comments become a space and every string literal `''`, in
549
+ * one left-to-right pass. Chained regexes get the order wrong (`'--'` opens a
550
+ * "comment", a quote inside a block comment a "string") and miss `E'\''`, so a quoted `DROP COLUMN tenant_id` read as a real one.
551
+ * Quoted identifiers stay; a `$$…$$` body is scanned on its own (`DO $$ … $$` runs).
552
+ */
553
+ // PostgreSQL's dolq_start / dolq_cont: ASCII letters, `_`, digits after the
554
+ // first, and any non-ASCII character.
555
+ const DOLLAR_TAG = /^\$(?:[A-Za-z_\u0080-\u{10FFFF}][A-Za-z0-9_\u0080-\u{10FFFF}]*)?\$/u;
556
+ function sqlCode(sql) {
557
+ let out = '';
558
+ let i = 0;
559
+ while (i < sql.length) {
560
+ const c = sql[i];
561
+ const dollar = c === '$' && !/[\w$]/.test(sql[i - 1] ?? '') && DOLLAR_TAG.exec(sql.slice(i));
562
+ if (dollar) {
563
+ // A `$$…$$` body may run (`DO $$ … $$`), so it is scanned on its own: a
564
+ // quote or `--` inside it must not swallow the SQL around it.
565
+ const tag = dollar[0];
566
+ const end = sql.indexOf(tag, i + tag.length);
567
+ const stop = end < 0 ? sql.length : end;
568
+ out += ` ${sqlCode(sql.slice(i + tag.length, stop))} `;
569
+ i = end < 0 ? sql.length : end + tag.length;
570
+ }
571
+ else if (sql.startsWith('--', i)) {
572
+ const end = sql.indexOf('\n', i);
573
+ i = end < 0 ? sql.length : end;
574
+ out += ' ';
575
+ }
576
+ else if (sql.startsWith('/*', i)) {
577
+ let depth = 1;
578
+ i += 2;
579
+ while (i < sql.length && depth > 0) {
580
+ if (sql.startsWith('/*', i)) {
581
+ depth++;
582
+ i += 2;
583
+ }
584
+ else if (sql.startsWith('*/', i)) {
585
+ depth--;
586
+ i += 2;
587
+ }
588
+ else
589
+ i++;
590
+ }
591
+ out += ' ';
592
+ }
593
+ else if (c === "'" ||
594
+ ((c === 'E' || c === 'e') && sql[i + 1] === "'" && !/\w/.test(sql[i - 1] ?? ''))) {
595
+ const escapes = c !== "'";
596
+ i += escapes ? 2 : 1;
597
+ while (i < sql.length) {
598
+ if (escapes && sql[i] === '\\')
599
+ i += 2;
600
+ else if (sql[i] === "'" && sql[i + 1] === "'")
601
+ i += 2;
602
+ else if (sql[i] === "'")
603
+ break;
604
+ else
605
+ i++;
606
+ }
607
+ i++;
608
+ out += "''";
609
+ }
610
+ else if (c === '"') {
611
+ const end = sql.indexOf('"', i + 1);
612
+ const stop = end < 0 ? sql.length : end + 1;
613
+ out += sql.slice(i, stop);
614
+ i = stop;
615
+ }
616
+ else {
617
+ out += c;
618
+ i++;
619
+ }
620
+ }
621
+ return out;
622
+ }
543
623
  function keyColumnSets(upSql) {
544
- const s = upSql.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
624
+ const s = sqlCode(upSql);
545
625
  const sets = [];
546
626
  const add = (cols, table) => {
547
627
  const key = cols
@@ -576,7 +656,9 @@ const bareTable = (t) => t.replace(/"/g, '').split('.').pop().toLowerCase();
576
656
  * 004): a key on it is instance-wide and needs no tenant column.
577
657
  */
578
658
  function tenantColumnChanges(upSql) {
579
- const s = upSql.replace(/--[^\n]*/g, '');
659
+ // A drop that is commented out or quoted (`COMMENT ON TABLE … IS '… DROP
660
+ // COLUMN tenant_id'`) takes nothing out of tenancy.
661
+ const s = sqlCode(upSql);
580
662
  const out = [];
581
663
  for (const m of s.matchAll(/ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([\w."]+)\s[^;]*?\b(ADD|DROP)\s+COLUMN\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?"?tenant_id"?\b/gi))
582
664
  out.push([bareTable(m[1]), m[2].toUpperCase() === 'DROP']);
@@ -898,6 +980,12 @@ export function validateSduiSchema(input) {
898
980
  collectEndpoints(schema, endpoints);
899
981
  for (const raw of endpoints) {
900
982
  const bare = raw.split('?')[0];
983
+ // A browser resolves `.` and `..` before it sends the request, so
984
+ // `/ext/dep/../../api/admin/users` is a call to `/api/admin/users`.
985
+ if (/(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i.test(raw.split(/[?#]/)[0])) {
986
+ out.push(err('SDUI_ENDPOINT_DOT_SEGMENT', `endpoint "${raw}" has a "." or ".." path segment, which a browser resolves to another path. Name the route itself.`, file));
987
+ continue;
988
+ }
901
989
  if (SDUI_SHARED_READ_ALLOWLIST.has(bare))
902
990
  continue;
903
991
  // A dependency's namespace is allowed (relation pickers etc.).
@@ -1016,24 +1104,78 @@ export function validateExtension(input) {
1016
1104
  },
1017
1105
  };
1018
1106
  }
1019
- /** Five cron fields, each `*`, `n`, `a-b` or a list of them, with `/step`; in range. */
1020
- function isCron(expr) {
1021
- const ranges = [
1107
+ /** The engine's `inputSchemaIssue`: the compiled schema, or null when Zod cannot compile it. */
1108
+ function compileInput(input) {
1109
+ if (!input || typeof input !== 'object' || Array.isArray(input))
1110
+ return null;
1111
+ try {
1112
+ return z.fromJSONSchema(input);
1113
+ }
1114
+ catch {
1115
+ return null;
1116
+ }
1117
+ }
1118
+ /**
1119
+ * The engine's `parseEgress`: a host or host:port, written the way the URL
1120
+ * parser writes it back, or it could never match a request.
1121
+ */
1122
+ function isEgressEntry(e) {
1123
+ if (!/^(\[[0-9a-f:.]+\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)(:\d{1,5})?$/.test(e))
1124
+ return false;
1125
+ try {
1126
+ return new URL(`http://${e}`).hostname === e.replace(/:\d{1,5}$/, '');
1127
+ }
1128
+ catch {
1129
+ return false;
1130
+ }
1131
+ }
1132
+ /** One cron field as the set it matches (the engine's `parseField`), or null. */
1133
+ function cronField(raw, min, max) {
1134
+ const out = new Set();
1135
+ for (const part of raw.split(',')) {
1136
+ const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
1137
+ if (!m)
1138
+ return null;
1139
+ const step = m[4] === undefined ? 1 : Number(m[4]);
1140
+ const lo = m[2] === undefined ? min : Number(m[2]);
1141
+ // A bare number with a step runs to the end of the range.
1142
+ const hi = m[3] !== undefined ? Number(m[3]) : m[2] === undefined || m[4] ? max : lo;
1143
+ if (step < 1 || lo < min || hi > max || lo > hi)
1144
+ return null;
1145
+ for (let v = lo; v <= hi; v += step)
1146
+ out.add(v);
1147
+ }
1148
+ return out;
1149
+ }
1150
+ /**
1151
+ * Five cron fields that fire within four years, as the engine's `nextCronRun`
1152
+ * reads them: day-of-month and day-of-week OR when both are restricted (do not
1153
+ * start with `*`), AND otherwise; 7 is Sunday.
1154
+ */
1155
+ function cronFires(expr) {
1156
+ const p = expr.trim().split(/\s+/);
1157
+ if (p.length !== 5)
1158
+ return false;
1159
+ const [minute, hour, dom, month, dow] = [
1022
1160
  [0, 59],
1023
1161
  [0, 23],
1024
1162
  [1, 31],
1025
1163
  [1, 12],
1026
1164
  [0, 7],
1027
- ];
1028
- const fields = expr.trim().split(/\s+/);
1029
- return (fields.length === 5 &&
1030
- fields.every((field, i) => field.split(',').every((part) => {
1031
- const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
1032
- if (!m)
1033
- return false;
1034
- const [min, max] = ranges[i];
1035
- const lo = m[2] === undefined ? min : Number(m[2]);
1036
- const hi = m[3] === undefined ? (m[2] === undefined ? max : lo) : Number(m[3]);
1037
- return lo >= min && hi <= max && lo <= hi && (m[4] === undefined || Number(m[4]) >= 1);
1038
- })));
1165
+ ].map(([lo, hi], i) => cronField(p[i], lo, hi));
1166
+ if (!minute || !hour || !dom || !month || !dow)
1167
+ return false;
1168
+ if (dow.delete(7))
1169
+ dow.add(0);
1170
+ const either = !p[2].startsWith('*') && !p[4].startsWith('*');
1171
+ const day = new Date();
1172
+ for (let i = 0; i < 366 * 4; i++, day.setUTCDate(day.getUTCDate() + 1)) {
1173
+ if (!month.has(day.getUTCMonth() + 1))
1174
+ continue;
1175
+ const d = dom.has(day.getUTCDate());
1176
+ const w = dow.has(day.getUTCDay());
1177
+ if (either ? d || w : d && w)
1178
+ return true;
1179
+ }
1180
+ return false;
1039
1181
  }
@@ -60,6 +60,9 @@ export type ActionOutcome = {
60
60
  } | {
61
61
  kind: 'reveal';
62
62
  value: string;
63
+ } | {
64
+ kind: 'redirect';
65
+ url: string;
63
66
  } | {
64
67
  kind: 'values';
65
68
  values: unknown;
@@ -85,6 +88,12 @@ export interface ViewNames {
85
88
  * checked. Omit to skip.
86
89
  */
87
90
  fields?: ReadonlyMap<string, Iterable<string>>;
91
+ /**
92
+ * Each declared collection's fields a list may use as a `facets` entry: a
93
+ * boolean, or one with declared choices. A collection absent here is not
94
+ * checked. Omit to skip.
95
+ */
96
+ facetFields?: ReadonlyMap<string, Iterable<string>>;
88
97
  }
89
98
  /**
90
99
  * What the schema cannot see in a (valid) view: a collection or action its
@@ -93,6 +102,13 @@ export interface ViewNames {
93
102
  * the extension does not ship, a field its collection does not have. (`fallback` is an inline view, not a reference.)
94
103
  */
95
104
  export declare function viewNameIssues(view: unknown, names: ViewNames): ViewIssue[];
105
+ /**
106
+ * A `pick` names an input the action declares as a plain string (the record's
107
+ * id is a string): not a number, a list, an object or a fixed set of choices.
108
+ * `inputs`: each own action's declared input JSON Schema, by name; an action
109
+ * absent from it (a dependency's, or one with no schema) is not checked.
110
+ */
111
+ export declare function pickIssues(view: unknown, inputs: ReadonlyMap<string, unknown>): ViewIssue[];
96
112
  type Kind = View['type'];
97
113
  type Of<K extends Kind> = Extract<View, {
98
114
  type: K;
@@ -133,6 +149,7 @@ export declare const view: {
133
149
  actions?: import("./types.generated.js").Buttons;
134
150
  fallback?: View;
135
151
  action: import("./types.generated.js").ActionName;
152
+ pick?: Record<string, import("./types.generated.js").Name>;
136
153
  fields?: import("./types.generated.js").Fields;
137
154
  sections?: Array<{
138
155
  title?: import("./types.generated.js").Text;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/view/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAe,SAAS,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,KAAK,EAAgB,SAAS,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAE9F,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACrD,cAAc,cAAc,CAAC;AAC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AAI,CAAC,MAAM,CAAC,CAAC;AACzB,KAAK,EAAE,CAAC,CAAC,SAAS,IAAI,IAAI,OAAO,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC,CAAC;AAYrD;;;;GAIG;AACH,eAAO,MAAM,IAAI;;;;;;;;;;;;iBAvTX,CAAA;;;;;;kBAII,CAAR;iBAAmB,CAAC;;;;;;;;;;;;;;;iBAgBL,CAAC;;;;;;kBAIH,CAAC;iBAAoB,CAAA;;;;;;;;;;;;;;;kBA2SpB,IAAI,OAAO,MAAM,KAAG,YAAY;CAC/C,CAAC;AAEF,sFAAsF;AACtF,eAAO,MAAM,CAAC;oBACI,MAAM,KAAG,GAAG;qBACX,MAAM,KAAG,GAAG;uBACV,MAAM,KAAG,GAAG;kBACjB,MAAM,KAAG,GAAG;gBAChB,GAAG;iBACF,GAAG;mBACC,MAAM,MAAM,SAAS,CAAC,IAAI,CAAC,UAAU,KAAK,KAAG,SAAS;CAEtE,CAAC"}
@@ -38,7 +38,8 @@ const CONDITION_LISTS = new Set(['filter', 'when', 'emphasisWhen', 'busyWhen']);
38
38
  * - the data API takes one value per field and operator (`{"f":{"gt":1,"lt":9}}`),
39
39
  * so a condition list that gives the same pair twice cannot be sent whole: one
40
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.
41
+ * - a button's `prompt` (and its `files.prompt`) never names an input its
42
+ * `input` already binds.
42
43
  */
43
44
  function crossChecks(v, path, out) {
44
45
  if (Array.isArray(v)) {
@@ -58,6 +59,50 @@ function crossChecks(v, path, out) {
58
59
  }
59
60
  });
60
61
  }
62
+ // `pick` draws an input as a picker: on a button only an input it asks for, on neither one it sets.
63
+ if (isObj(v.pick)) {
64
+ const button = v.type !== 'form';
65
+ for (const name of Object.keys(v.pick)) {
66
+ if (isObj(v.input) && Object.hasOwn(v.input, name)) {
67
+ out.push({
68
+ path: `${path}/pick/${name}`,
69
+ message: 'names an input the button already sets',
70
+ });
71
+ }
72
+ else if (button && !(Array.isArray(v.prompt) && v.prompt.includes(name))) {
73
+ out.push({
74
+ path: `${path}/pick/${name}`,
75
+ message: 'names an input the button does not ask for (`prompt`)',
76
+ });
77
+ }
78
+ }
79
+ }
80
+ if (Array.isArray(v.facets)) {
81
+ const all = v.facets;
82
+ all.forEach((f, i) => {
83
+ if (all.indexOf(f) !== i)
84
+ out.push({ path: `${path}/facets/${i}`, message: 'repeats a field' });
85
+ });
86
+ }
87
+ // A facet adds `field eq value`: on a field the view's `filter` already constrains it would contradict it.
88
+ if (Array.isArray(v.facets) && Array.isArray(v.filter)) {
89
+ const fixed = new Set(v.filter.map((c) => (isObj(c) ? c.field : undefined)));
90
+ v.facets.forEach((f, i) => {
91
+ if (fixed.has(f)) {
92
+ out.push({
93
+ path: `${path}/facets/${i}`,
94
+ message: "is a field the view's filter already constrains",
95
+ });
96
+ }
97
+ });
98
+ }
99
+ const filePrompt = isObj(v.files) && isObj(v.files.prompt) ? v.files.prompt.input : undefined;
100
+ if (typeof filePrompt === 'string' && isObj(v.input) && Object.hasOwn(v.input, filePrompt)) {
101
+ out.push({
102
+ path: `${path}/files/prompt/input`,
103
+ message: 'names an input the button already sets',
104
+ });
105
+ }
61
106
  for (const [k, x] of Object.entries(v)) {
62
107
  if (CONDITION_LISTS.has(k) && Array.isArray(x)) {
63
108
  const seen = new Set();
@@ -92,6 +137,9 @@ export function readActionResult(result) {
92
137
  if (isObj(r) && 'reveal' in r && typeof r.reveal === 'string') {
93
138
  return { kind: 'reveal', value: r.reveal };
94
139
  }
140
+ if (isObj(r) && 'redirect' in r && typeof r.redirect === 'string') {
141
+ return { kind: 'redirect', url: r.redirect };
142
+ }
95
143
  return { kind: 'values', values: result };
96
144
  }
97
145
  /** Keys that name one field of the bound collection, by view kind (`*`: any). */
@@ -120,6 +168,8 @@ function fieldRefs(v) {
120
168
  add(`/${k}`, v[k]);
121
169
  fieldList(v.fields, '/fields');
122
170
  fieldList(v.card, '/card');
171
+ if (Array.isArray(v.facets))
172
+ v.facets.forEach((f, i) => add(`/facets/${i}`, f));
123
173
  if (Array.isArray(v.sections)) {
124
174
  v.sections.forEach((s, i) => isObj(s) && fieldList(s.fields, `/sections/${i}/fields`));
125
175
  }
@@ -151,6 +201,7 @@ export function viewNameIssues(view, names) {
151
201
  const views = names.views && new Set(names.views);
152
202
  const keys = names.messageKeys && new Set(names.messageKeys);
153
203
  const fields = names.fields && new Map([...names.fields].map(([c, f]) => [c, new Set(f)]));
204
+ const facetable = names.facetFields && new Map([...names.facetFields].map(([c, f]) => [c, new Set(f)]));
154
205
  const ids = new Set();
155
206
  const out = [];
156
207
  const issue = (path, message) => out.push({ path, message });
@@ -180,8 +231,26 @@ export function viewNameIssues(view, names) {
180
231
  issue(`${path}${at}`, `field "${f}" is not a field of "${v.collection}"`);
181
232
  }
182
233
  }
234
+ const facetOk = !valuesOnly && typeof v.collection === 'string' && facetable?.get(v.collection);
235
+ if (facetOk && Array.isArray(v.facets)) {
236
+ v.facets.forEach((f, i) => {
237
+ // A field the collection lacks is reported above, as every field reference.
238
+ if (typeof f === 'string' && known && known.has(f) && !facetOk.has(f)) {
239
+ issue(`${path}/facets/${i}`, `field "${f}" is neither a boolean nor a single-value field with declared choices`);
240
+ }
241
+ });
242
+ }
183
243
  for (const [k, x] of Object.entries(v)) {
184
244
  const at = `${path}/${k}`;
245
+ if (k === 'pick' && !valuesOnly && isObj(x)) {
246
+ // Input names are the caller's; each value names a collection.
247
+ for (const [name, c] of Object.entries(x)) {
248
+ if (typeof c === 'string' && !collections.has(c)) {
249
+ issue(`${at}/${name}`, `collection "${c}" is not declared by this extension`);
250
+ }
251
+ }
252
+ continue;
253
+ }
185
254
  if (k === '$selected') {
186
255
  if (typeof x === 'string' && !panes.has(x)) {
187
256
  issue(at, `"${x}" is not an earlier pane of an enclosing split`);
@@ -233,6 +302,46 @@ export function viewNameIssues(view, names) {
233
302
  walk(view, '', new Set(), false);
234
303
  return out;
235
304
  }
305
+ /**
306
+ * A `pick` names an input the action declares as a plain string (the record's
307
+ * id is a string): not a number, a list, an object or a fixed set of choices.
308
+ * `inputs`: each own action's declared input JSON Schema, by name; an action
309
+ * absent from it (a dependency's, or one with no schema) is not checked.
310
+ */
311
+ export function pickIssues(view, inputs) {
312
+ const out = [];
313
+ const walk = (v, path) => {
314
+ if (Array.isArray(v)) {
315
+ v.forEach((x, i) => walk(x, `${path}/${i}`));
316
+ return;
317
+ }
318
+ if (!isObj(v))
319
+ return;
320
+ if (isObj(v.pick) && typeof v.action === 'string' && inputs.has(v.action)) {
321
+ const props = inputs.get(v.action)
322
+ ?.properties;
323
+ for (const name of Object.keys(v.pick)) {
324
+ const p = props && Object.hasOwn(props, name) ? props[name] : undefined;
325
+ const t = isObj(p) ? p.type : undefined;
326
+ const text = t === 'string' ||
327
+ (Array.isArray(t) &&
328
+ t.length > 0 &&
329
+ t.every((x) => x === 'string' || x === 'null') &&
330
+ t.includes('string'));
331
+ if (!text || (isObj(p) && Array.isArray(p.enum))) {
332
+ out.push({
333
+ path: `${path}/pick/${name}`,
334
+ message: `is not a string input of action "${v.action}"`,
335
+ });
336
+ }
337
+ }
338
+ }
339
+ for (const [k, x] of Object.entries(v))
340
+ walk(x, `${path}/${k}`);
341
+ };
342
+ walk(view, '');
343
+ return out;
344
+ }
236
345
  /** Drops `undefined` keys (`sort: cond ? 'a' : undefined`) at every depth, as the file would. */
237
346
  const clean = (v) => JSON.parse(JSON.stringify(v));
238
347
  const kind = (type) => (props) => clean({ type, ...props });
@@ -91,4 +91,30 @@ export declare function viewFields(fields: Fields | undefined, schema: readonly
91
91
  export declare function fallbackFor(view: View, drawn: ReadonlySet<string>): View | null;
92
92
  /** The engine path that runs an action: its own extension's, or `<dependency>.<action>`. */
93
93
  export declare function actionPath(extension: string, action: string): string;
94
+ /** The collection a relation field points at (`m2o`, `reference`); none for any other field. */
95
+ export declare function relatedOf(f: SchemaField | undefined): string | null;
96
+ /** A facet value as the choice declares it. */
97
+ export type FacetValue = string | number | boolean;
98
+ /**
99
+ * A field's declared choices, in order, each as the declaration gives it (a
100
+ * plain value or `{ value, label }`). The engine's `enum` declares them as
101
+ * `options.values`; a list in `options`, or `options.choices`, is read too.
102
+ * Nothing for a field that declares none.
103
+ */
104
+ export declare function declaredChoices(f: SchemaField | undefined): unknown[];
105
+ /**
106
+ * What a list's `facets` entry offers for a field: its declared choices, or
107
+ * `true` and `false` for a boolean; nothing for any other field.
108
+ */
109
+ export declare function facetOptions(f: SchemaField | undefined): {
110
+ value: FacetValue;
111
+ label: string;
112
+ }[];
113
+ /**
114
+ * A list's `filter` with the facet values picked (field → value) added as
115
+ * `field eq value`. A facet on a field the filter constrains is refused by
116
+ * `validateView`; one that slips through is dropped, so the view's own
117
+ * condition always stands.
118
+ */
119
+ export declare function withFacets(filter: Conditions | undefined, picked: Readonly<Record<string, FacetValue | undefined>>): Conditions | undefined;
94
120
  //# sourceMappingURL=runtime.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/view/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EACV,MAAM,EAEN,UAAU,EACV,KAAK,EACL,MAAM,EACN,WAAW,EACX,KAAK,EAGL,IAAI,EACJ,KAAK,EACL,IAAI,EACL,MAAM,sBAAsB,CAAC;AAE9B,8EAA8E;AAC9E,MAAM,WAAW,SAAS;IACxB,sCAAsC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,mEAAmE;IACnE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IACtC,0DAA0D;IAC1D,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,yCAAyC;IACzC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object' && v !== null && !Array.isArray(v) && Object.keys(v)[0]?.startsWith('$');
13
+ /** An own property only: `constructor` on a plain record is no field. */
14
+ const own = (o, k) => o && Object.hasOwn(o, k) ? o[k] : undefined;
13
15
  function localToday() {
14
16
  const d = new Date();
15
17
  const p = (n) => String(n).padStart(2, '0');
@@ -24,13 +26,13 @@ export function resolveValue(v, s) {
24
26
  if (!isRef(v))
25
27
  return v;
26
28
  if ('$record' in v)
27
- return s.record?.[v.$record];
29
+ return own(s.record, v.$record);
28
30
  if ('$selected' in v)
29
- return s.selected?.[v.$selected];
31
+ return own(s.selected, v.$selected);
30
32
  if ('$selection' in v)
31
- return s.selection?.map((r) => r[v.$selection]);
33
+ return s.selection?.map((r) => own(r, v.$selection));
32
34
  if ('$param' in v)
33
- return s.params?.[v.$param];
35
+ return own(s.params, v.$param);
34
36
  if ('$user' in v)
35
37
  return s.user;
36
38
  return s.today ?? localToday();
@@ -115,7 +117,7 @@ export function toFilter(conds, s) {
115
117
  return null;
116
118
  }
117
119
  // The data API takes one value per field and operator; `validateView` refuses the pair twice.
118
- if (out[c.field] && c.op in out[c.field]) {
120
+ if (Object.hasOwn(out, c.field) && c.op in out[c.field]) {
119
121
  throw new Error(`view/2: "${c.field}" ${c.op} is given twice in one condition list`);
120
122
  }
121
123
  out[c.field] = { ...out[c.field], [c.op]: value };
@@ -126,7 +128,7 @@ const cmp = (a, b) => typeof a === 'number' && typeof b === 'number'
126
128
  ? a - b
127
129
  : String(a ?? '').localeCompare(String(b ?? ''));
128
130
  function holds(c, row, s) {
129
- const have = row[c.field];
131
+ const have = own(row, c.field);
130
132
  if (!('value' in c))
131
133
  return c.op === 'null' ? have == null : have != null;
132
134
  const want = resolveValue(c.value, s);
@@ -238,3 +240,55 @@ export function actionPath(extension, action) {
238
240
  const EXTENSION_NAME = /^[a-z][a-z0-9-]*(\/[a-z][a-z0-9-]*)*$/;
239
241
  /** An action name, as the manifest's `actions[].name`. */
240
242
  const ACTION = /^[a-z][a-zA-Z0-9]*$/;
243
+ /** The collection a relation field points at (`m2o`, `reference`); none for any other field. */
244
+ export function relatedOf(f) {
245
+ const target = f?.options
246
+ ?.related_collection;
247
+ return (f?.type === 'm2o' || f?.type === 'reference') && typeof target === 'string'
248
+ ? target
249
+ : null;
250
+ }
251
+ /**
252
+ * A field's declared choices, in order, each as the declaration gives it (a
253
+ * plain value or `{ value, label }`). The engine's `enum` declares them as
254
+ * `options.values`; a list in `options`, or `options.choices`, is read too.
255
+ * Nothing for a field that declares none.
256
+ */
257
+ export function declaredChoices(f) {
258
+ const opts = f?.options;
259
+ if (Array.isArray(opts))
260
+ return opts;
261
+ const list = opts?.values ?? opts?.choices;
262
+ return Array.isArray(list) ? list : [];
263
+ }
264
+ /**
265
+ * What a list's `facets` entry offers for a field: its declared choices, or
266
+ * `true` and `false` for a boolean; nothing for any other field.
267
+ */
268
+ export function facetOptions(f) {
269
+ if (f?.type === 'boolean') {
270
+ return [true, false].map((value) => ({ value, label: String(value) }));
271
+ }
272
+ // A multi-value field holds a list: `eq` on one value cannot select it.
273
+ if (f?.options?.multiple === true)
274
+ return [];
275
+ // The choice keeps its type (a number stays a number): the query compares it as declared.
276
+ const typed = (v) => typeof v === 'number' || typeof v === 'boolean' ? v : String(v);
277
+ return declaredChoices(f).map((c) => {
278
+ if (typeof c !== 'object' || c === null)
279
+ return { value: typed(c), label: String(c) };
280
+ const { value, label } = c;
281
+ return { value: typed(value), label: String(label ?? value) };
282
+ });
283
+ }
284
+ /**
285
+ * A list's `filter` with the facet values picked (field → value) added as
286
+ * `field eq value`. A facet on a field the filter constrains is refused by
287
+ * `validateView`; one that slips through is dropped, so the view's own
288
+ * condition always stands.
289
+ */
290
+ export function withFacets(filter, picked) {
291
+ const own = new Set((filter ?? []).map((c) => c.field));
292
+ const added = Object.entries(picked).flatMap(([field, value]) => value === undefined || own.has(field) ? [] : [{ field, op: 'eq', value }]);
293
+ return added.length ? [...(filter ?? []), ...added] : filter;
294
+ }
@@ -1 +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;AA+btC,eAAO,MAAM,WAAW,EAAE,MAQzB,CAAC"}
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;AAqetC,eAAO,MAAM,WAAW,EAAE,MAQzB,CAAC"}