@khanglvm/relay 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +4 -4
  3. package/src/cli/args.js +46 -0
  4. package/src/cli/ask.js +12 -0
  5. package/src/cli/boards.js +326 -0
  6. package/src/cli/config.js +56 -0
  7. package/src/cli/context.js +13 -0
  8. package/src/cli/git.js +183 -0
  9. package/src/cli/help.js +90 -0
  10. package/src/cli/index.js +103 -0
  11. package/src/cli/install.js +197 -0
  12. package/src/cli/io.js +186 -0
  13. package/src/cli/mcp.js +94 -0
  14. package/src/cli/share.js +45 -0
  15. package/src/cli/skill.js +192 -0
  16. package/src/cli/upgrade.js +130 -0
  17. package/src/cli/wait.js +172 -0
  18. package/src/file-preview.js +1 -1
  19. package/src/index.js +1 -1
  20. package/src/mcp-ui/board/block-ctx.js +43 -0
  21. package/src/mcp-ui/board/bridge.js +165 -0
  22. package/src/mcp-ui/board/controls.js +310 -0
  23. package/src/mcp-ui/board/core.js +20 -0
  24. package/src/mcp-ui/board/lifecycle.js +118 -0
  25. package/src/mcp-ui/board/normalize.js +95 -0
  26. package/src/mcp-ui/board/render.js +200 -0
  27. package/src/mcp-ui/board/state.js +106 -0
  28. package/src/mcp-ui/board/vendors.js +86 -0
  29. package/src/mcp.js +12 -18
  30. package/src/{server.js → server/board.js} +15 -778
  31. package/src/server/files.js +141 -0
  32. package/src/server/http.js +114 -0
  33. package/src/server/index.js +2 -0
  34. package/src/server/page.js +183 -0
  35. package/src/server/paths.js +7 -0
  36. package/src/server/result.js +58 -0
  37. package/src/server/reviews.js +41 -0
  38. package/src/server/sanitize.js +231 -0
  39. package/src/spec/blocks/a2ui.js +25 -0
  40. package/src/spec/blocks/chart.js +49 -0
  41. package/src/spec/blocks/code.js +38 -0
  42. package/src/spec/blocks/diagram.js +39 -0
  43. package/src/spec/blocks/git-conflict.js +106 -0
  44. package/src/spec/blocks/image.js +32 -0
  45. package/src/spec/blocks/index.js +33 -0
  46. package/src/spec/blocks/markdown.js +13 -0
  47. package/src/spec/blocks/pdf.js +38 -0
  48. package/src/spec/blocks/table.js +122 -0
  49. package/src/spec/blocks/video.js +68 -0
  50. package/src/spec/blocks/widgets.js +98 -0
  51. package/src/spec/constants.js +65 -0
  52. package/src/spec/index.js +5 -0
  53. package/src/spec/normalize.js +285 -0
  54. package/src/spec/ready.js +106 -0
  55. package/src/spec/schema.js +182 -0
  56. package/src/spec/sources.js +83 -0
  57. package/src/ui/annotate/api.js +149 -0
  58. package/src/ui/annotate/badges.js +77 -0
  59. package/src/ui/annotate/chrome.js +158 -0
  60. package/src/ui/annotate/core.js +134 -0
  61. package/src/ui/annotate/highlights.js +129 -0
  62. package/src/ui/annotate/mutations.js +127 -0
  63. package/src/ui/annotate/popover.js +206 -0
  64. package/src/ui/annotate/summary.js +67 -0
  65. package/src/ui/app/annotations.js +88 -0
  66. package/src/ui/app/autosave.js +44 -0
  67. package/src/ui/app/core.js +74 -0
  68. package/src/ui/app/drafts.js +201 -0
  69. package/src/ui/app/heartbeat.js +150 -0
  70. package/src/ui/app/iframe-bridge.js +64 -0
  71. package/src/ui/app/persistence.js +117 -0
  72. package/src/ui/app/prefilled.js +21 -0
  73. package/src/ui/app/presence.js +38 -0
  74. package/src/ui/app/question-color.js +67 -0
  75. package/src/ui/app/questions.js +360 -0
  76. package/src/ui/app/render.js +135 -0
  77. package/src/ui/app/share.js +108 -0
  78. package/src/ui/app/submit.js +109 -0
  79. package/src/ui/app/theme.js +63 -0
  80. package/src/ui/blocks/api.js +1 -0
  81. package/src/ui/blocks/chart.js +222 -0
  82. package/src/ui/blocks/code.js +138 -0
  83. package/src/ui/blocks/compare.js +82 -0
  84. package/src/ui/blocks/core.js +74 -0
  85. package/src/ui/blocks/diff.js +361 -0
  86. package/src/ui/blocks/dispatch.js +111 -0
  87. package/src/ui/blocks/file-links.js +180 -0
  88. package/src/ui/blocks/git-conflict.js +151 -0
  89. package/src/ui/blocks/graphviz.js +57 -0
  90. package/src/ui/blocks/html.js +45 -0
  91. package/src/ui/blocks/image.js +371 -0
  92. package/src/ui/blocks/kpi.js +26 -0
  93. package/src/ui/blocks/markdown.js +223 -0
  94. package/src/ui/blocks/mermaid.js +242 -0
  95. package/src/ui/blocks/palette.js +59 -0
  96. package/src/ui/blocks/pdf.js +21 -0
  97. package/src/ui/blocks/plantuml.js +152 -0
  98. package/src/ui/blocks/table.js +155 -0
  99. package/src/ui/blocks/typography.js +25 -0
  100. package/src/ui/blocks/vendor.js +43 -0
  101. package/src/ui/blocks/video.js +43 -0
  102. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  103. package/src/ui/blocks/viewer.js +324 -0
  104. package/src/ui/kit.js +1 -0
  105. package/src/ui/manifest.js +140 -0
  106. package/types/index.d.ts +1 -1
  107. package/types/spec/blocks/a2ui.d.ts +4 -0
  108. package/types/spec/blocks/chart.d.ts +4 -0
  109. package/types/spec/blocks/code.d.ts +10 -0
  110. package/types/spec/blocks/diagram.d.ts +15 -0
  111. package/types/spec/blocks/git-conflict.d.ts +7 -0
  112. package/types/spec/blocks/image.d.ts +5 -0
  113. package/types/spec/blocks/index.d.ts +30 -0
  114. package/types/spec/blocks/markdown.d.ts +5 -0
  115. package/types/spec/blocks/pdf.d.ts +4 -0
  116. package/types/spec/blocks/table.d.ts +9 -0
  117. package/types/spec/blocks/video.d.ts +4 -0
  118. package/types/spec/blocks/widgets.d.ts +21 -0
  119. package/types/spec/constants.d.ts +67 -0
  120. package/types/spec/index.d.ts +4 -0
  121. package/types/spec/normalize.d.ts +17 -0
  122. package/types/spec/ready.d.ts +1 -0
  123. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  124. package/types/spec/sources.d.ts +14 -0
  125. package/types/ui/manifest.d.ts +62 -0
  126. package/src/cli.js +0 -1767
  127. package/src/mcp-ui/board.js +0 -1162
  128. package/src/spec.js +0 -1224
  129. package/src/ui/annotate.js +0 -1055
  130. package/src/ui/app.js +0 -1643
  131. package/src/ui/blocks.js +0 -3260
package/src/spec.js DELETED
@@ -1,1224 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import vm from 'node:vm';
4
- import { fileURLToPath } from 'node:url';
5
- import { CliError } from './util.js';
6
- import { assertSafeJson, guardExpress, resolveA2uiBlock, validateSurface } from './a2ui/compile.js';
7
-
8
- export const TYPES = ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate'];
9
-
10
- const ALIASES = {
11
- radio: 'single',
12
- choice: 'single',
13
- select: 'single',
14
- checkbox: 'multi',
15
- checkboxes: 'multi',
16
- boolean: 'yesno',
17
- bool: 'yesno',
18
- yn: 'yesno',
19
- input: 'text',
20
- string: 'text',
21
- longtext: 'textarea',
22
- long: 'textarea',
23
- rating: 'scale',
24
- likert: 'scale',
25
- colour: 'color',
26
- swatch: 'color',
27
- ranking: 'rank',
28
- order: 'rank',
29
- ordering: 'rank',
30
- prioritize: 'rank',
31
- sort: 'rank',
32
- signoff: 'checklist',
33
- 'sign-off': 'checklist',
34
- qa: 'checklist',
35
- allocation: 'allocate',
36
- budget: 'allocate',
37
- distribute: 'allocate',
38
- points: 'allocate',
39
- };
40
-
41
- const HTML_HEIGHT = { min: 100, max: 2400, boardDefault: 400, questionDefault: 360 };
42
-
43
- // Block heights clamp to the same window; defaults vary per block type.
44
- const BLOCK_HEIGHT = { min: 100, max: 2400 };
45
- export const BLOCK_TYPES = ['markdown', 'mermaid', 'graphviz', 'plantuml', 'chart', 'table', 'code', 'diff', 'git-conflict', 'video', 'pdf', 'html', 'image', 'palette', 'kpi', 'typography', 'compare', 'a2ui'];
46
- const CHART_KINDS = ['bar', 'line', 'pie', 'doughnut', 'radar', 'scatter'];
47
-
48
- // code/diff blocks may load their text from a local file (like htmlFile). Caps
49
- // keep a runaway file from bloating the board payload.
50
- const TEXT_FILE_MAX_BYTES = 512 * 1024;
51
-
52
- // video blocks: a YouTube/Vimeo link embeds via iframe; an http(s) media URL or
53
- // a local file plays in a <video> element (local files stream from the server,
54
- // never embedded, so large clips don't bloat the board).
55
- const VIDEO_MIMES = {
56
- mp4: 'video/mp4', m4v: 'video/x-m4v', webm: 'video/webm', ogv: 'video/ogg',
57
- ogg: 'video/ogg', mov: 'video/quicktime', mkv: 'video/x-matroska',
58
- };
59
- const VIDEO_MAX_BYTES = 512 * 1024 * 1024;
60
-
61
- const PDF_MIME = 'application/pdf';
62
- const PDF_MAX_BYTES = 512 * 1024 * 1024;
63
-
64
- // image blocks: local files are embedded as data URIs at spec time (the page
65
- // then loads them via /img/b/<id>), so boards stay self-contained offline.
66
- const IMAGE_MIMES = {
67
- png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
68
- webp: 'image/webp', svg: 'image/svg+xml', avif: 'image/avif', bmp: 'image/bmp',
69
- };
70
- const IMAGE_MAX_BYTES = 8 * 1024 * 1024;
71
- const VENDOR_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'vendor');
72
-
73
- let mermaidValidatorPromise = null;
74
-
75
- const asStr = (v) => (typeof v === 'string' ? v : v == null ? '' : String(v));
76
-
77
- function clampInt(v, min, max, def) {
78
- const n = Number.parseInt(v, 10);
79
- if (!Number.isFinite(n)) return def;
80
- return Math.min(max, Math.max(min, n));
81
- }
82
-
83
- function readHtml(obj, cwd, where) {
84
- if (typeof obj.html === 'string' && obj.html.trim()) return obj.html;
85
- if (typeof obj.htmlFile === 'string' && obj.htmlFile.trim()) {
86
- const p = path.resolve(cwd, obj.htmlFile);
87
- try {
88
- return fs.readFileSync(p, 'utf8');
89
- } catch {
90
- throw new CliError(`${where}: cannot read htmlFile "${obj.htmlFile}" (resolved: ${p})`);
91
- }
92
- }
93
- return '';
94
- }
95
-
96
- // Reads an html-block body from either an inline string or a file path.
97
- function readBlockHtml(block, cwd, where) {
98
- if (typeof block.html === 'string' && block.html) return block.html;
99
- if (typeof block.htmlFile === 'string' && block.htmlFile.trim()) {
100
- const p = path.resolve(cwd, block.htmlFile);
101
- try {
102
- return fs.readFileSync(p, 'utf8');
103
- } catch {
104
- throw new CliError(`${where}: cannot read htmlFile "${block.htmlFile}" (resolved: ${p})`);
105
- }
106
- }
107
- return '';
108
- }
109
-
110
- // Reads a code/diff block body from an inline string field or a local file.
111
- // `inlineKey` is the inline field (e.g. "code"/"diff"); `fileKey` its file
112
- // twin (e.g. "codeFile"/"diffFile"). Returns '' when neither is present.
113
- function readTextSource(block, inlineKey, fileKey, cwd, where) {
114
- if (typeof block[inlineKey] === 'string' && block[inlineKey] !== '') return block[inlineKey];
115
- if (typeof block[fileKey] === 'string' && block[fileKey].trim()) {
116
- const p = path.resolve(cwd, block[fileKey]);
117
- let buf;
118
- try {
119
- buf = fs.readFileSync(p);
120
- } catch {
121
- throw new CliError(`${where}: cannot read ${fileKey} "${block[fileKey]}" (resolved: ${p})`);
122
- }
123
- if (buf.length > TEXT_FILE_MAX_BYTES) {
124
- throw new CliError(`${where}: ${fileKey} "${block[fileKey]}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
125
- }
126
- return buf.toString('utf8');
127
- }
128
- return '';
129
- }
130
-
131
- function readAnyTextSource(block, inlineKeys, fileKeys, cwd, where, label) {
132
- for (const key of inlineKeys) {
133
- if (typeof block[key] === 'string' && block[key] !== '') return { text: block[key], sourceKey: key };
134
- }
135
- for (const key of fileKeys) {
136
- if (typeof block[key] === 'string' && block[key].trim()) {
137
- const p = path.resolve(cwd, block[key]);
138
- let buf;
139
- try {
140
- buf = fs.readFileSync(p);
141
- } catch {
142
- throw new CliError(`${where}: cannot read ${label} "${block[key]}" (resolved: ${p})`);
143
- }
144
- if (buf.length > TEXT_FILE_MAX_BYTES) {
145
- throw new CliError(`${where}: ${label} "${block[key]}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
146
- }
147
- return { text: buf.toString('utf8'), sourceKey: key, file: p };
148
- }
149
- }
150
- return { text: '', sourceKey: '' };
151
- }
152
-
153
- function joinConflictLines(lines) {
154
- return lines.join('\n');
155
- }
156
-
157
- function parseGitConflictContent(content, where) {
158
- const lines = String(content || '').replace(/\r\n?/g, '\n').split('\n');
159
- const parts = [];
160
- const conflicts = [];
161
- let textBuf = [];
162
- const flushText = () => {
163
- if (!textBuf.length) return;
164
- parts.push({ type: 'text', text: joinConflictLines(textBuf) });
165
- textBuf = [];
166
- };
167
-
168
- for (let i = 0; i < lines.length; i++) {
169
- const start = lines[i].match(/^<<<<<<<(?:\s+(.*))?$/);
170
- if (!start) {
171
- textBuf.push(lines[i]);
172
- continue;
173
- }
174
-
175
- flushText();
176
- const oursLabel = start[1] || 'ours';
177
- const ours = [];
178
- const base = [];
179
- const theirs = [];
180
- let baseLabel = '';
181
- let theirsLabel = 'theirs';
182
- let section = 'ours';
183
- let closed = false;
184
-
185
- for (i = i + 1; i < lines.length; i++) {
186
- const line = lines[i];
187
- const baseStart = line.match(/^\|\|\|\|\|\|\|(?:\s+(.*))?$/);
188
- if (baseStart && section === 'ours') {
189
- baseLabel = baseStart[1] || 'base';
190
- section = 'base';
191
- continue;
192
- }
193
- if (/^=======$/.test(line) && (section === 'ours' || section === 'base')) {
194
- section = 'theirs';
195
- continue;
196
- }
197
- const end = line.match(/^>>>>>>>(?:\s+(.*))?$/);
198
- if (end && section === 'theirs') {
199
- theirsLabel = end[1] || theirsLabel;
200
- closed = true;
201
- break;
202
- }
203
- if (section === 'ours') ours.push(line);
204
- else if (section === 'base') base.push(line);
205
- else theirs.push(line);
206
- }
207
-
208
- if (!closed) {
209
- throw new CliError(`${where}: conflict marker starting at line ${conflicts.length + 1} is missing a matching >>>>>>> marker.`);
210
- }
211
- const id = `c${conflicts.length + 1}`;
212
- conflicts.push({
213
- id,
214
- oursLabel,
215
- theirsLabel,
216
- ...(baseLabel ? { baseLabel } : {}),
217
- ours: joinConflictLines(ours),
218
- theirs: joinConflictLines(theirs),
219
- ...(baseLabel ? { base: joinConflictLines(base) } : {}),
220
- });
221
- parts.push({ type: 'conflict', conflictId: id });
222
- }
223
-
224
- flushText();
225
- return { conflicts, parts };
226
- }
227
-
228
- // Resolve an image source (shared by the `image` and `compare` blocks): an
229
- // http(s)/data URL passes through; a local file is read + embedded as a data
230
- // URI (capped) so the board stays self-contained offline.
231
- function resolveImageSrc(srcRaw, cwd, where, field) {
232
- const src = asStr(srcRaw).trim();
233
- if (!src) throw new CliError(`${where}: ${field} needs a "src" (http(s)/data URL or local file path).`);
234
- if (/^(https?:|data:)/i.test(src)) return src;
235
- const p = path.resolve(cwd, src);
236
- const ext = path.extname(p).slice(1).toLowerCase();
237
- const mime = IMAGE_MIMES[ext];
238
- if (!mime) throw new CliError(`${where}: ${field}: unsupported image extension ".${ext}" — use ${Object.keys(IMAGE_MIMES).join('/')}, or an http(s)/data URL.`);
239
- let buf;
240
- try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: ${field}: cannot read image "${src}" (resolved: ${p})`); }
241
- if (buf.length > IMAGE_MAX_BYTES) throw new CliError(`${where}: ${field}: image "${src}" is ${(buf.length / 1024 / 1024).toFixed(1)}MB — max ${IMAGE_MAX_BYTES / 1024 / 1024}MB.`);
242
- return `data:${mime};base64,${buf.toString('base64')}`;
243
- }
244
-
245
- // Minimal RFC-4180-ish CSV/TSV parser: handles quoted fields containing the
246
- // delimiter, embedded newlines, and "" escaped quotes. Returns an array of rows
247
- // (each an array of string cells). Library-free.
248
- function parseDelimited(text, delim) {
249
- const rows = [];
250
- let row = [];
251
- let field = '';
252
- let inQ = false;
253
- const pushField = () => { row.push(field); field = ''; };
254
- const pushRow = () => { pushField(); rows.push(row); row = []; };
255
- for (let i = 0; i < text.length; i++) {
256
- const c = text[i];
257
- if (inQ) {
258
- if (c === '"') {
259
- if (text[i + 1] === '"') { field += '"'; i++; } else inQ = false;
260
- } else field += c;
261
- continue;
262
- }
263
- if (c === '"') inQ = true;
264
- else if (c === delim) pushField();
265
- else if (c === '\n') pushRow();
266
- else if (c === '\r') { /* swallow CR (CRLF) */ }
267
- else field += c;
268
- }
269
- if (field.length || row.length) pushRow();
270
- // drop a single trailing empty row from a final newline
271
- if (rows.length && rows[rows.length - 1].length === 1 && rows[rows.length - 1][0] === '') rows.pop();
272
- return rows;
273
- }
274
-
275
- // Load table {columns, rows} from a local .csv/.tsv/.json file (rowsFile).
276
- // CSV/TSV: first row = header → column keys. JSON: an array of objects (columns
277
- // from the union of keys) or arrays (needs explicit "columns").
278
- function loadRowsFile(file, cwd, where) {
279
- const p = path.resolve(cwd, file);
280
- let buf;
281
- try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: cannot read rowsFile "${file}" (resolved: ${p})`); }
282
- if (buf.length > TEXT_FILE_MAX_BYTES) {
283
- throw new CliError(`${where}: rowsFile "${file}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
284
- }
285
- const text = buf.toString('utf8');
286
- const ext = path.extname(p).slice(1).toLowerCase();
287
- if (ext === 'json') {
288
- let data;
289
- try { data = JSON.parse(text); } catch (e) { throw new CliError(`${where}: rowsFile "${file}" JSON parse error: ${e.message}`); }
290
- if (!Array.isArray(data)) throw new CliError(`${where}: rowsFile "${file}" JSON must be an array of rows.`);
291
- const cols = [];
292
- for (const r of data) {
293
- if (r && typeof r === 'object' && !Array.isArray(r)) {
294
- for (const k of Object.keys(r)) if (!cols.includes(k)) cols.push(k);
295
- }
296
- }
297
- return { columns: cols, rows: data };
298
- }
299
- const parsed = parseDelimited(text, ext === 'tsv' ? '\t' : ',');
300
- if (!parsed.length) return { columns: [], rows: [] };
301
- const header = parsed[0].map((h) => String(h).trim());
302
- const rows = parsed.slice(1).map((cells) => {
303
- const obj = {};
304
- header.forEach((h, i) => { obj[h] = cells[i] !== undefined ? cells[i] : ''; });
305
- return obj;
306
- });
307
- return { columns: header, rows };
308
- }
309
-
310
- // Recognizes a YouTube / Vimeo URL (or a bare YouTube id) and returns
311
- // {provider, videoId, start} for an iframe embed, else null. Cross-platform —
312
- // pure string parsing, no URL host assumptions beyond the known providers.
313
- function parseVideoEmbed(src) {
314
- const s = String(src).trim();
315
- // bare 11-char YouTube id
316
- if (/^[\w-]{11}$/.test(s)) return { provider: 'youtube', videoId: s, start: 0 };
317
- let m;
318
- if ((m = s.match(/(?:youtube\.com\/(?:watch\?(?:.*&)?v=|embed\/|shorts\/|v\/)|youtu\.be\/)([\w-]{11})/i))) {
319
- const t = s.match(/[?&](?:t|start)=(\d+)/);
320
- return { provider: 'youtube', videoId: m[1], start: t ? Number(t[1]) : 0 };
321
- }
322
- if ((m = s.match(/vimeo\.com\/(?:video\/)?(\d+)/i))) {
323
- return { provider: 'vimeo', videoId: m[1], start: 0 };
324
- }
325
- return null;
326
- }
327
-
328
- function compactError(err) {
329
- const raw = err && (err.str || err.message) ? (err.str || err.message) : String(err || 'unknown error');
330
- const msg = String(raw).replace(/\s+/g, ' ').trim();
331
- return msg.length > 500 ? msg.slice(0, 497) + '...' : msg;
332
- }
333
-
334
- async function mermaidValidator() {
335
- if (mermaidValidatorPromise) return mermaidValidatorPromise;
336
- mermaidValidatorPromise = (async () => {
337
- const sourcePath = path.join(VENDOR_DIR, 'mermaid.min.js');
338
- let source;
339
- try {
340
- source = fs.readFileSync(sourcePath, 'utf8');
341
- } catch {
342
- throw new CliError('mermaid blocks need the vendored parser (vendor/mermaid.min.js is missing).');
343
- }
344
- const quietConsole = { log() {}, info() {}, warn() {}, error() {}, debug() {} };
345
- const context = {
346
- console: quietConsole,
347
- setTimeout,
348
- clearTimeout,
349
- };
350
- context.globalThis = context;
351
- context.window = { addEventListener() {} };
352
- vm.createContext(context);
353
- try {
354
- vm.runInContext(source, context, { filename: sourcePath });
355
- } catch (err) {
356
- throw new CliError(`could not load mermaid parser: ${compactError(err)}`);
357
- }
358
- if (!context.mermaid || typeof context.mermaid.parse !== 'function') {
359
- throw new CliError('could not load mermaid parser: vendor/mermaid.min.js did not expose mermaid.parse.');
360
- }
361
- try {
362
- context.mermaid.initialize({
363
- startOnLoad: false,
364
- securityLevel: 'strict',
365
- suppressErrorRendering: true,
366
- });
367
- } catch {
368
- // Some Mermaid versions dislike repeated initialize calls; parse below is
369
- // the real readiness gate.
370
- }
371
- return context.mermaid;
372
- })();
373
- return mermaidValidatorPromise;
374
- }
375
-
376
- async function assertMermaidSyntax(code, where) {
377
- const mermaid = await mermaidValidator();
378
- try {
379
- const parsed = mermaid.parse(code);
380
- if (parsed && typeof parsed.then === 'function') await parsed;
381
- } catch (err) {
382
- throw new CliError(`${where}: invalid mermaid syntax — ${compactError(err)}`);
383
- }
384
- }
385
-
386
- function* allBlocks(spec) {
387
- const boardBlocks = Array.isArray(spec.blocks) ? spec.blocks : [];
388
- for (let i = 0; i < boardBlocks.length; i++) {
389
- yield { block: boardBlocks[i], where: `board.blocks[${i}]${boardBlocks[i]?.id ? ` (${boardBlocks[i].id})` : ''}` };
390
- }
391
- const questions = Array.isArray(spec.questions) ? spec.questions : [];
392
- for (let qi = 0; qi < questions.length; qi++) {
393
- const q = questions[qi] || {};
394
- const qBlocks = Array.isArray(q.blocks) ? q.blocks : [];
395
- for (let bi = 0; bi < qBlocks.length; bi++) {
396
- yield { block: qBlocks[bi], where: `questions[${qi}].blocks[${bi}]${qBlocks[bi]?.id ? ` (${qBlocks[bi].id})` : ''}` };
397
- }
398
- const opts = Array.isArray(q.options) ? q.options : [];
399
- for (let oi = 0; oi < opts.length; oi++) {
400
- const oBlocks = Array.isArray(opts[oi]?.blocks) ? opts[oi].blocks : [];
401
- for (let bi = 0; bi < oBlocks.length; bi++) {
402
- yield {
403
- block: oBlocks[bi],
404
- where: `questions[${qi}].options[${oi}].blocks[${bi}]${oBlocks[bi]?.id ? ` (${oBlocks[bi].id})` : ''}`,
405
- };
406
- }
407
- }
408
- }
409
- }
410
-
411
- export async function assertSpecReady(spec) {
412
- if (!spec || typeof spec !== 'object') return spec;
413
- if (spec.__relayReady === true) return spec;
414
- for (const { block, where } of allBlocks(spec)) {
415
- if (block && block.type === 'mermaid') await assertMermaidSyntax(block.code || '', where);
416
- if (block && block.type === 'a2ui') await resolveA2uiBlock(block, `${where} (a2ui)`);
417
- }
418
- Object.defineProperty(spec, '__relayReady', { value: true, enumerable: false, configurable: true });
419
- return spec;
420
- }
421
-
422
- // Normalizes one block object. `id` is the already-assigned block id.
423
- // Returns the normalized block (with a guaranteed string `type` + `id`).
424
- function normalizeBlock(rawBlock, id, cwd, where) {
425
- if (rawBlock === null || typeof rawBlock !== 'object' || Array.isArray(rawBlock)) {
426
- throw new CliError(`${where}: must be an object with a "type".`);
427
- }
428
- let type = asStr(rawBlock.type).trim().toLowerCase();
429
- if (!type) throw new CliError(`${where}: missing "type". Valid: ${BLOCK_TYPES.join(', ')}.`);
430
- if (!BLOCK_TYPES.includes(type)) {
431
- throw new CliError(`${where}: unknown block type "${rawBlock.type}". Valid: ${BLOCK_TYPES.join(', ')}.`);
432
- }
433
-
434
- const hasHeight = rawBlock.height !== undefined && rawBlock.height !== null && rawBlock.height !== '';
435
-
436
- if (type === 'markdown') {
437
- const md = readTextSource(rawBlock, 'md', 'mdFile', cwd, where);
438
- if (!md.trim()) throw new CliError(`${where}: markdown block needs a non-empty "md" string or a readable "mdFile".`);
439
- const block = { id, type: 'markdown', md };
440
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
441
- return block;
442
- }
443
-
444
- if (type === 'mermaid') {
445
- const code = asStr(rawBlock.code);
446
- if (!code.trim()) throw new CliError(`${where}: mermaid block needs a non-empty "code" string.`);
447
- const block = { id, type: 'mermaid', code };
448
- if (rawBlock.editable === true) block.editable = true;
449
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
450
- return block;
451
- }
452
-
453
- if (type === 'graphviz') {
454
- const dot = asStr(rawBlock.dot);
455
- if (!dot.trim()) throw new CliError(`${where}: graphviz block needs a non-empty "dot" string.`);
456
- const block = { id, type: 'graphviz', dot };
457
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
458
- return block;
459
- }
460
-
461
- if (type === 'plantuml') {
462
- const code = asStr(rawBlock.code);
463
- if (!code.trim()) throw new CliError(`${where}: plantuml block needs a non-empty "code" string.`);
464
- const block = { id, type: 'plantuml', code };
465
- if (rawBlock.server !== undefined && rawBlock.server !== null && rawBlock.server !== '') {
466
- const server = asStr(rawBlock.server).trim();
467
- if (!/^https?:\/\/\S+$/i.test(server)) {
468
- throw new CliError(`${where}: plantuml "server" must be an http(s) URL string.`);
469
- }
470
- block.server = server;
471
- }
472
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
473
- return block;
474
- }
475
-
476
- if (type === 'code') {
477
- const code = readTextSource(rawBlock, 'code', 'codeFile', cwd, where);
478
- if (!code) throw new CliError(`${where}: code block needs a "code" string or a readable "codeFile".`);
479
- const block = { id, type: 'code', code };
480
- if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
481
- // lang defaults from the codeFile extension when not given explicitly.
482
- else if (typeof rawBlock.codeFile === 'string' && rawBlock.codeFile.trim()) {
483
- const ext = path.extname(rawBlock.codeFile).slice(1).toLowerCase();
484
- if (ext) block.lang = ext;
485
- }
486
- if (rawBlock.filename !== undefined) block.filename = asStr(rawBlock.filename);
487
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
488
- return block;
489
- }
490
-
491
- if (type === 'diff') {
492
- const diff = readTextSource(rawBlock, 'diff', 'diffFile', cwd, where);
493
- if (!diff.trim()) throw new CliError(`${where}: diff block needs a non-empty "diff" string (unified diff) or a readable "diffFile".`);
494
- const block = { id, type: 'diff', diff };
495
- if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
496
- if (rawBlock.filename !== undefined) block.filename = asStr(rawBlock.filename);
497
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
498
- if (rawBlock.review === true) block.review = true;
499
- if (rawBlock.reviewKind !== undefined) block.reviewKind = asStr(rawBlock.reviewKind);
500
- if (rawBlock.commit !== undefined) block.commit = asStr(rawBlock.commit);
501
- const view = asStr(rawBlock.view).trim().toLowerCase();
502
- if (view === 'split' || view === 'unified') block.view = view;
503
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
504
- return block;
505
- }
506
-
507
- if (type === 'git-conflict') {
508
- const src = readAnyTextSource(rawBlock, ['content', 'text'], ['file', 'path', 'src'], cwd, where, 'git conflict file');
509
- if (!src.text.trim()) {
510
- throw new CliError(`${where}: git-conflict block needs inline "content"/"text" or a readable local "file"/"path".`);
511
- }
512
- const parsed = parseGitConflictContent(src.text, where);
513
- if (!parsed.conflicts.length) {
514
- throw new CliError(`${where}: no git conflict markers found (expected <<<<<<<, =======, >>>>>>>).`);
515
- }
516
- const filename = asStr(rawBlock.filename ?? rawBlock.name ?? (src.file ? path.basename(src.file) : '')).trim();
517
- const block = {
518
- id,
519
- type: 'git-conflict',
520
- filename,
521
- conflicts: parsed.conflicts,
522
- parts: parsed.parts,
523
- };
524
- const lang = asStr(rawBlock.lang).trim() || (filename ? path.extname(filename).slice(1).toLowerCase() : '');
525
- if (lang) block.lang = lang;
526
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
527
- if (src.file) block.file = src.file;
528
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
529
- return block;
530
- }
531
-
532
- if (type === 'video') {
533
- const src = asStr(rawBlock.src ?? rawBlock.file ?? rawBlock.url).trim();
534
- if (!src) throw new CliError(`${where}: video block needs a "src" (YouTube/Vimeo URL, http(s) media URL, or local file path).`);
535
- const block = { id, type: 'video' };
536
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
537
- if (rawBlock.alt !== undefined) block.title = asStr(rawBlock.alt);
538
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
539
- const embed = parseVideoEmbed(src);
540
- if (embed) {
541
- block.provider = embed.provider;
542
- block.videoId = embed.videoId;
543
- if (embed.start) block.start = embed.start;
544
- return block;
545
- }
546
- if (/^https?:/i.test(src)) {
547
- block.src = src;
548
- const ext = path.extname(src.split(/[?#]/)[0]).slice(1).toLowerCase();
549
- if (VIDEO_MIMES[ext]) block.mime = VIDEO_MIMES[ext];
550
- return block;
551
- }
552
- // local file — kept as an absolute path the server streams (never embedded
553
- // in the payload). The client only learns a flag + mime via /video/b/<id>.
554
- const p = path.resolve(cwd, src);
555
- const ext = path.extname(p).slice(1).toLowerCase();
556
- const mime = VIDEO_MIMES[ext];
557
- if (!mime) {
558
- throw new CliError(`${where}: unsupported video extension ".${ext}" — use ${Object.keys(VIDEO_MIMES).join('/')}, a YouTube/Vimeo URL, or an http(s) media URL.`);
559
- }
560
- let stat;
561
- try {
562
- stat = fs.statSync(p);
563
- } catch {
564
- throw new CliError(`${where}: cannot read video "${src}" (resolved: ${p})`);
565
- }
566
- if (stat.size > VIDEO_MAX_BYTES) {
567
- throw new CliError(`${where}: video "${src}" is ${(stat.size / 1024 / 1024).toFixed(0)}MB — max ${VIDEO_MAX_BYTES / 1024 / 1024}MB.`);
568
- }
569
- block.file = p;
570
- block.mime = mime;
571
- if (!block.title) block.title = path.basename(p);
572
- return block;
573
- }
574
-
575
- if (type === 'pdf') {
576
- const src = asStr(rawBlock.src ?? rawBlock.file ?? rawBlock.url).trim();
577
- if (!src) throw new CliError(`${where}: pdf block needs a "src" (http(s) PDF URL or local .pdf file path).`);
578
- const block = { id, type: 'pdf' };
579
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
580
- if (rawBlock.alt !== undefined && block.title === undefined) block.title = asStr(rawBlock.alt);
581
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
582
- if (/^https?:/i.test(src)) {
583
- block.src = src;
584
- block.mime = PDF_MIME;
585
- if (!block.title) block.title = path.basename(src.split(/[?#]/)[0]) || 'PDF';
586
- return block;
587
- }
588
- const p = path.resolve(cwd, src);
589
- const ext = path.extname(p).slice(1).toLowerCase();
590
- if (ext !== 'pdf') throw new CliError(`${where}: unsupported pdf extension ".${ext}" — use a local .pdf file or an http(s) PDF URL.`);
591
- let stat;
592
- try {
593
- stat = fs.statSync(p);
594
- } catch {
595
- throw new CliError(`${where}: cannot read pdf "${src}" (resolved: ${p})`);
596
- }
597
- if (stat.size > PDF_MAX_BYTES) {
598
- throw new CliError(`${where}: pdf "${src}" is ${(stat.size / 1024 / 1024).toFixed(0)}MB — max ${PDF_MAX_BYTES / 1024 / 1024}MB.`);
599
- }
600
- block.file = p;
601
- block.mime = PDF_MIME;
602
- if (!block.title) block.title = path.basename(p);
603
- return block;
604
- }
605
-
606
- if (type === 'chart') {
607
- const hasConfig = rawBlock.config && typeof rawBlock.config === 'object' && !Array.isArray(rawBlock.config);
608
- const hasShorthand =
609
- typeof rawBlock.kind === 'string' ||
610
- Array.isArray(rawBlock.labels) ||
611
- Array.isArray(rawBlock.series);
612
- if (!hasConfig && !hasShorthand) {
613
- throw new CliError(`${where}: chart needs "config" (full Chart.js config) or "kind"+"labels"+"series".`);
614
- }
615
- const block = { id, type: 'chart' };
616
- block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, 320);
617
- if (hasConfig) {
618
- block.config = rawBlock.config;
619
- return block;
620
- }
621
- // Shorthand form: validate kind/labels/series.
622
- const kind = asStr(rawBlock.kind).trim().toLowerCase();
623
- if (!kind) throw new CliError(`${where}: chart shorthand needs a "kind" (${CHART_KINDS.join('|')}).`);
624
- if (!CHART_KINDS.includes(kind)) {
625
- throw new CliError(`${where}: unknown chart kind "${rawBlock.kind}". Valid: ${CHART_KINDS.join(', ')}.`);
626
- }
627
- if (!Array.isArray(rawBlock.labels)) {
628
- throw new CliError(`${where}: chart shorthand needs a "labels" array.`);
629
- }
630
- if (!Array.isArray(rawBlock.series) || rawBlock.series.length < 1) {
631
- throw new CliError(`${where}: chart shorthand needs a non-empty "series" array of {label, data[]}.`);
632
- }
633
- block.kind = kind;
634
- block.labels = rawBlock.labels.map((l) => asStr(l));
635
- block.series = rawBlock.series.map((s, k) => {
636
- if (s === null || typeof s !== 'object' || Array.isArray(s)) {
637
- throw new CliError(`${where}.series[${k}]: must be an object {label, data[]}.`);
638
- }
639
- if (!Array.isArray(s.data)) {
640
- throw new CliError(`${where}.series[${k}]: needs a "data" array.`);
641
- }
642
- const out = { label: asStr(s.label), data: s.data };
643
- if (s.color !== undefined) out.color = asStr(s.color);
644
- return out;
645
- });
646
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
647
- return block;
648
- }
649
-
650
- if (type === 'table') {
651
- // Rows/columns may come from a local .csv/.tsv/.json file instead of inline.
652
- let rawColumns = rawBlock.columns;
653
- let rawRows = rawBlock.rows;
654
- if (typeof rawBlock.rowsFile === 'string' && rawBlock.rowsFile.trim() && !Array.isArray(rawRows)) {
655
- const loaded = loadRowsFile(rawBlock.rowsFile, cwd, where);
656
- rawRows = loaded.rows;
657
- if (!Array.isArray(rawColumns) || !rawColumns.length) rawColumns = loaded.columns;
658
- }
659
- if (!Array.isArray(rawColumns) || rawColumns.length < 1) {
660
- throw new CliError(`${where}: table needs a non-empty "columns" array (strings or {key,label,align?})${rawBlock.rowsFile ? ' — the rowsFile had no header/keys to infer them' : ''}.`);
661
- }
662
- if (!Array.isArray(rawRows)) {
663
- throw new CliError(`${where}: table needs a "rows" array or a readable "rowsFile".`);
664
- }
665
- const columns = rawColumns.map((c, k) => {
666
- if (typeof c === 'string' || typeof c === 'number') {
667
- const key = String(c);
668
- return { key, label: key };
669
- }
670
- if (c && typeof c === 'object' && !Array.isArray(c)) {
671
- const key = asStr(c.key ?? c.label).trim();
672
- if (!key) throw new CliError(`${where}.columns[${k}]: needs "key" or "label".`);
673
- const col = { key, label: asStr(c.label ?? c.key) || key };
674
- if (c.align !== undefined) col.align = asStr(c.align);
675
- return col;
676
- }
677
- throw new CliError(`${where}.columns[${k}]: must be a string or {key, label, align?}.`);
678
- });
679
- // Normalize array rows into objects keyed by column key, so the client
680
- // (and table-cell annotation values) always index rows the same way.
681
- const rows = rawRows.map((r, ri) => {
682
- if (Array.isArray(r)) {
683
- const obj = {};
684
- columns.forEach((col, ci) => {
685
- obj[col.key] = r[ci];
686
- });
687
- return obj;
688
- }
689
- if (r && typeof r === 'object') return r;
690
- throw new CliError(`${where}.rows[${ri}]: must be an array or an object.`);
691
- });
692
- const block = { id, type: 'table', columns, rows };
693
- if (rawBlock.sortable === true) block.sortable = true;
694
- if (rawBlock.filterable === true) block.filterable = true;
695
- if (rawBlock.exportable === true) block.exportable = true;
696
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
697
- return block;
698
- }
699
-
700
- if (type === 'image') {
701
- const block = { id, type: 'image' };
702
- block.src = resolveImageSrc(rawBlock.src ?? rawBlock.file ?? rawBlock.url, cwd, where, 'image block');
703
- if (rawBlock.alt !== undefined) block.alt = asStr(rawBlock.alt);
704
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
705
- return block;
706
- }
707
-
708
- if (type === 'kpi') {
709
- // Stat cards: a row of big-number metrics, each with an optional delta
710
- // (up/down tinted) and sublabel. For "revenue ↑12%" at a glance, no chart.
711
- const rawItems = Array.isArray(rawBlock.items) ? rawBlock.items : [];
712
- if (!rawItems.length) throw new CliError(`${where}: kpi block needs a non-empty "items" array of {label, value, delta?, dir?, sub?}.`);
713
- const items = rawItems.map((it, k) => {
714
- if (it === null || typeof it !== 'object' || Array.isArray(it)) throw new CliError(`${where}.items[${k}]: must be an object {label, value, …}.`);
715
- const out = { label: asStr(it.label), value: asStr(it.value) };
716
- if (it.delta !== undefined && it.delta !== null && it.delta !== '') out.delta = asStr(it.delta);
717
- const dir = asStr(it.dir ?? it.deltaDir).trim().toLowerCase();
718
- if (dir === 'up' || dir === 'down' || dir === 'flat') out.dir = dir;
719
- if (it.sub !== undefined) out.sub = asStr(it.sub);
720
- return out;
721
- });
722
- const block = { id, type: 'kpi', items };
723
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
724
- return block;
725
- }
726
-
727
- if (type === 'typography') {
728
- // Type specimens: render sample text at given size/weight/font so a designer
729
- // can react to type choices the way they react to a palette.
730
- const raw = Array.isArray(rawBlock.specimens) ? rawBlock.specimens : (Array.isArray(rawBlock.samples) ? rawBlock.samples : []);
731
- if (!raw.length) throw new CliError(`${where}: typography block needs a non-empty "specimens" array of {label?, size?, weight?, text?}.`);
732
- const specimens = raw.map((s, k) => {
733
- if (s === null || typeof s !== 'object' || Array.isArray(s)) throw new CliError(`${where}.specimens[${k}]: must be an object.`);
734
- const out = { text: asStr(s.text ?? s.sample) || 'The quick brown fox jumps over the lazy dog' };
735
- if (s.label !== undefined) out.label = asStr(s.label);
736
- if (s.size !== undefined) out.size = asStr(s.size);
737
- if (s.weight !== undefined) out.weight = asStr(s.weight);
738
- if (s.font !== undefined) out.font = asStr(s.font);
739
- const lh = s.lineHeight ?? s.leading;
740
- if (lh !== undefined) out.lineHeight = asStr(lh);
741
- const ls = s.letterSpacing ?? s.tracking;
742
- if (ls !== undefined) out.letterSpacing = asStr(ls);
743
- return out;
744
- });
745
- const block = { id, type: 'typography', specimens };
746
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
747
- if (rawBlock.font !== undefined) block.font = asStr(rawBlock.font);
748
- return block;
749
- }
750
-
751
- if (type === 'compare') {
752
- // Before/after: two images with a draggable divider to compare a redesign.
753
- const beforeRaw = rawBlock.before && typeof rawBlock.before === 'object' ? rawBlock.before.src : (rawBlock.before ?? rawBlock.beforeSrc);
754
- const afterRaw = rawBlock.after && typeof rawBlock.after === 'object' ? rawBlock.after.src : (rawBlock.after ?? rawBlock.afterSrc);
755
- const block = {
756
- id, type: 'compare',
757
- before: resolveImageSrc(beforeRaw, cwd, where, '"before"'),
758
- after: resolveImageSrc(afterRaw, cwd, where, '"after"'),
759
- };
760
- block.beforeLabel = asStr(rawBlock.beforeLabel ?? (rawBlock.before && rawBlock.before.label) ?? 'Before') || 'Before';
761
- block.afterLabel = asStr(rawBlock.afterLabel ?? (rawBlock.after && rawBlock.after.label) ?? 'After') || 'After';
762
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
763
- return block;
764
- }
765
-
766
- if (type === 'a2ui') {
767
- // A live A2UI v1.0 widget: Express text (compiled in assertSpecReady) or
768
- // ready JSON components, checked against Relay's catalog either way.
769
- const hasExpress = rawBlock.express !== undefined && rawBlock.express !== null;
770
- const hasComponents = rawBlock.components !== undefined && rawBlock.components !== null;
771
- if (hasExpress === hasComponents) throw new CliError(`${where}: a2ui block needs exactly one of "express" (A2UI Express text) or "components" (JSON list).`);
772
- const block = { id, type: 'a2ui' };
773
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
774
- if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
775
- if (hasExpress) {
776
- if (rawBlock.dataModel !== undefined) throw new CliError(`${where}: with "express", set data with \`$/path = value\` lines, not "dataModel".`);
777
- block.express = guardExpress(rawBlock.express, where);
778
- return block;
779
- }
780
- assertSafeJson(rawBlock.components, where);
781
- const surface = validateSurface({ components: rawBlock.components, dataModel: rawBlock.dataModel }, where);
782
- return Object.assign(block, surface);
783
- }
784
-
785
- if (type === 'palette') {
786
- // Accept either { palettes: [{name, colors:[…]}, …] } or a single-palette
787
- // shorthand { name?, colors:[…] }. Each palette needs a non-empty colors
788
- // array of CSS color strings (#rrggbb, rgb(), hsl(), named — kept as given).
789
- const rawList = Array.isArray(rawBlock.palettes)
790
- ? rawBlock.palettes
791
- : (Array.isArray(rawBlock.colors) ? [{ name: rawBlock.name, sub: rawBlock.sub, colors: rawBlock.colors }] : null);
792
- if (!rawList || !rawList.length) {
793
- throw new CliError(`${where}: palette block needs "palettes" (array) or a "colors" array.`);
794
- }
795
- const palettes = rawList.map((p, j) => {
796
- if (!p || typeof p !== 'object') throw new CliError(`${where}.palettes[${j}]: must be an object with "colors".`);
797
- const colors = (Array.isArray(p.colors) ? p.colors : [])
798
- .map((c) => asStr(c).trim())
799
- .filter(Boolean);
800
- if (!colors.length) throw new CliError(`${where}.palettes[${j}]: needs a non-empty "colors" array.`);
801
- const out = { colors };
802
- if (p.name !== undefined) out.name = asStr(p.name);
803
- const sub = p.sub ?? p.mood;
804
- if (sub !== undefined) out.sub = asStr(sub);
805
- const tag = p.badge ?? p.tag;
806
- if (tag !== undefined) out.tag = asStr(tag);
807
- if (p.tagTone !== undefined) out.tagTone = asStr(p.tagTone).trim().toLowerCase();
808
- if (p.featured === true) out.featured = true;
809
- return out;
810
- });
811
- const block = { id, type: 'palette', palettes };
812
- if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
813
- return block;
814
- }
815
-
816
- // type === 'html'
817
- const html = readBlockHtml(rawBlock, cwd, where);
818
- if (!html) {
819
- throw new CliError(`${where}: html block needs an "html" string or readable "htmlFile".`);
820
- }
821
- return {
822
- id,
823
- type: 'html',
824
- html,
825
- height: clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, 360),
826
- };
827
- }
828
-
829
- // Builds the normalized block list for a scope (board or question).
830
- // Legacy html/htmlFile become a PREPENDED html block; ids are assigned in
831
- // final order with `prefix` ('' for board → b1,b2…; '<qid>-' for questions).
832
- function buildBlocks(rawObj, cwd, where, prefix) {
833
- const blocks = [];
834
- let n = 0;
835
- const nextId = () => `${prefix}b${++n}`;
836
-
837
- // Legacy html/htmlFile → a single prepended html block. htmlHeight applies.
838
- const legacyHtml = readHtml(rawObj, cwd, where);
839
- if (legacyHtml) {
840
- const def = prefix ? HTML_HEIGHT.questionDefault : HTML_HEIGHT.boardDefault;
841
- blocks.push({
842
- id: nextId(),
843
- type: 'html',
844
- html: legacyHtml,
845
- height: clampInt(rawObj.htmlHeight, HTML_HEIGHT.min, HTML_HEIGHT.max, def),
846
- });
847
- }
848
-
849
- if (rawObj.blocks !== undefined && rawObj.blocks !== null) {
850
- if (!Array.isArray(rawObj.blocks)) throw new CliError(`${where}.blocks: must be an array.`);
851
- rawObj.blocks.forEach((b, i) => {
852
- const nb = normalizeBlock(b, nextId(), cwd, `${where}.blocks[${i}]`);
853
- // Cross-block fields handled uniformly so every block type supports them:
854
- // `ref` = a stable name a markdown reference link can open in a modal;
855
- // `pins` = enable coordinate pin-comments on an image.
856
- if (b && typeof b === 'object') {
857
- if (typeof b.ref === 'string' && b.ref.trim()) nb.ref = b.ref.trim();
858
- if (nb.type === 'image' && b.pins === true) nb.pins = true;
859
- }
860
- blocks.push(nb);
861
- });
862
- }
863
- return blocks;
864
- }
865
-
866
- export function normalizeSpec(raw, { cwd = process.cwd() } = {}) {
867
- if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
868
- throw new CliError('Spec must be a JSON object. Run `rly agent` for the schema and examples.');
869
- }
870
- const spec = {
871
- title: asStr(raw.title).trim() || 'Relay',
872
- intro: asStr(raw.intro),
873
- blocks: buildBlocks(raw, cwd, 'board', ''),
874
- allowPartial: raw.allowPartial !== false,
875
- note: raw.note !== false,
876
- autoClose: raw.autoClose !== false,
877
- responseRequired: raw.responseRequired !== false,
878
- questions: [],
879
- submitLabel: '',
880
- };
881
-
882
- const rawQs = raw.questions == null ? [] : raw.questions;
883
- if (!Array.isArray(rawQs)) throw new CliError('"questions" must be an array.');
884
-
885
- const seen = new Set();
886
- rawQs.forEach((rq, i) => {
887
- const where = `questions[${i}]`;
888
- if (rq === null || typeof rq !== 'object' || Array.isArray(rq)) {
889
- throw new CliError(`${where}: must be an object.`);
890
- }
891
- const label = asStr(rq.label ?? rq.question ?? rq.text).trim();
892
- if (!label) throw new CliError(`${where}: missing "label".`);
893
-
894
- let type = asStr(rq.type).trim().toLowerCase() || 'text';
895
- type = ALIASES[type] || type;
896
- if (!TYPES.includes(type)) {
897
- throw new CliError(`${where}: unknown type "${rq.type}". Valid: ${TYPES.join(', ')} (plus aliases like radio/checkbox/boolean/rating).`);
898
- }
899
-
900
- const id = asStr(rq.id).trim() || `q${i + 1}`;
901
- if (seen.has(id)) throw new CliError(`${where}: duplicate question id "${id}".`);
902
- seen.add(id);
903
-
904
- const q = {
905
- id,
906
- type,
907
- label,
908
- description: asStr(rq.description),
909
- required: rq.required === true,
910
- // Decision types (single/rank/checklist/allocate) show the optional
911
- // per-answer note by default so the user can qualify their pick; other
912
- // types stay opt-in. An explicit note:false turns it off.
913
- note: rq.note === undefined
914
- ? (type === 'single' || type === 'rank' || type === 'checklist' || type === 'allocate')
915
- : rq.note === true,
916
- blocks: buildBlocks(rq, cwd, where, `${id}-`),
917
- placeholder: asStr(rq.placeholder),
918
- };
919
-
920
- if (type === 'single' || type === 'multi' || type === 'rank' || type === 'checklist' || type === 'allocate') {
921
- const opts = Array.isArray(rq.options) ? rq.options : [];
922
- q.options = opts.map((o, j) => {
923
- if (typeof o === 'string' || typeof o === 'number') {
924
- return { value: String(o), label: String(o) };
925
- }
926
- if (o && typeof o === 'object') {
927
- const value = asStr(o.value ?? o.label).trim();
928
- const olabel = asStr(o.label ?? o.value).trim();
929
- if (!value) throw new CliError(`${where}.options[${j}]: needs "value" or "label".`);
930
- const out = { value, label: olabel || value };
931
- if (o.description) out.description = asStr(o.description);
932
- // Per-option visuals: any block type, rendered inside the option card
933
- // (ids <qid>-o<n>-b<m>). Lets a choice show its example instead of
934
- // making the user read-and-guess.
935
- const oblocks = buildBlocks(o, cwd, `${where}.options[${j}]`, `${id}-o${j + 1}-`);
936
- if (oblocks.length) out.blocks = oblocks;
937
- return out;
938
- }
939
- throw new CliError(`${where}.options[${j}]: must be a string or {value, label, description?, blocks?}.`);
940
- });
941
- const minOpts = type === 'rank' ? 2 : 1;
942
- if (q.options.length < minOpts) {
943
- throw new CliError(`${where}: type "${type}" needs at least ${minOpts} option${minOpts > 1 ? 's' : ''}.`);
944
- }
945
- // Radio (single) questions include an "Other" free-text option by default so
946
- // the user is never boxed into the listed choices; opt out with other:false.
947
- // Multi stays opt-in (checkbox lists are usually exhaustive on purpose).
948
- // rank/checklist/allocate operate over a fixed set, so no "Other".
949
- if (type === 'single' || type === 'multi') {
950
- q.other = type === 'single' ? rq.other !== false : rq.other === true;
951
- }
952
- }
953
-
954
- if (type === 'checklist') {
955
- // Per-item status control. Default Pass / Fail / N/A; override with
956
- // "statuses" (strings or {value,label,tone?}). tone colors the chip.
957
- const rawSt = Array.isArray(rq.statuses) && rq.statuses.length
958
- ? rq.statuses
959
- : [{ value: 'pass', label: 'Pass', tone: 'ok' }, { value: 'fail', label: 'Fail', tone: 'bad' }, { value: 'na', label: 'N/A', tone: 'muted' }];
960
- q.statuses = rawSt.map((s, k) => {
961
- if (typeof s === 'string' || typeof s === 'number') {
962
- const value = String(s).trim();
963
- return { value, label: value === 'na' ? 'N/A' : value.charAt(0).toUpperCase() + value.slice(1) };
964
- }
965
- if (s && typeof s === 'object') {
966
- const value = asStr(s.value ?? s.label).trim();
967
- if (!value) throw new CliError(`${where}.statuses[${k}]: needs "value" or "label".`);
968
- const out = { value, label: asStr(s.label ?? s.value) || value };
969
- const tone = asStr(s.tone).trim().toLowerCase();
970
- if (tone) out.tone = tone;
971
- return out;
972
- }
973
- throw new CliError(`${where}.statuses[${k}]: must be a string or {value, label, tone?}.`);
974
- });
975
- if (q.statuses.length < 2) throw new CliError(`${where}: checklist needs ≥2 "statuses".`);
976
- }
977
-
978
- if (type === 'allocate') {
979
- q.total = clampInt(rq.total, 1, 1000000, 100);
980
- if (rq.unit !== undefined) q.unit = asStr(rq.unit);
981
- }
982
-
983
- if (type === 'scale') {
984
- q.min = clampInt(rq.min, 0, 9, 1);
985
- q.max = clampInt(rq.max, q.min + 1, 10, Math.max(5, q.min + 1));
986
- q.minLabel = asStr(rq.minLabel);
987
- q.maxLabel = asStr(rq.maxLabel);
988
- }
989
-
990
- if (type === 'color') {
991
- // Optional preset swatches the user can click beside the native picker.
992
- const presets = (Array.isArray(rq.presets) ? rq.presets : [])
993
- .map((c) => asStr(c).trim())
994
- .filter(Boolean);
995
- if (presets.length) q.presets = presets;
996
- // Richer "pick from a palette": labeled swatch cards. Each click selects
997
- // that color as the answer and each card is individually commentable.
998
- // Items: a color string, or {value|color, label?}. Any CSS color system.
999
- if (Array.isArray(rq.palette) && rq.palette.length) {
1000
- q.palette = rq.palette.map((p, k) => {
1001
- if (typeof p === 'string' || typeof p === 'number') {
1002
- const value = String(p).trim();
1003
- return { value, label: value };
1004
- }
1005
- if (p && typeof p === 'object') {
1006
- const value = asStr(p.value ?? p.color).trim();
1007
- if (!value) throw new CliError(`${where}.palette[${k}]: needs a "value" or "color".`);
1008
- return { value, label: asStr(p.label ?? p.name) || value };
1009
- }
1010
- throw new CliError(`${where}.palette[${k}]: must be a color string or {value/color, label?}.`);
1011
- }).filter((p) => p.value);
1012
- }
1013
- }
1014
-
1015
- if (rq.default !== undefined) q.default = rq.default;
1016
- spec.questions.push(q);
1017
- });
1018
-
1019
- if (!spec.questions.length && !spec.blocks.length) {
1020
- throw new CliError('Spec needs "questions" and/or "blocks"/"html" — nothing to show.');
1021
- }
1022
- if (!spec.responseRequired && spec.questions.length) {
1023
- throw new CliError('responseRequired:false is display-only and cannot contain questions. Use responseRequired:true when answers are needed.');
1024
- }
1025
- spec.submitLabel = asStr(raw.submitLabel).trim() || (spec.questions.length ? 'Submit' : 'Acknowledge');
1026
- return spec;
1027
- }
1028
-
1029
- // Inline question syntax for `rly ask -q`: "[!]label::type::opt1,opt2"
1030
- // Leading "!" marks the question required. type defaults to "text".
1031
- export function questionFromInline(s, i) {
1032
- let body = asStr(s).trim();
1033
- let required = false;
1034
- if (body.startsWith('!')) {
1035
- required = true;
1036
- body = body.slice(1).trim();
1037
- }
1038
- const [label, type, options] = body.split('::').map((p) => p.trim());
1039
- if (!label) throw new CliError(`-q #${i + 1}: empty question text.`);
1040
- const q = { label, required };
1041
- if (type) q.type = type;
1042
- if (options) q.options = options.split(',').map((o) => o.trim()).filter(Boolean);
1043
- return q;
1044
- }
1045
-
1046
- const BLOCK_SCHEMA = {
1047
- type: 'array',
1048
- description:
1049
- 'Rich content blocks rendered in order. Board-level blocks show above the questions; per-question blocks show above the control. Each is annotatable (element-level comments returned in result.annotations).',
1050
- items: {
1051
- type: 'object',
1052
- required: ['type'],
1053
- properties: {
1054
- type: { type: 'string', enum: BLOCK_TYPES },
1055
- md: { type: 'string', description: 'markdown: built-in mini renderer (no external library) — headings, lists, code, quotes, links, images, and GFM pipe tables. Text selections are commentable. For real tabular data prefer a "table" block (sortable + per-cell comments).' },
1056
- mdFile: { type: 'string', description: 'markdown: path to a local .md file to load + render instead of inline "md" (e.g. view a README/plan/report). Resolved against the CWD. Quick view of one or more files: `rly view a.md b.md`.' },
1057
- code: { type: 'string', description: 'mermaid: diagram source (e.g. "graph TD; A-->B"); plantuml: the @startuml…@enduml source; code: the source to display (syntax-highlighted with line numbers).' },
1058
- codeFile: { type: 'string', description: 'code: path to a local source file to load + display instead of inline "code". Resolved against the CWD; lang defaults from the file extension.' },
1059
- filename: { type: 'string', description: 'code/diff/git-conflict: optional file name/path shown as a header label above the block.' },
1060
- editable: { type: 'boolean', description: 'mermaid: when true, render an "Edit diagram" toggle so the user can edit the diagram source live. The edited source is returned in result.blockEdits[<blockId>].' },
1061
- dot: { type: 'string', description: 'graphviz: DOT source (e.g. "digraph { a -> b }"). Rendered offline via vendored Viz.js; nodes and edges are individually commentable.' },
1062
- server: { type: 'string', description: 'plantuml: PlantUML server base URL (http(s)). Defaults to https://www.plantuml.com/plantuml. Diagrams render via this server (needs network).' },
1063
- lang: { type: 'string', description: 'code/diff/git-conflict block: language hint for syntax highlighting (js, ts, py, go, rust, java, c, cpp, csharp, ruby, php, swift, kotlin, sql, yaml, json, sh, css, html, …).' },
1064
- diff: { type: 'string', description: 'diff: a unified diff (git diff / diff -u output) — rendered as a colored, line-numbered comparison with +added / −removed / context rows and file/hunk headers. No git needed; just write/paste the diff text.' },
1065
- diffFile: { type: 'string', description: 'diff: path to a local file containing a unified diff (alternative to "diff"). Resolved against the CWD.' },
1066
- view: { type: 'string', enum: ['unified', 'split'], description: 'diff: initial layout — "unified" (default, one column) or "split" (side-by-side old vs new). The viewer also has a live toggle either way.' },
1067
- review: { type: 'boolean', description: 'diff: when true, render per-hunk Apply / Skip / Hold controls and return choices in result.blockEdits[blockId] as {type:"diff-review", hunks:{...}}. Used by `rly git cherry-pick --code`.' },
1068
- reviewKind: { type: 'string', description: 'diff review: optional label for the review workflow, such as "cherry-pick" or "pick".' },
1069
- commit: { type: 'string', description: 'diff review: optional commit SHA associated with this diff.' },
1070
- express: { type: 'string', description: 'a2ui: a live widget in A2UI Express, e.g. `$/jobs = [{title:"Build",tone:"ok"}]` then `root = Card("CI", [List($/jobs), Button("Retry", action=Event("retry"))])`. Compiled by the A2UI SDK against Relay\'s catalog (run `rly a2ui` for the grammar and every component). Button events, input values come back in result.blockEdits[blockId] as {type:"a2ui", data, events}.' },
1071
- components: { type: 'array', description: 'a2ui: the same widget as flat A2UI v1.0 JSON components (root id "root", a Card) instead of "express".', items: { type: 'object' } },
1072
- dataModel: { type: 'object', description: 'a2ui: the data model for "components" (use `$/path = value` lines with "express" instead).' },
1073
- content: { type: 'string', description: 'git-conflict: inline file content containing conflict markers (<<<<<<< / ======= / >>>>>>>). The board auto-detects each hunk and returns resolutions in result.blockEdits[blockId].' },
1074
- text: { type: 'string', description: 'git-conflict: alias for inline "content".' },
1075
- file: { type: 'string', description: 'git-conflict: local conflicted file path to load, parse, and resolve. Resolved against the CWD.' },
1076
- path: { type: 'string', description: 'git-conflict: alias for local conflicted file path.' },
1077
- config: { type: 'object', description: 'chart: a full Chart.js config object.' },
1078
- kind: { type: 'string', enum: CHART_KINDS, description: 'chart shorthand: chart kind (alternative to "config").' },
1079
- labels: { type: 'array', description: 'chart shorthand: x-axis / category labels.' },
1080
- series: {
1081
- type: 'array',
1082
- description: 'chart shorthand: [{label, data:[...], color?}]. Chart data points are individually commentable.',
1083
- items: { type: 'object', properties: { label: { type: 'string' }, data: { type: 'array' }, color: { type: 'string' } } },
1084
- },
1085
- title: { type: 'string', description: 'chart shorthand: chart title. video: title/caption shown under the player.' },
1086
- columns: {
1087
- type: 'array',
1088
- description: 'table: strings, or {key, label, align?}. Cells are commentable.',
1089
- items: { anyOf: [{ type: 'string' }, { type: 'object' }] },
1090
- },
1091
- rows: { type: 'array', description: 'table: array of arrays (positional) or array of objects (keyed by column key).' },
1092
- rowsFile: { type: 'string', description: 'table: load rows from a local .csv/.tsv/.json file instead of inline "rows". CSV/TSV first row is the header (becomes "columns" if omitted); JSON is an array of objects. Resolved against the CWD. Quick view: `rly view data.csv`.' },
1093
- sortable: { type: 'boolean', description: 'table: enable click-to-sort headers.' },
1094
- filterable: { type: 'boolean', description: 'table: show a filter box that live-filters rows by substring across all cells. Good for large tables.' },
1095
- exportable: { type: 'boolean', description: 'table: show a "CSV" button that downloads the (filtered) rows as a CSV file.' },
1096
- html: { type: 'string', description: 'html: custom markup rendered in a sandboxed iframe.' },
1097
- htmlFile: { type: 'string', description: 'html: path to an HTML file (alternative to "html").' },
1098
- src: { type: 'string', description: 'image: http(s)/data URL, or a local file path (png/jpg/gif/webp/svg/avif/bmp — embedded at spec time, served offline). video: a YouTube/Vimeo URL (embeds an iframe player), an http(s) media URL, or a local video file (mp4/webm/ogv/mov/mkv/m4v — streamed from the server, never embedded).' },
1099
- alt: { type: 'string', description: 'image: alt text / annotation label. video: accessible title for the player.' },
1100
- palettes: {
1101
- type: 'array',
1102
- description: 'palette: one or more color palettes to display as swatch cards. Each swatch reveals its hex on hover and copies it on click; mark one {featured:true} to show it as a larger spotlight. Each item: {name?, sub? (or mood?), tag? (or badge?), tagTone? (warm|cool|neutral|nature|bold|digital), featured?, colors:[…]}.',
1103
- items: {
1104
- type: 'object',
1105
- properties: {
1106
- name: { type: 'string' },
1107
- sub: { type: 'string' },
1108
- mood: { type: 'string' },
1109
- tag: { type: 'string' },
1110
- badge: { type: 'string' },
1111
- tagTone: { type: 'string', enum: ['warm', 'cool', 'neutral', 'nature', 'bold', 'digital'] },
1112
- featured: { type: 'boolean' },
1113
- colors: { type: 'array', items: { type: 'string' }, description: 'CSS colors — #rrggbb, rgb()/hsl(), or named.' },
1114
- },
1115
- required: ['colors'],
1116
- },
1117
- },
1118
- colors: { type: 'array', items: { type: 'string' }, description: 'palette shorthand: colors for a single palette (use "palettes" for several named ones). Pairs with block-level "name".' },
1119
- name: { type: 'string', description: 'palette shorthand: name for the single "colors" palette.' },
1120
- items: {
1121
- type: 'array',
1122
- description: 'kpi: stat cards. Each {label, value, delta?, dir? (up|down|flat — tints the delta), sub?}. Big-number metrics at a glance ("Revenue $1.2M ↑12%") with no chart.',
1123
- items: { type: 'object', properties: { label: { type: 'string' }, value: { type: 'string' }, delta: { type: 'string' }, dir: { type: 'string', enum: ['up', 'down', 'flat'] }, sub: { type: 'string' } }, required: ['value'] },
1124
- },
1125
- specimens: {
1126
- type: 'array',
1127
- description: 'typography: type specimens rendered at the given style. Each {label?, size? (e.g. "32px"/"2rem"), weight? (e.g. "600"), font?, lineHeight?, letterSpacing?, text?}. Block-level "font" sets a default family.',
1128
- items: { type: 'object', properties: { label: { type: 'string' }, size: { type: 'string' }, weight: { type: 'string' }, font: { type: 'string' }, lineHeight: { type: 'string' }, letterSpacing: { type: 'string' }, text: { type: 'string' } } },
1129
- },
1130
- ref: { type: 'string', description: 'Any block: a stable name (e.g. "velocity") that a markdown reference link [see chart](#ref:velocity) can open in a full-screen modal — so a question can point back to a visual shown earlier instead of making the user scroll up.' },
1131
- pins: { type: 'boolean', description: 'image: enable coordinate pin-comments — the user clicks any point on the image to drop a comment anchored to that spot (Figma-style), returned as a {kind:"image-point", x, y} annotation.' },
1132
- before: { description: 'compare: the "before" image — an http(s)/data URL, a local file path, or {src, label}.' },
1133
- after: { description: 'compare: the "after" image — an http(s)/data URL, a local file path, or {src, label}.' },
1134
- beforeLabel: { type: 'string', description: 'compare: caption for the before side (default "Before").' },
1135
- afterLabel: { type: 'string', description: 'compare: caption for the after side (default "After").' },
1136
- height: { type: 'integer', minimum: BLOCK_HEIGHT.min, maximum: BLOCK_HEIGHT.max, description: 'Block height in px. Defaults: chart 320, html 360; markdown/table/code flow naturally; mermaid/graphviz/plantuml natural (max 800, scrolls; set a larger height to override); image/compare natural.' },
1137
- },
1138
- },
1139
- };
1140
-
1141
- export const SPEC_SCHEMA = {
1142
- $schema: 'https://json-schema.org/draft/2020-12/schema',
1143
- title: 'relay board spec',
1144
- type: 'object',
1145
- description:
1146
- 'A relay board. Renders an optional intro, board-level blocks, then questions (each with optional per-question blocks), then a submit button. The result JSON contains "answers", "comment", per-question "notes", "annotations" (element-level comments the user attached to any block — see the annotation shape below), and "blockEdits" (a map blockId→edited source for any editable mermaid block the user changed, null when none).',
1147
- properties: {
1148
- version: { const: 1, description: 'Spec version. Optional: a spec without it is read as version 1.' },
1149
- $schema: { type: 'string', description: 'Optional URL of this schema, for editor completion. Relay ignores it.' },
1150
- title: { type: 'string', description: 'Board title (default "Relay")' },
1151
- intro: { type: 'string', description: 'Intro text shown under the title. Newlines preserved.' },
1152
- blocks: BLOCK_SCHEMA,
1153
- html: { type: 'string', description: 'Legacy: board-level custom HTML. Normalized into a single html block PREPENDED to "blocks".' },
1154
- htmlFile: { type: 'string', description: 'Legacy: path to an HTML file (alternative to "html"). Resolved against the CWD. Normalized into a prepended html block.' },
1155
- htmlHeight: { type: 'integer', minimum: HTML_HEIGHT.min, maximum: HTML_HEIGHT.max, default: HTML_HEIGHT.boardDefault, description: 'Legacy: iframe height for the html/htmlFile block.' },
1156
- allowPartial: { type: 'boolean', default: true, description: 'When true, users may submit with unanswered questions (returned in "skipped").' },
1157
- note: { type: 'boolean', default: true, description: 'Show an optional free-text note box ("Anything else?") returned as "comment".' },
1158
- autoClose: { type: 'boolean', default: true, description: 'Try to close the browser tab automatically after submit.' },
1159
- responseRequired: { type: 'boolean', default: true, description: 'Set false for a display-only board: no questions, note box, comments, or Submit/Acknowledge action are shown, and the presenting agent should continue immediately.' },
1160
- submitLabel: { type: 'string', description: 'Submit button label. Defaults: "Submit", or "Acknowledge" when there are no questions.' },
1161
- questions: {
1162
- type: 'array',
1163
- items: {
1164
- type: 'object',
1165
- required: ['label'],
1166
- properties: {
1167
- id: { type: 'string', description: 'Answer key in the result JSON. Defaults to q1, q2, …' },
1168
- type: { type: 'string', enum: ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate'], default: 'text' },
1169
- label: { type: 'string' },
1170
- description: { type: 'string' },
1171
- required: { type: 'boolean', default: false },
1172
- options: {
1173
- type: 'array',
1174
- description: 'For single/multi/rank/checklist/allocate. Strings, or {value, label, description, blocks?}. An option\'s "blocks" render INSIDE that option card — use them to show each choice (image/chart/mermaid/html…) instead of describing it in words. "rank": user reorders (drag/↑↓), answer is the ordered values, ≥2 options. "checklist": each option gets a status (see "statuses"), answer is {value: status}. "allocate": user distributes "total" across options, answer is {value: number}.',
1175
- items: {
1176
- anyOf: [
1177
- { type: 'string' },
1178
- {
1179
- type: 'object',
1180
- properties: {
1181
- value: { type: 'string' },
1182
- label: { type: 'string' },
1183
- description: { type: 'string' },
1184
- blocks: { ...BLOCK_SCHEMA, description: 'Visuals for THIS option, rendered inside its card. Same block types as everywhere else. Keep them compact (height ~140–260).' },
1185
- },
1186
- },
1187
- ],
1188
- },
1189
- },
1190
- other: { type: 'boolean', description: 'Add a free-text "Other" option (a multi-line textarea); its text is returned verbatim as the value. Defaults ON for "single" (radio) questions so the user is never boxed in — set other:false to remove it; "multi" stays opt-in (other:true).' },
1191
- note: { type: 'boolean', description: 'Small optional free-text field under the question (to qualify an answer). Returned separately as result.notes[questionId]. Defaults to true for the decision types — single, rank, checklist, allocate — so users can qualify their pick; false for other types. Set note:false to hide it, note:true to add it.' },
1192
- placeholder: { type: 'string', description: 'For text/textarea.' },
1193
- default: { description: 'Pre-selected value. Shape matches the answer shape for the type.' },
1194
- min: { type: 'integer', default: 1, description: 'scale only' },
1195
- max: { type: 'integer', default: 5, maximum: 10, description: 'scale only' },
1196
- minLabel: { type: 'string', description: 'scale only' },
1197
- maxLabel: { type: 'string', description: 'scale only' },
1198
- presets: { type: 'array', items: { type: 'string' }, description: 'color only: optional small preset swatches (CSS colors) shown beside the native picker for one-click selection. The answer is returned as a color string.' },
1199
- palette: { type: 'array', description: 'color only: a "pick from a palette" of labeled swatch CARDS — each click selects that color as the answer, and each card is individually commentable (per-color feedback). Items: a CSS color string (hex/rgb/hsl/named — multiple color systems supported via the browser, no library), or {value (or color), label?}. The native picker stays available for a custom color.', items: { anyOf: [{ type: 'string' }, { type: 'object' }] } },
1200
- statuses: { type: 'array', description: 'checklist only: the per-item statuses (default Pass / Fail / N/A). Strings, or {value, label, tone?} where tone ∈ ok|bad|muted|warn tints the chip. Answer is a map {optionValue: statusValue} for the items the user set.', items: { anyOf: [{ type: 'string' }, { type: 'object' }] } },
1201
- total: { type: 'integer', minimum: 1, default: 100, description: 'allocate only: the budget to distribute across options (default 100). Answer is a map {optionValue: number}.' },
1202
- unit: { type: 'string', description: 'allocate only: optional unit label shown next to the total (e.g. "%", "pts", "hrs").' },
1203
- blocks: BLOCK_SCHEMA,
1204
- html: { type: 'string', description: 'Legacy: per-question custom HTML. Normalized into an html block prepended to this question\'s "blocks".' },
1205
- htmlFile: { type: 'string', description: 'Legacy: path to an HTML file (alternative to "html").' },
1206
- htmlHeight: { type: 'integer', minimum: HTML_HEIGHT.min, maximum: HTML_HEIGHT.max, default: HTML_HEIGHT.questionDefault, description: 'Legacy: iframe height for the html/htmlFile block.' },
1207
- },
1208
- },
1209
- },
1210
- annotations: {
1211
- type: 'array',
1212
- readOnly: true,
1213
- description:
1214
- 'Returned in the result (not part of the input spec). Element-level comments the user attached to blocks. Each: {id, questionId|null, blockId|null, target:{kind:"chart-element"|"mermaid-node"|"graphviz-node"|"table-cell"|"text"|"html-element"|"image", …}, text, createdAt}. For html-element, target carries a stable ref + label; users can hover any element of a custom-HTML block (automatic) or ones the author marked with data-relay-annotate.',
1215
- },
1216
- blockEdits: {
1217
- type: 'object',
1218
- readOnly: true,
1219
- description:
1220
- 'Returned in the result (not part of the input spec). A map blockId→edited block payload. Editable mermaid blocks return edited source strings. git-conflict blocks return {type:"git-conflict-resolution", resolutions, content, resolved, filename, file}. diff review blocks return {type:"diff-review", hunks, resolved, commit}. a2ui blocks return {type:"a2ui", data (the widget data model with the user input values), events:[{name, context, at}] (each button click, in order)}. null when the user made no edits.',
1221
- },
1222
- },
1223
- anyOf: [{ required: ['questions'] }, { required: ['blocks'] }, { required: ['html'] }, { required: ['htmlFile'] }],
1224
- };