@keemakr/ui-sdk 1.7.0 → 1.8.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/dist/check.js ADDED
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Checks before publish (WS28-S5): one pure checker for a screen tree or a page, run the same way
3
+ * by every surface that publishes one. The `keemakr-ui check` CLI and its CI action (Pack authors),
4
+ * core's MCP tools `ui_tree_validate` and `ui_tree_lint` (agents), and the builder's gate (a save
5
+ * shows the findings; a push or a template submit refuses on errors) all call `checkPage`, so a
6
+ * finding has one rule id and one path wherever it is seen.
7
+ *
8
+ * import { checkPage } from '@keemakr/ui-sdk/check';
9
+ * const { ok, findings } = checkPage(tree, { bindings: { datasets: ['leads'], actions: ['approve'] } });
10
+ *
11
+ * Pure: no network, no clock, no file system. Everything that depends on a company (its installed
12
+ * datasets, the action ids its Packs declare) comes in as `bindings`, which the caller reads
13
+ * before it calls. Without `bindings` the binding rules do not run: a Pack's own screen names its
14
+ * own actions, and only a page assembled for a company is bound to that company's installs.
15
+ *
16
+ * Errors block a publish; warnings are shown. The rules:
17
+ * schema.* the tree does not parse as core parses it (the Zod schema is the gate).
18
+ * limit.* a field is over its cap. The caps are NODE_LIMITS, read from the same schema.
19
+ * binding.* a dataset or an action the company does not have.
20
+ * reach.* the newest release of a client gets a fallback instead of the node.
21
+ * workaround.* / a11y.* a known hand-built stand-in for a block the SDK has; some have a fix
22
+ * (`fixPage`, or `keemakr-ui check --fix`).
23
+ */
24
+ import { NODE_LIMITS } from './node-limits.js';
25
+ import { KNOWN_NODE_TYPES } from './nodes.js';
26
+ import { CORE_DRAWN_NODE_TYPES, latestRelease, negotiateTree, nodeSetForClient, } from './negotiate.js';
27
+ import { screenTreeSchema } from './schema.js';
28
+ /** Every rule, with its severity and what it means: for the CLI's `--rules` and the catalog tool. */
29
+ export const CHECK_RULES = {
30
+ 'schema.invalid': { severity: 'error', summary: 'The tree does not parse as core parses it.' },
31
+ 'schema.unknown_node': { severity: 'error', summary: 'A node type the catalog does not have.' },
32
+ 'limit.exceeded': { severity: 'error', summary: 'A field is over its cap in NODE_LIMITS.' },
33
+ 'binding.dataset_unknown': {
34
+ severity: 'error',
35
+ summary: 'A dataset node names a dataset the company has not installed.',
36
+ },
37
+ 'binding.action_undeclared': {
38
+ severity: 'error',
39
+ summary: 'A press or a form calls an action id no installed Pack declares.',
40
+ },
41
+ 'catalog.mismatch': {
42
+ severity: 'warning',
43
+ summary: 'The page names a catalog other than the one it is checked against.',
44
+ },
45
+ 'reach.fallback': {
46
+ severity: 'warning',
47
+ summary: "A client's newest release gets a fallback in place of the node.",
48
+ },
49
+ 'workaround.empty_text': {
50
+ severity: 'warning',
51
+ summary: 'An empty text node used as a spacer.',
52
+ },
53
+ 'workaround.text_alert': {
54
+ severity: 'warning',
55
+ summary: 'A warning or a note written as text with a sign in front.',
56
+ },
57
+ 'workaround.markdown_link': {
58
+ severity: 'warning',
59
+ summary: 'A markdown node that holds only one link.',
60
+ },
61
+ 'workaround.on_off_select': {
62
+ severity: 'warning',
63
+ summary: 'A select with only On and Off (or Yes and No).',
64
+ },
65
+ 'workaround.key_value_table': {
66
+ severity: 'warning',
67
+ summary: 'A two-column table of labels and values.',
68
+ },
69
+ 'a11y.disabled_without_reason': {
70
+ severity: 'warning',
71
+ summary: 'A disabled control that does not say why.',
72
+ },
73
+ 'check.truncated': {
74
+ severity: 'warning',
75
+ summary: 'Too many findings: only the first are listed (CHECK_LIMITS.findings).',
76
+ },
77
+ };
78
+ /**
79
+ * Bounds on the work one check does, because a document can come from anyone allowed to call it
80
+ * (an agent over MCP). No real page comes near them: the schema itself nests a few levels and its
81
+ * keys are short. Past `depth` the walks stop; a key longer than `keyLength` is not a schema key
82
+ * and is not walked into; past `findings` the list is cut (the counts stay exact) and
83
+ * `check.truncated` says so.
84
+ */
85
+ export const CHECK_LIMITS = { depth: 32, keyLength: 64, findings: 500 };
86
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
87
+ const join = (base, key) => (base ? `${base}.${key}` : key);
88
+ /** A page wraps its tree (`{ format: 'keemakr.page', tree, ... }`); a bare tree is checked as is. */
89
+ function treeOf(document) {
90
+ if (isObject(document) && isObject(document.tree) && !('children' in document)) {
91
+ return {
92
+ tree: document.tree,
93
+ base: 'tree',
94
+ catalogId: typeof document.catalogId === 'string' ? document.catalogId : undefined,
95
+ };
96
+ }
97
+ return { tree: document, base: '' };
98
+ }
99
+ function pathOf(base, path) {
100
+ let out = base;
101
+ for (const key of path) {
102
+ if (typeof key === 'number')
103
+ out += `[${key}]`;
104
+ else {
105
+ const name = String(key);
106
+ // A key no schema has can be as long as the sender likes: keep the path short.
107
+ out = join(out, name.length > CHECK_LIMITS.keyLength ? `${name.slice(0, 16)}…` : name);
108
+ }
109
+ }
110
+ return out || '(root)';
111
+ }
112
+ function valueAt(root, path) {
113
+ let value = root;
114
+ for (const key of path) {
115
+ if (Array.isArray(value) && typeof key === 'number')
116
+ value = value[key];
117
+ else if (isObject(value))
118
+ value = value[String(key)];
119
+ else
120
+ return undefined;
121
+ }
122
+ return value;
123
+ }
124
+ /**
125
+ * Every node of the tree where a node can stand: the tree's children, a section's, each tab's and
126
+ * a table row's `expand`. Read from the raw input, so a tree that fails the schema elsewhere is
127
+ * still walked. The page format (page.ts) stamps node ids over the same walk.
128
+ */
129
+ export function placedNodes(tree, base) {
130
+ const out = [];
131
+ const visitList = (list, path, inExpand, depth = 0) => {
132
+ if (!Array.isArray(list) || depth > CHECK_LIMITS.depth)
133
+ return;
134
+ list.forEach((child, index) => {
135
+ if (!isObject(child))
136
+ return;
137
+ const at = `${path}[${index}]`;
138
+ out.push({
139
+ node: child,
140
+ path: at,
141
+ replace: (next) => (list[index] = next),
142
+ list,
143
+ index,
144
+ inExpand,
145
+ });
146
+ const next = depth + 1;
147
+ if (child.type === 'section')
148
+ visitList(child.children, `${at}.children`, inExpand, next);
149
+ if (child.type === 'tabs' && Array.isArray(child.tabs)) {
150
+ child.tabs.forEach((tab, i) => {
151
+ if (isObject(tab))
152
+ visitList(tab.children, `${at}.tabs[${i}].children`, inExpand, next);
153
+ });
154
+ }
155
+ if (child.type === 'table' && Array.isArray(child.rows)) {
156
+ child.rows.forEach((row, i) => {
157
+ if (isObject(row) && isObject(row.expand)) {
158
+ visitList(row.expand.children, `${at}.rows[${i}].expand.children`, true, next);
159
+ }
160
+ });
161
+ }
162
+ });
163
+ };
164
+ if (isObject(tree))
165
+ visitList(tree.children, join(base, 'children'), false);
166
+ return out;
167
+ }
168
+ /**
169
+ * Every action id the tree calls, wherever a press or a submit can name one: a press of kind
170
+ * `action` (buttons, rows, cells, cards, a select's change), a form's submit and its secondary
171
+ * sends, a table's bulk actions, a composer's send and an inline edit's save.
172
+ */
173
+ /**
174
+ * The action ids the tree calls that `declared` lacks. Only those are collected, so the findings
175
+ * cap never hides an undeclared call behind a page of declared ones.
176
+ */
177
+ function actionRefs(value, path, declared, out, depth = 0) {
178
+ if (depth > CHECK_LIMITS.depth || out.length > CHECK_LIMITS.findings)
179
+ return;
180
+ if (Array.isArray(value)) {
181
+ value.forEach((item, index) => actionRefs(item, `${path}[${index}]`, declared, out, depth + 1));
182
+ return;
183
+ }
184
+ if (!isObject(value))
185
+ return;
186
+ if (typeof value.action === 'string' &&
187
+ (value.kind === undefined || value.kind === 'action') &&
188
+ !declared.has(value.action)) {
189
+ out.push({ id: value.action.slice(0, 64), path: join(path, 'action') });
190
+ }
191
+ for (const [key, child] of Object.entries(value)) {
192
+ // Values a press posts or carries are data, never a reference to an action. A key no schema
193
+ // has is not walked into, so a path stays short whatever the document holds.
194
+ if (key === 'input' || key === 'params' || key.length > CHECK_LIMITS.keyLength)
195
+ continue;
196
+ actionRefs(child, join(path, key), declared, out, depth + 1);
197
+ }
198
+ }
199
+ function finding(rule, path, message, fix, extra = {}) {
200
+ return { rule, severity: CHECK_RULES[rule].severity, path, message, fix, ...extra };
201
+ }
202
+ /** The schema's own verdict, as core reaches it: one finding per Zod issue. */
203
+ function schemaFindings(tree, base, walkedUnknown) {
204
+ const parsed = screenTreeSchema.safeParse(tree);
205
+ const findings = [];
206
+ if (parsed.success)
207
+ return { parsed: parsed.data, findings };
208
+ for (const issue of parsed.error.issues) {
209
+ const path = pathOf(base, issue.path);
210
+ // A node the walk in checkPage already reported as schema.unknown_node: the union's own
211
+ // complaint about it (at the node or at its `type`) is the same fact said less usefully.
212
+ // Only those: an unknown type where the walk does not reach (a header control, a card's
213
+ // button) stays a schema.invalid here, so a tree core refuses never checks clean.
214
+ const nodePath = issue.path.at(-1) === 'type' ? pathOf(base, issue.path.slice(0, -1)) : path;
215
+ if (walkedUnknown.has(nodePath))
216
+ continue;
217
+ if (issue.code === 'too_big') {
218
+ const max = String(issue.maximum);
219
+ const unit = issue.origin === 'string'
220
+ ? `${max} characters`
221
+ : issue.origin === 'array' || issue.origin === 'set'
222
+ ? `${max} items`
223
+ : `at most ${max}`;
224
+ findings.push(finding('limit.exceeded', path, issue.message, `Keep it to ${unit}: trim, page or split it (NODE_LIMITS).`));
225
+ continue;
226
+ }
227
+ findings.push(finding('schema.invalid', path, issue.message, 'Change the field to what the schema takes.'));
228
+ }
229
+ if (findings.length === 0 && walkedUnknown.size === 0) {
230
+ // The parse failed but every issue was skipped: never let that read as a clean tree.
231
+ findings.push(finding('schema.invalid', pathOf(base, []), parsed.error.message, 'Fix the tree so it parses.'));
232
+ }
233
+ return { parsed: undefined, findings };
234
+ }
235
+ const ALERT_SIGN = /^\s*(?:(⚠️?|❗|‼️?)|(ℹ️?)|(warning|caution)\s*:|(note|info)\s*:)\s*/iu;
236
+ const ONLY_LINK = /^\s*\[([^\]\n]{1,120})\]\((https:\/\/[^\s)]{1,2000})\)\s*$/;
237
+ const ON_OFF_PAIRS = [
238
+ ['on', 'off'],
239
+ ['yes', 'no'],
240
+ ['enabled', 'disabled'],
241
+ ['true', 'false'],
242
+ ];
243
+ const KEY_LABELS = new Set(['field', 'key', 'name', 'label', 'property', 'setting', 'item']);
244
+ /** The known hand-built stand-ins (public/ui-sdk/checker.md), found on one node. */
245
+ function workaroundsOf({ node, path, inExpand }) {
246
+ const out = [];
247
+ // Only where the replacement may stand, and never over an inline edit (it would drop the edit).
248
+ const replaceable = !inExpand && !node.edit;
249
+ if (node.type === 'text' && typeof node.value === 'string') {
250
+ if (node.value.trim() === '') {
251
+ out.push({
252
+ finding: finding('workaround.empty_text', path, 'An empty text node makes space.', 'Use a `divider` block, or remove the node.', replaceable ? { fixable: true } : {}),
253
+ replacement: replaceable ? { type: 'divider' } : undefined,
254
+ });
255
+ }
256
+ else {
257
+ const sign = ALERT_SIGN.exec(node.value);
258
+ if (sign) {
259
+ const text = node.value.slice(sign[0].length).trim();
260
+ const tone = sign[1] || sign[3] ? 'warning' : 'info';
261
+ const canFix = replaceable && text.length > 0 && text.length <= NODE_LIMITS.alert.text;
262
+ out.push({
263
+ finding: finding('workaround.text_alert', path, 'A text node with a sign in front stands in for an alert.', `Use an \`alert\` block with tone "${tone}".`, canFix ? { fixable: true } : {}),
264
+ replacement: canFix ? { type: 'alert', tone, text } : undefined,
265
+ });
266
+ }
267
+ }
268
+ }
269
+ if (node.type === 'markdown' && typeof node.value === 'string' && !node.edit) {
270
+ const link = ONLY_LINK.exec(node.value);
271
+ if (link) {
272
+ out.push({
273
+ finding: finding('workaround.markdown_link', path, 'A markdown node holds only one link.', 'Use a `link` block (href, and copy if the reader pastes it).', replaceable ? { fixable: true } : {}),
274
+ replacement: replaceable
275
+ ? { type: 'link', label: link[1].trim(), href: link[2] }
276
+ : undefined,
277
+ });
278
+ }
279
+ }
280
+ if (node.type === 'select' && Array.isArray(node.options) && node.options.length === 2) {
281
+ const labels = node.options
282
+ .map((option) => (isObject(option) ? String(option.label ?? '').toLowerCase() : ''))
283
+ .sort();
284
+ if (ON_OFF_PAIRS.some((pair) => [...pair].sort().join() === labels.join())) {
285
+ out.push({
286
+ finding: finding('workaround.on_off_select', path, 'A select with two options stands in for a switch.', 'Use a `toggle` block, or a form field of kind "checkbox".'),
287
+ });
288
+ }
289
+ }
290
+ if (node.type === 'table' && Array.isArray(node.columns) && node.columns.length === 2) {
291
+ const [first, second] = node.columns.map((column) => isObject(column) ? String(column.label ?? '').toLowerCase() : '');
292
+ if (KEY_LABELS.has(first) && second === 'value') {
293
+ out.push({
294
+ finding: finding('workaround.key_value_table', path, 'A two-column table of labels and values.', 'Use a `details` block.'),
295
+ });
296
+ }
297
+ }
298
+ if ((node.type === 'button' || node.type === 'select') &&
299
+ node.disabled === true &&
300
+ node.disabledReason === undefined &&
301
+ node.hint === undefined) {
302
+ out.push({
303
+ finding: finding('a11y.disabled_without_reason', path, 'A disabled control does not say why.', 'Add `disabledReason` (or a `hint`).'),
304
+ });
305
+ }
306
+ return out;
307
+ }
308
+ function clientSpecs(options) {
309
+ const clients = options.clients ?? ['web', 'mobile'];
310
+ return clients.map((spec) => typeof spec === 'string' ? { client: spec, version: latestRelease(spec).since } : spec);
311
+ }
312
+ const CORE_DRAWN = new Set(CORE_DRAWN_NODE_TYPES);
313
+ function bySeverityThenPath(a, b) {
314
+ if (a.severity !== b.severity)
315
+ return a.severity === 'error' ? -1 : 1;
316
+ if (a.path !== b.path)
317
+ return a.path < b.path ? -1 : 1;
318
+ if (a.rule !== b.rule)
319
+ return a.rule < b.rule ? -1 : 1;
320
+ return (a.client ?? '') < (b.client ?? '') ? -1 : (a.client ?? '') > (b.client ?? '') ? 1 : 0;
321
+ }
322
+ /**
323
+ * Check a screen tree, or a page that wraps one, before it is published. Never throws on bad
324
+ * input: an unparseable document is a finding.
325
+ */
326
+ export function checkPage(document, options = {}) {
327
+ const { tree, base, catalogId } = treeOf(document);
328
+ const knownTypes = new Set(options.catalog?.nodeTypes ?? KNOWN_NODE_TYPES);
329
+ const findings = [];
330
+ if (catalogId && options.catalog && catalogId !== options.catalog.catalogId) {
331
+ findings.push(finding('catalog.mismatch', 'catalogId', `The page was built against ${catalogId}; this check uses ${options.catalog.catalogId}.`, 'Check the page again and save it, so it names the catalog it was checked against.'));
332
+ }
333
+ const nodes = placedNodes(tree, base);
334
+ const walkedUnknown = new Set();
335
+ for (const { node, path } of nodes) {
336
+ if (typeof node.type === 'string' && !knownTypes.has(node.type)) {
337
+ walkedUnknown.add(path);
338
+ findings.push(finding('schema.unknown_node', path, `"${node.type}" is not a node type of this catalog`, 'Use a node the catalog lists (ui_catalog_get), or ask for the block you need.'));
339
+ }
340
+ }
341
+ const schema = schemaFindings(tree, base, walkedUnknown);
342
+ findings.push(...schema.findings);
343
+ if (options.bindings) {
344
+ const datasets = new Set(options.bindings.datasets);
345
+ for (const { node, path } of nodes) {
346
+ if (node.type === 'dataset' && typeof node.dataset === 'string') {
347
+ if (!datasets.has(node.dataset)) {
348
+ findings.push(finding('binding.dataset_unknown', `${path}.dataset`, `"${node.dataset}" is not a dataset the company has installed.`, 'Pick one of the installed datasets, or install the Pack that declares it.'));
349
+ }
350
+ }
351
+ }
352
+ const actions = new Set(options.bindings.actions);
353
+ const refs = [];
354
+ if (isObject(tree))
355
+ actionRefs(tree, base, actions, refs);
356
+ for (const ref of refs) {
357
+ findings.push(finding('binding.action_undeclared', ref.path, `"${ref.id}" is not an action an installed Pack declares.`, 'Pick a declared action by its stable id, or bind the page to the Pack that has it.'));
358
+ }
359
+ }
360
+ for (const placed of nodes)
361
+ findings.push(...workaroundsOf(placed).map((w) => w.finding));
362
+ if (schema.parsed) {
363
+ for (const { client, version } of clientSpecs(options)) {
364
+ const { fallbacks } = negotiateTree(schema.parsed, nodeSetForClient(client, version));
365
+ for (const fallback of fallbacks) {
366
+ if (CORE_DRAWN.has(fallback.type))
367
+ continue; // core draws it before any client sees it
368
+ const as = fallback.as === 'dropped'
369
+ ? 'nothing'
370
+ : fallback.as === 'folded'
371
+ ? 'an older form of it'
372
+ : `a ${fallback.as} fallback`;
373
+ findings.push(finding('reach.fallback', join(base, fallback.path), `${client} ${version} draws ${fallback.reason === 'node' ? fallback.type : fallback.reason} as ${as}.`, 'Use what the client draws, or accept the fallback for that client.', { client: `${client}@${version}` }));
374
+ }
375
+ }
376
+ }
377
+ findings.sort(bySeverityThenPath);
378
+ const errors = findings.filter((f) => f.severity === 'error').length;
379
+ const warnings = findings.length - errors;
380
+ if (findings.length > CHECK_LIMITS.findings) {
381
+ const total = findings.length;
382
+ findings.length = CHECK_LIMITS.findings;
383
+ findings.push(finding('check.truncated', '(root)', `${total} findings; the first ${CHECK_LIMITS.findings} are listed.`, 'Fix these and check again.'));
384
+ }
385
+ return { ok: errors === 0, errors, warnings, findings };
386
+ }
387
+ /**
388
+ * Make the changes the checker knows to be safe (each finding marked `fixable`) on a copy of the
389
+ * document, then check the copy. The input is never changed.
390
+ */
391
+ export function fixPage(document, options = {}) {
392
+ const copy = structuredClone(document);
393
+ const { tree, base } = treeOf(copy);
394
+ const fixed = [];
395
+ for (const placed of placedNodes(tree, base)) {
396
+ const fix = workaroundsOf(placed).find((w) => w.replacement);
397
+ if (!fix?.replacement)
398
+ continue;
399
+ placed.replace(fix.replacement);
400
+ fixed.push(fix.finding);
401
+ }
402
+ return { document: copy, fixed, result: checkPage(copy, options) };
403
+ }
404
+ /** One line per finding, for a terminal or a CI log. */
405
+ export function formatFinding(finding) {
406
+ const client = finding.client ? ` [${finding.client}]` : '';
407
+ return `${finding.severity.padEnd(7)} ${finding.rule} ${finding.path}${client} ${finding.message} Fix: ${finding.fix}`;
408
+ }
package/dist/cli.js CHANGED
@@ -3,6 +3,7 @@ import { watch } from 'node:fs';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { join } from 'node:path';
5
5
  import { buildModuleUi } from './build.js';
6
+ import { runCheckCli } from './check-cli.js';
6
7
  async function build() {
7
8
  const result = await buildModuleUi();
8
9
  if (result.removedScreens.length > 0) {
@@ -108,8 +109,11 @@ async function main() {
108
109
  const separator = args.indexOf('--');
109
110
  await dev(separator === -1 ? args : args.slice(separator + 1));
110
111
  }
112
+ else if (command === 'check') {
113
+ process.exitCode = runCheckCli(args);
114
+ }
111
115
  else {
112
- throw new Error('Usage: keemakr-ui build | keemakr-ui dev -- eve dev');
116
+ throw new Error('Usage: keemakr-ui build | keemakr-ui dev -- eve dev | keemakr-ui check <file.json>...');
113
117
  }
114
118
  }
115
119
  main().catch((error) => {
package/dist/define.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ActionResultInput, JobStatusInput, ScreenTreeInput, SurfaceDefinition } from './schema.js';
1
+ import type { ActionResultInput, JobStatusInput, ScreenCache, ScreenTreeInput, SurfaceDefinition } from './schema.js';
2
2
  export type ScreenParams = Record<string, string>;
3
3
  export type LoadHandler<Ctx> = (ctx: Ctx, params: ScreenParams) => ScreenTreeInput | Promise<ScreenTreeInput>;
4
4
  export type ActionHandler<Ctx> = (ctx: Ctx, input: Record<string, unknown>, params: ScreenParams) => ActionResultInput | Promise<ActionResultInput>;
@@ -13,6 +13,12 @@ export interface ScreenDefinition<Ctx = unknown> {
13
13
  actions?: Record<string, ActionHandler<Ctx>>;
14
14
  /** Needed only when an action returns `job`. Served at POST /screens/{screen}/jobs/{id}. */
15
15
  job?: JobHandler<Ctx>;
16
+ /**
17
+ * Let core keep this screen's tree for a repeat load by the same person, for up to `max_age_s`
18
+ * seconds (at most 3600), and load it again in the background (stale-while-revalidate). The
19
+ * build copies it into the manifest, so write it as a literal: `cache: { max_age_s: 60 }`.
20
+ */
21
+ cache?: ScreenCache;
16
22
  }
17
23
  /**
18
24
  * Identity function (the defineProvider pattern): exists for inference and
package/dist/define.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * agent tools — tenant and scopes come from the verified grant, never from
14
14
  * params.
15
15
  */
16
- import { surfaceDefinitionSchema } from './schema.js';
16
+ import { screenCacheSchema, surfaceDefinitionSchema } from './schema.js';
17
17
  const ACTION_KEY = /^[a-z][a-z0-9_-]*$/;
18
18
  /**
19
19
  * Identity function (the defineProvider pattern): exists for inference and
@@ -25,6 +25,8 @@ export function defineScreen(screen) {
25
25
  throw new Error(`defineScreen: action key "${key}" must be a lowercase slug (a-z, 0-9, -, _), max 64 chars`);
26
26
  }
27
27
  }
28
+ if (screen.cache !== undefined)
29
+ screenCacheSchema.parse(screen.cache);
28
30
  return screen;
29
31
  }
30
32
  /** Define surface metadata. The filesystem supplies its key, root screen, and child ownership. */
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { UI_SCHEMA_VERSION, pressSchema, chatPressSchema, valuePressSchema, NAVIGATE_OPENS, buttonSchema, cellSchema, factCellSchema, tableCellSchema, dateFormatSchema, nodeSchema, screenPresentationSchema, screenTreeSchema, actionResultSchema, screenLoadRequestSchema, screenLoadResponseSchema, screenActionRequestSchema, interfaceFamilySchema, surfaceDefinitionSchema, surfaceSchema, screenRegistrationSchema, uiManifestSchema, jobIdSchema, jobStatusSchema, screenJobRequestSchema, mediaPathSchema, seekPointSchema, seekPressSchema, focusPressSchema, appPressSchema, BADGE_COUNT_MAX, surfaceBadgeSchema, screenBadgesRequestSchema, screenBadgesResponseSchema, TABS_MAX, SECTION_ROLES, } from './schema.js';
2
- export type { Press, ChatPress, SeekPress, SeekPoint, FocusPress, AppPress, ValuePress, NavigatePress, PendingOpenOption, SectionRole, NavigateOpen, ScreenPresentation, ScreenNode, ScreenRootNode, ScreenTree, ActionResult, InterfaceFamily, SurfaceDefinition, Surface, ScreenRegistration, UiManifest, ScreenTreeInput, ActionResultInput, JobStatus, JobStatusInput, SurfaceBadge, SurfaceBadgeInput, ScreenBadgesRequest, ScreenBadgesResponse, } from './schema.js';
1
+ export { UI_SCHEMA_VERSION, pressSchema, chatPressSchema, valuePressSchema, NAVIGATE_OPENS, buttonSchema, cellSchema, factCellSchema, tableCellSchema, dateFormatSchema, nodeSchema, screenPresentationSchema, screenTreeSchema, actionResultSchema, screenLoadRequestSchema, screenLoadResponseSchema, screenActionRequestSchema, interfaceFamilySchema, surfaceDefinitionSchema, surfaceSchema, screenRegistrationSchema, screenCacheSchema, SCREEN_CACHE_MAX_AGE_S, uiManifestSchema, jobIdSchema, jobStatusSchema, screenJobRequestSchema, mediaPathSchema, mediaHostSchema, mediaHostsSchema, mediaUrlSchema, mediaSourceSchema, seekPointSchema, seekPressSchema, focusPressSchema, appPressSchema, BADGE_COUNT_MAX, surfaceBadgeSchema, screenBadgesRequestSchema, screenBadgesResponseSchema, TABS_MAX, SECTION_ROLES, } from './schema.js';
2
+ export type { Press, ChatPress, SeekPress, SeekPoint, FocusPress, AppPress, ValuePress, NavigatePress, PendingOpenOption, SectionRole, NavigateOpen, ScreenPresentation, ScreenNode, ScreenRootNode, ScreenTree, ActionResult, InterfaceFamily, SurfaceDefinition, Surface, ScreenRegistration, ScreenCache, UiManifest, ScreenTreeInput, ActionResultInput, JobStatus, JobStatusInput, SurfaceBadge, SurfaceBadgeInput, ScreenBadgesRequest, ScreenBadgesResponse, } from './schema.js';
3
3
  export { BADGE_DISPLAY_MAX, answerBadges, badgeSpokenLabel, badgeText, defineBadges, parseScreenBadges, } from './badges.js';
4
4
  export type { BadgesHandler } from './badges.js';
5
5
  export { CHART_POINTS_MAX, thinChart, thinnedIndices } from './chart.js';
@@ -16,8 +16,10 @@ export { SEARCH_DEBOUNCE_MS, SEARCH_MIN_LENGTH, liveSearchField, pressWithValues
16
16
  export type { LiveSearchFormLike, SearchTrigger } from './filters.js';
17
17
  export { CHANNEL_BUILDS, CLIENT_RELEASES, CORE_DRAWN_NODE_TYPES, CURRENT_SCHEMA_CLAIM, CURRENT_UI_SDK_SNAPSHOT, FLOOR_NODE_SET, GENERIC_FALLBACK_TEXT, SAFETY_FALLBACK_TEXT, UI_SDK_SNAPSHOTS, fallbackNode, isChatPress, latestRelease, negotiateTree, nodeSetForClaim, nodeSetForClient, uiSchemaClaimOf, } from './negotiate.js';
18
18
  export type { ChannelBuild, ClientRelease, ClientTarget, Fallback, NegotiatedTree, NodeSet, UiFeature, UiSchemaClaim, UiSdkSnapshot, } from './negotiate.js';
19
+ export { CORE_RENDERER, reachByClient } from './reach.js';
20
+ export type { ClientReach, ReachChannel, ReachLevel, ReachOptions, ReachTarget } from './reach.js';
19
21
  export { PUBLISHED_PARSERS, type PublishedParser } from './published/index.js';
20
- export { MEDIA_CONTENT_TYPES, mediaContentType, mediaPathOf } from './media.js';
22
+ export { MEDIA_CONTENT_TYPES, isMediaUrl, mediaContentType, mediaPathOf, mediaUrlAllowed, } from './media.js';
21
23
  export { PLAYBACK_RATES, SEEK_AT_MAX, formatPlayhead, isSeekPress, nextPlaybackRate, playbackRateLabel, playheadWords, seekTarget, seeksIn, } from './player.js';
22
24
  export type { PlaybackRate, PlayerKey, SeekReference } from './player.js';
23
25
  export { FOCUSABLE_FIELD_KINDS, focusIssue, focusesIn, isFocusPress } from './focus.js';
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // platform components, proxies load/action with a grant
7
7
  //
8
8
  // Module code never ships to the browser. UI is data, not code.
9
- export { UI_SCHEMA_VERSION, pressSchema, chatPressSchema, valuePressSchema, NAVIGATE_OPENS, buttonSchema, cellSchema, factCellSchema, tableCellSchema, dateFormatSchema, nodeSchema, screenPresentationSchema, screenTreeSchema, actionResultSchema, screenLoadRequestSchema, screenLoadResponseSchema, screenActionRequestSchema, interfaceFamilySchema, surfaceDefinitionSchema, surfaceSchema, screenRegistrationSchema, uiManifestSchema, jobIdSchema, jobStatusSchema, screenJobRequestSchema, mediaPathSchema, seekPointSchema, seekPressSchema, focusPressSchema, appPressSchema, BADGE_COUNT_MAX, surfaceBadgeSchema, screenBadgesRequestSchema, screenBadgesResponseSchema, TABS_MAX, SECTION_ROLES, } from './schema.js';
9
+ export { UI_SCHEMA_VERSION, pressSchema, chatPressSchema, valuePressSchema, NAVIGATE_OPENS, buttonSchema, cellSchema, factCellSchema, tableCellSchema, dateFormatSchema, nodeSchema, screenPresentationSchema, screenTreeSchema, actionResultSchema, screenLoadRequestSchema, screenLoadResponseSchema, screenActionRequestSchema, interfaceFamilySchema, surfaceDefinitionSchema, surfaceSchema, screenRegistrationSchema, screenCacheSchema, SCREEN_CACHE_MAX_AGE_S, uiManifestSchema, jobIdSchema, jobStatusSchema, screenJobRequestSchema, mediaPathSchema, mediaHostSchema, mediaHostsSchema, mediaUrlSchema, mediaSourceSchema, seekPointSchema, seekPressSchema, focusPressSchema, appPressSchema, BADGE_COUNT_MAX, surfaceBadgeSchema, screenBadgesRequestSchema, screenBadgesResponseSchema, TABS_MAX, SECTION_ROLES, } from './schema.js';
10
10
  export { BADGE_DISPLAY_MAX, answerBadges, badgeSpokenLabel, badgeText, defineBadges, parseScreenBadges, } from './badges.js';
11
11
  export { CHART_POINTS_MAX, thinChart, thinnedIndices } from './chart.js';
12
12
  export { TABS_MAX_1_4_0, foldTabs, onlyTabParamsDiffer, openingTab, tabParamsOf } from './tabs.js';
@@ -18,8 +18,9 @@ export { foldTableCell, isNewerTableCell, meterLabel, meterPercent } from './cel
18
18
  export { opensInDrawer, screenPlace } from './drawer.js';
19
19
  export { SEARCH_DEBOUNCE_MS, SEARCH_MIN_LENGTH, liveSearchField, pressWithValues, searchFires, searchPress, splitValues, toggleValue, } from './filters.js';
20
20
  export { CHANNEL_BUILDS, CLIENT_RELEASES, CORE_DRAWN_NODE_TYPES, CURRENT_SCHEMA_CLAIM, CURRENT_UI_SDK_SNAPSHOT, FLOOR_NODE_SET, GENERIC_FALLBACK_TEXT, SAFETY_FALLBACK_TEXT, UI_SDK_SNAPSHOTS, fallbackNode, isChatPress, latestRelease, negotiateTree, nodeSetForClaim, nodeSetForClient, uiSchemaClaimOf, } from './negotiate.js';
21
+ export { CORE_RENDERER, reachByClient } from './reach.js';
21
22
  export { PUBLISHED_PARSERS } from './published/index.js';
22
- export { MEDIA_CONTENT_TYPES, mediaContentType, mediaPathOf } from './media.js';
23
+ export { MEDIA_CONTENT_TYPES, isMediaUrl, mediaContentType, mediaPathOf, mediaUrlAllowed, } from './media.js';
23
24
  export { PLAYBACK_RATES, SEEK_AT_MAX, formatPlayhead, isSeekPress, nextPlaybackRate, playbackRateLabel, playheadWords, seekTarget, seeksIn, } from './player.js';
24
25
  export { FOCUSABLE_FIELD_KINDS, focusIssue, focusesIn, isFocusPress } from './focus.js';
25
26
  export { APP_DESTINATIONS, APPOINTMENT_PARAM, appPressPath, isAppPress } from './app-press.js';
package/dist/media.d.ts CHANGED
@@ -8,3 +8,15 @@ export declare function mediaContentType(path: string): string | null;
8
8
  * `mediaPathOf(new URL(req.url).pathname)`.
9
9
  */
10
10
  export declare function mediaPathOf(pathname: string): string | null;
11
+ /**
12
+ * True when a media block's `src` (or `poster`) is a URL rather than a path in
13
+ * the module's runtime. Renderers use it to pick core's URL route over the path
14
+ * route; anything with a scheme other than https is never loaded.
15
+ */
16
+ export declare function isMediaUrl(src: string): boolean;
17
+ /**
18
+ * Whether a media URL may be shown: https, valid, and on one of the module's
19
+ * `mediaHosts` exactly. Core applies this to every screen tree before a viewer
20
+ * sees it, and again when it is asked to fetch the file.
21
+ */
22
+ export declare function mediaUrlAllowed(src: string, hosts: readonly string[]): boolean;
package/dist/media.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // capability grant exactly as its load and action routes do. Core fetches from
4
4
  // there and passes on only these types, so a module that labels a file with
5
5
  // any other type gets a broken image, not a security hole.
6
- import { mediaPathSchema } from './schema.js';
6
+ import { mediaPathSchema, mediaUrlSchema } from './schema.js';
7
7
  /** The types core passes on, by file extension. */
8
8
  export const MEDIA_CONTENT_TYPES = {
9
9
  png: 'image/png',
@@ -46,3 +46,21 @@ export function mediaPathOf(pathname) {
46
46
  }
47
47
  return mediaPathSchema.safeParse(path).success ? path : null;
48
48
  }
49
+ /**
50
+ * True when a media block's `src` (or `poster`) is a URL rather than a path in
51
+ * the module's runtime. Renderers use it to pick core's URL route over the path
52
+ * route; anything with a scheme other than https is never loaded.
53
+ */
54
+ export function isMediaUrl(src) {
55
+ return src.includes(':');
56
+ }
57
+ /**
58
+ * Whether a media URL may be shown: https, valid, and on one of the module's
59
+ * `mediaHosts` exactly. Core applies this to every screen tree before a viewer
60
+ * sees it, and again when it is asked to fetch the file.
61
+ */
62
+ export function mediaUrlAllowed(src, hosts) {
63
+ if (!mediaUrlSchema.safeParse(src).success)
64
+ return false;
65
+ return hosts.includes(new URL(src).hostname);
66
+ }
@@ -117,8 +117,16 @@ import type { ChatPress, ScreenRootNode, ScreenTree } from './schema.js';
117
117
  * action (newer than any published release; core's own renderer draws them). Without it, the
118
118
  * role is dropped: a controls band is the `row` section it already is, and a thread keeps
119
119
  * scrolling as a `scroll` section, opening at its top.
120
+ * - `media.url`: an `image` src, or a `video` src or poster, that is a signed https URL on one of
121
+ * the module's `manifest.mediaHosts` (KEE-989), which the client loads through core's URL
122
+ * media route (`<media base>?src=<url>`), never from the host (newer than any published
123
+ * release; core's own renderer draws it). A published parse refuses a URL there, and an older
124
+ * renderer would ask core's path route for it. Without it, an image or a video with a URL src
125
+ * becomes its stand-in line (`fallbackNode`: the image's alt, "Video: <title>"), and a URL
126
+ * poster on a video whose src is a path is dropped. Core removes every URL not on the
127
+ * module's list (or every URL, with the registry key `ui.media-urls` off) before this runs.
120
128
  */
121
- export type UiFeature = 'breadcrumbs' | 'button.disabled' | 'section.row' | 'form.field_kinds' | 'form.confirm' | 'press.chat' | 'form.radio' | 'table.cells' | 'header.meta' | 'tabs.many' | 'choice.action' | 'markdown.links' | 'form.disabled' | 'press.seek' | 'edit.inline' | 'timeline.time_tag' | 'stat.bar' | 'stat.sparkline' | 'section.action' | 'facts.meter' | 'form.show_when' | 'press.focus' | 'press.app' | 'pending.open' | 'form.allowed_days' | 'section.roles';
129
+ export type UiFeature = 'breadcrumbs' | 'button.disabled' | 'section.row' | 'form.field_kinds' | 'form.confirm' | 'press.chat' | 'form.radio' | 'table.cells' | 'header.meta' | 'tabs.many' | 'choice.action' | 'markdown.links' | 'form.disabled' | 'press.seek' | 'edit.inline' | 'timeline.time_tag' | 'stat.bar' | 'stat.sparkline' | 'section.action' | 'facts.meter' | 'form.show_when' | 'press.focus' | 'press.app' | 'pending.open' | 'form.allowed_days' | 'section.roles' | 'media.url';
122
130
  /** The node types and features one ui-sdk release, or one client, draws. */
123
131
  export interface NodeSet {
124
132
  /** For messages: "ui-sdk 1.4.0", "mobile 0.2.5". */
@@ -155,7 +163,7 @@ export declare const UI_SDK_SNAPSHOTS: {
155
163
  readonly current: {
156
164
  readonly name: "ui-sdk (this package)";
157
165
  readonly nodes: readonly ["heading", "text", "markdown", "stat", "button", "form", "table", "timeline", "pending_request", "pending_requests", "choice_cards", "progress", "chart", "section", "tabs", "pagination", "select", "alert", "details", "timestamp", "divider", "board", "link", "tags", "toggle", "segmented", "progress_bar", "conversation", "composer", "calendar", "image", "video", "stacked_bar", "heatmap", "audio", "document"];
158
- readonly features: readonly ["breadcrumbs", "button.disabled", "section.row", "form.field_kinds", "form.confirm", "press.chat", "form.radio", "table.cells", "header.meta", "tabs.many", "choice.action", "markdown.links", "form.disabled", "press.seek", "edit.inline", "timeline.time_tag", "stat.bar", "stat.sparkline", "section.action", "facts.meter", "form.show_when", "press.focus", "press.app", "pending.open", "form.allowed_days", "section.roles"];
166
+ readonly features: readonly ["breadcrumbs", "button.disabled", "section.row", "form.field_kinds", "form.confirm", "press.chat", "form.radio", "table.cells", "header.meta", "tabs.many", "choice.action", "markdown.links", "form.disabled", "press.seek", "edit.inline", "timeline.time_tag", "stat.bar", "stat.sparkline", "section.action", "facts.meter", "form.show_when", "press.focus", "press.app", "pending.open", "form.allowed_days", "section.roles", "media.url"];
159
167
  };
160
168
  };
161
169
  export type UiSdkSnapshot = keyof typeof UI_SDK_SNAPSHOTS;
@@ -359,4 +367,5 @@ export declare function fallbackNode(node: ScreenRootNode | {
359
367
  }, timeZone?: string): FallbackNode;
360
368
  /** Module text is plain text: escape it so it reads the same inside a markdown fallback. */
361
369
  export declare function escapeMarkdown(value: string): string;
370
+ export declare function compareVersions(a: string, b: string): number;
362
371
  export {};
package/dist/negotiate.js CHANGED
@@ -26,6 +26,7 @@ import { conformTree } from './conform.js';
26
26
  import { isAppPress } from './app-press.js';
27
27
  import { isFocusPress } from './focus.js';
28
28
  import { withoutScreenLinks } from './markdown-links.js';
29
+ import { isMediaUrl } from './media.js';
29
30
  import { pageRangeLabel } from './pager.js';
30
31
  import { formatPlayhead, isSeekPress } from './player.js';
31
32
  import { stackedBarParts } from './stacked-bar.js';
@@ -63,6 +64,7 @@ const ALL_FEATURES = [
63
64
  'pending.open',
64
65
  'form.allowed_days',
65
66
  'section.roles',
67
+ 'media.url',
66
68
  ];
67
69
  /** The nodes of ui-sdk 1.1.0 and 1.2.0 (one schema). */
68
70
  const NODES_1_1_0 = [
@@ -465,6 +467,27 @@ export function negotiateTree(tree, set) {
465
467
  hint: clip(tile.hint ? `${tile.hint} · ${legend}` : legend, STAT_HINT_MAX),
466
468
  };
467
469
  }
470
+ case 'image':
471
+ case 'video': {
472
+ if (features.has('media.url'))
473
+ return node;
474
+ if (isMediaUrl(node.src)) {
475
+ const replacement = fallbackNode(node, zone);
476
+ fallbacks.push({ path, type: node.type, reason: 'media.url', as: replacement.type });
477
+ return replacement;
478
+ }
479
+ if (node.type === 'video' && node.poster && isMediaUrl(node.poster)) {
480
+ fallbacks.push({
481
+ path: `${path}.poster`,
482
+ type: 'video',
483
+ reason: 'media.url',
484
+ as: 'dropped',
485
+ });
486
+ const { poster: _poster, ...video } = node;
487
+ return video;
488
+ }
489
+ return node;
490
+ }
468
491
  case 'choice_cards':
469
492
  return features.has('choice.action') ? node : foldChoiceActions(node, path, fallbacks);
470
493
  case 'timeline':
@@ -1294,7 +1317,7 @@ function parseVersion(version) {
1294
1317
  return null;
1295
1318
  return [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)];
1296
1319
  }
1297
- function compareVersions(a, b) {
1320
+ export function compareVersions(a, b) {
1298
1321
  const pa = parseVersion(a) ?? [0, 0, 0];
1299
1322
  const pb = parseVersion(b) ?? [0, 0, 0];
1300
1323
  for (let i = 0; i < 3; i += 1) {