farseer-cli 1.25.0 → 1.26.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 (69) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/dashboards.js +2 -0
  3. package/dist/commands/dashboards.js.map +1 -1
  4. package/dist/commands/login.js +18 -7
  5. package/dist/commands/login.js.map +1 -1
  6. package/dist/commands/logout.js +28 -12
  7. package/dist/commands/logout.js.map +1 -1
  8. package/dist/commands/run.js +2 -3
  9. package/dist/commands/run.js.map +1 -1
  10. package/dist/commands/whoami.js +12 -5
  11. package/dist/commands/whoami.js.map +1 -1
  12. package/dist/mcp/tools/authTools.js +2 -1
  13. package/dist/mcp/tools/authTools.js.map +1 -1
  14. package/dist/mcp/tools/dashboardTools.js +3 -1
  15. package/dist/mcp/tools/dashboardTools.js.map +1 -1
  16. package/dist/mcp/tools/runTools.js +2 -3
  17. package/dist/mcp/tools/runTools.js.map +1 -1
  18. package/dist/mcp/utils/helpers.js +8 -6
  19. package/dist/mcp/utils/helpers.js.map +2 -2
  20. package/dist/mcp/utils/session.js +6 -2
  21. package/dist/mcp/utils/session.js.map +1 -1
  22. package/dist/operations/dashboards.js +1 -1
  23. package/dist/operations/dashboards.js.map +1 -1
  24. package/dist/pipeline/generated-reference.json +8 -8
  25. package/dist/services/codefirst/layoutReadback.js +95 -0
  26. package/dist/services/codefirst/layoutReadback.js.map +2 -2
  27. package/dist/services/configService.js +33 -18
  28. package/dist/services/configService.js.map +1 -1
  29. package/dist/services/credentials.js +26 -11
  30. package/dist/services/credentials.js.map +1 -1
  31. package/dist/services/farseerService.js +34 -32
  32. package/dist/services/farseerService.js.map +1 -1
  33. package/dist/services/keycloak.js +44 -0
  34. package/dist/services/keycloak.js.map +6 -0
  35. package/dist/services/preflight.js +1 -2
  36. package/dist/services/preflight.js.map +1 -1
  37. package/dist/services/realms.js +67 -15
  38. package/dist/services/realms.js.map +1 -1
  39. package/dist/utils/serverUrl.js +42 -0
  40. package/dist/utils/serverUrl.js.map +6 -0
  41. package/docs/pipeline-reference.md +13 -3
  42. package/package.json +1 -1
  43. package/skills/farseer-code-tiles/SKILL.md +153 -0
  44. package/skills/farseer-code-tiles/anti-patterns.md +183 -0
  45. package/skills/farseer-code-tiles/api.md +237 -0
  46. package/skills/farseer-code-tiles/check-tile.mjs +521 -0
  47. package/skills/farseer-code-tiles/design.md +159 -0
  48. package/skills/farseer-code-tiles/echarts-look.md +110 -0
  49. package/skills/farseer-code-tiles/examples/board-deck.js +695 -0
  50. package/skills/farseer-code-tiles/examples/data-checks.js +475 -0
  51. package/skills/farseer-code-tiles/examples/kpi-cards.js +374 -0
  52. package/skills/farseer-code-tiles/examples/map-countries.js +377 -0
  53. package/skills/farseer-code-tiles/examples/month-plan.js +443 -0
  54. package/skills/farseer-code-tiles/examples/new-location.js +581 -0
  55. package/skills/farseer-code-tiles/examples/open-forecast.js +598 -0
  56. package/skills/farseer-code-tiles/examples/pl-sankey.js +402 -0
  57. package/skills/farseer-code-tiles/examples/ranked-bars.js +337 -0
  58. package/skills/farseer-code-tiles/examples/request-form.js +464 -0
  59. package/skills/farseer-code-tiles/farseer-table.md +98 -0
  60. package/skills/farseer-code-tiles/known-mistakes.md +178 -0
  61. package/skills/farseer-code-tiles/maps/europe.geo.json +1 -0
  62. package/skills/farseer-code-tiles/maps/pick-map.mjs +59 -0
  63. package/skills/farseer-code-tiles/maps/world.geo.json +1 -0
  64. package/skills/farseer-dashboards/SKILL.md +3 -2
  65. package/skills/farseer-dashboards/check.md +3 -2
  66. package/skills/farseer-dashboards/measures.md +3 -1
  67. package/skills/farseer-optimize-model/SKILL.md +9 -1
  68. package/skills/farseer-pnl/SKILL.md +3 -3
  69. package/skills/pipeline-authoring/SKILL.md +2 -2
@@ -0,0 +1,521 @@
1
+ #!/usr/bin/env node
2
+ // Checks a saved Code tile's code against the detectors from known-mistakes.md and anti-patterns.md. It needs no
3
+ // browser and reads no data: it runs the code once with made-up data to catch a crash, in a child node with the
4
+ // permission model on and no grants. Check a few cells with farseer formula eval, and look at the tile or ask the user to.
5
+ // Run it from your working folder, so its report is written there and not into the installed skill.
6
+ //
7
+ // farseer dashboards show-tile <dashboard> <tile> --json > tile.json
8
+ // node <skill folder>/check-tile.mjs --tile-json tile.json [--out ./check]
9
+ // node <skill folder>/check-tile.mjs --code tile.js (before the tile is saved)
10
+ //
11
+ // Exit code 1 when anything leaves the tile empty, wrong or unable to write; warnings alone exit 0.
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { spawnSync } from 'node:child_process';
16
+
17
+ const args = Object.fromEntries(
18
+ process.argv.slice(2).reduce((pairs, arg, i, all) => {
19
+ if (arg.startsWith('--')) pairs.push([arg.slice(2), all[i + 1] && !all[i + 1].startsWith('--') ? all[i + 1] : true]);
20
+ return pairs;
21
+ }, [])
22
+ );
23
+ const given = (name) => (args[name] && args[name] !== true ? String(args[name]) : null);
24
+ if (!given('tile-json') && !given('code')) {
25
+ console.error('usage: node check-tile.mjs --tile-json <file> | --code <file> [--out dir]');
26
+ process.exit(2);
27
+ }
28
+ const out = path.resolve(given('out') ?? 'tile-check');
29
+ fs.mkdirSync(out, { recursive: true });
30
+
31
+ const findings = []; // { level: 'error' | 'warning', check, message }
32
+ const error = (check, message) => findings.push({ level: 'error', check, message });
33
+ const warn = (check, message) => findings.push({ level: 'warning', check, message });
34
+
35
+ // 1. The tile
36
+ let tile = { name: path.basename(given('code') ?? ''), data: { code: '' } };
37
+ if (given('tile-json')) {
38
+ const read = JSON.parse(fs.readFileSync(given('tile-json'), 'utf8'));
39
+ tile = read.tile ?? read;
40
+ } else {
41
+ tile.data.code = fs.readFileSync(given('code'), 'utf8');
42
+ }
43
+ if (given('tile-json') && tile.data?.type !== 'CODE') {
44
+ console.error(`${given('tile-json')} is not a Code tile (data.type ${tile.data?.type})`);
45
+ process.exit(2);
46
+ }
47
+ const tileId = tile.id ?? null;
48
+ const code = tile.data?.code ?? '';
49
+
50
+ // The AC colour (the farseer-dashboards skill, the AC colour): #323232 or a brand colour dark enough to read as the
51
+ // darkest thing on the page, never red or green
52
+ const codeAC = code.match(/const\s+AC\s*=\s*['"](#[0-9a-fA-F]{6})['"]/)?.[1]?.toUpperCase();
53
+ if (codeAC) {
54
+ const n = parseInt(codeAC.slice(1), 16);
55
+ const [r, g, b] = [n >> 16, (n >> 8) & 255, n & 255];
56
+ const lin = (c) => { const s = c / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
57
+ const luminance = 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
58
+ if ((r > 150 && g < 90 && b < 90) || (g > 120 && r < 90 && b < 110 && g - Math.max(r, b) > 50)) {
59
+ error('ac', `AC is ${codeAC}, a red or green: those are the variance colours. AC is #323232 or a dark brand colour; keep the brand red or green for the logo and small accents.`);
60
+ } else if (luminance > 0.06) {
61
+ error('ac', `AC is ${codeAC}, too light to read as the darkest thing on the page (relative luminance ${luminance.toFixed(3)}, at most about 0.06). Use #323232, or the brand's darkest colour.`);
62
+ }
63
+ }
64
+
65
+ // 2. Detectors (known-mistakes.md). They read the code with comments and string contents blanked out.
66
+ function blank(source) {
67
+ // keeps positions: comments and the insides of strings become spaces
68
+ let result = '';
69
+ let i = 0;
70
+ while (i < source.length) {
71
+ const c = source[i];
72
+ const next = source[i + 1];
73
+ if (c === '/' && next === '/') {
74
+ while (i < source.length && source[i] !== '\n') (result += ' '), i++;
75
+ } else if (c === '/' && next === '*') {
76
+ while (i < source.length && !(source[i] === '*' && source[i + 1] === '/')) (result += source[i] === '\n' ? '\n' : ' '), i++;
77
+ result += ' ';
78
+ i += 2;
79
+ } else if (c === '"' || c === "'" || c === '`') {
80
+ result += c;
81
+ i++;
82
+ while (i < source.length && source[i] !== c) {
83
+ if (source[i] === '\\') (result += ' '), (i += 2);
84
+ else (result += source[i] === '\n' ? '\n' : ' '), i++;
85
+ }
86
+ result += c;
87
+ i++;
88
+ } else {
89
+ result += c;
90
+ i++;
91
+ }
92
+ }
93
+ return result;
94
+ }
95
+ const plain = blank(code);
96
+ const lineOf = (index) => code.slice(0, index).split('\n').length;
97
+
98
+ // where the draw function starts: the first `return` directly in the default export's body
99
+ function depthAt(index) {
100
+ let depth = 0;
101
+ for (let i = 0; i < index; i++) {
102
+ if (plain[i] === '{') depth++;
103
+ else if (plain[i] === '}') depth--;
104
+ }
105
+ return depth;
106
+ }
107
+ const exportAt = plain.search(/export\s+default\s+(async\s+)?function\s*\w*\s*\(/);
108
+ if (exportAt < 0) error('module', 'No `export default function (ctx) { … }`: the tile runs nothing.');
109
+ let drawStart = -1;
110
+ for (const match of plain.matchAll(/\breturn\b/g)) {
111
+ if (match.index > exportAt && depthAt(match.index) === 1) {
112
+ drawStart = match.index;
113
+ break;
114
+ }
115
+ }
116
+ if (exportAt >= 0 && drawStart < 0) error('module', 'The default export returns no draw function, so nothing is drawn.');
117
+
118
+ for (const match of plain.matchAll(/(?<!function\s)\b(ctx\.query|ctx\.getEntities|readTable)\s*\(/g)) {
119
+ if (drawStart >= 0 && match.index > drawStart) {
120
+ error('made-while-drawing', `line ${lineOf(match.index)}: ${match[1]}() inside the draw function opens a new read on every draw. Open it once in the body.`);
121
+ }
122
+ }
123
+ // writes: only from a click or key handler; a write returns a handle, never a Promise
124
+ const closingParen = (from) => {
125
+ let depth = 0;
126
+ for (let i = from; i < plain.length; i++) {
127
+ if (plain[i] === '(') depth++;
128
+ else if (plain[i] === ')' && --depth === 0) return i;
129
+ }
130
+ return plain.length;
131
+ };
132
+ for (const match of plain.matchAll(/ctx\.(write|addMembers|updateMembers)\s*\(/g)) {
133
+ const depth = depthAt(match.index);
134
+ const statementStart = Math.max(plain.lastIndexOf(';', match.index), plain.lastIndexOf('{', match.index), plain.lastIndexOf('}', match.index));
135
+ const before = plain.slice(statementStart + 1, match.index);
136
+ const inHandler = /=>|\bfunction\b/.test(before) || (drawStart >= 0 && match.index > drawStart ? depth > 2 : depth > 1);
137
+ if (!inHandler) error('write-outside-handler', `line ${lineOf(match.index)}: ctx.${match[1]}() outside a click or key handler. Writes run only right after the viewer clicks or types in the tile.`);
138
+ const after = plain.slice(closingParen(match.index + match[0].length - 1) + 1).trimStart();
139
+ if (/\bawait\s*$/.test(before) || /^\.\s*(then|catch|finally)\b/.test(after)) {
140
+ error('write-awaited', `line ${lineOf(match.index)}: ctx.${match[1]}() returns a handle, not a Promise: await or .then on it throws. Keep the handle and show its loading and error when the tile draws (api.md, Writing).`);
141
+ } else if (!/[=:]\s*$|[=:]\s*[\w.$]*\s*$|\(\s*$|,\s*$|return\s*$/.test(before)) {
142
+ warn('write-unchecked', `line ${lineOf(match.index)}: the handle ctx.${match[1]}() returns is dropped. Keep it and show a refused write's error beside the button.`);
143
+ }
144
+ }
145
+ // a planner reads the months it writes with the filter bar off: a Year to date or month pick there cuts the open months
146
+ if (/ctx\.write\s*\(/.test(plain) && /"Months"\s*>/.test(code)) {
147
+ for (const match of plain.matchAll(/ctx\.(query|read)\s*\(/g)) {
148
+ const call = plain.slice(match.index, closingParen(match.index + match[0].length - 1));
149
+ if (/includeDashboardFilters\s*:\s*true/.test(call)) {
150
+ warn('period-cut', `line ${lineOf(match.index)}: this read follows the filter bar in a tile that writes months; a Year to date or month pick cuts the months after it. Read the cells with includeDashboardFilters: false and name the picked members from picks() (known-mistakes.md, A planner whose open months are empty).`);
151
+ }
152
+ }
153
+ }
154
+ // a title joins its parts with commas, never a dash or a middle dot (design.md, Text)
155
+ for (const match of code.matchAll(/heading\([^;\n]*?['"`][^'"`\n]*?\s[—–·]\s[^'"`\n]*['"`]/g)) {
156
+ warn('title-joiner', `line ${lineOf(match.index)}: the title joins its parts with a dash or a middle dot. Use a comma: "Conference travelers, Budget 2027, Product".`);
157
+ }
158
+ // a grid of inputs carries a placeholder in the first empty row at most (design.md, Forms)
159
+ for (const match of plain.matchAll(/\.placeholder\s*=/g)) {
160
+ const before = plain.slice(Math.max(0, match.index - 300), match.index);
161
+ const loop = Math.max(before.lastIndexOf('.map('), before.lastIndexOf('.forEach('), before.lastIndexOf('for ('));
162
+ if (loop >= 0 && !/\bfunction\b/.test(before.slice(loop)) && !/placeholder\s*=\s*[^;]*\?/.test(plain.slice(match.index, match.index + 120))) {
163
+ warn('placeholder-every-row', `line ${lineOf(match.index)}: a placeholder set in a loop repeats on every empty row. Keep it on the first empty row at most; the column header says what goes there.`);
164
+ break;
165
+ }
166
+ }
167
+ // a thousands format ('#,##0,') shows 1,170 EUR as 1: the unit beside it has to say kEUR
168
+ if (/['"`]#,##0(\.0+)?,['"`]/.test(code) && /\(EUR\)|\bEUR\)/.test(code) && !/kEUR|k EUR|thousand/i.test(code)) {
169
+ error('unit-scale', "A number is formatted in thousands ('#,##0,') but the tile labels it EUR: 1,170 EUR shows as 1. Format it '#,##0', or say kEUR in the title and headers.");
170
+ }
171
+ // a typed number is read in the viewer's locale: dropping dots or swapping the comma reads 13,000 as 13 for en-US viewers
172
+ if (/\.replace\(\s*['"],['"]\s*,\s*['"]\.['"]\s*\)|\.replace\(\s*\/\\\.\/g\s*,\s*['"]['"]\s*\)/.test(code)) {
173
+ error('number-locale', "A typed number is parsed by swapping ',' and '.': 14,000 typed by an en-US viewer becomes 14. Read it with parseNumber, in ctx.theme.numberLocale (known-mistakes.md).");
174
+ }
175
+ if (/ctx\.filters\b/.test(plain)) error('no-filters', 'ctx.filters no longer exists. Read the filter bar through a DTABLE read: picks([...]) (api.md, The dashboard\'s filters).');
176
+ for (const match of plain.matchAll(/\.release\s*\(\s*\)/g)) error('release', `line ${lineOf(match.index)}: a read is stopped with .close(), not .release().`);
177
+ if (/ctx\.action\s*\(/.test(plain)) error('no-apps', 'ctx.action(): a Code tile can\'t run an App. Write the cells or members yourself (api.md, Writing).');
178
+ // A button label never wraps (SKILL.md, Non-negotiables): every button needs white-space: nowrap
179
+ if (/createElement\(\s*['"]button['"]|<button\b/.test(code) && !/white-space\s*:\s*nowrap|whiteSpace\s*=\s*['"]nowrap['"]|whiteSpace\s*:\s*['"]nowrap['"]/.test(code)) {
180
+ error('button-wrap', 'The tile has a button and no white-space: nowrap anywhere: its label wraps when the tile is narrow. Set it on every button.');
181
+ }
182
+ for (const [pattern, what] of [
183
+ [/\bfetch\s*\(/, 'fetch'],
184
+ [/\bXMLHttpRequest\b/, 'XMLHttpRequest'],
185
+ [/\bWebSocket\b/, 'WebSocket'],
186
+ [/\bimport\s*\(/, 'import()'],
187
+ [/\blocalStorage\b/, 'localStorage'],
188
+ [/\bsessionStorage\b/, 'sessionStorage'],
189
+ [/\bindexedDB\b/, 'indexedDB'],
190
+ [/document\.cookie/, 'document.cookie'],
191
+ [/window\.open\s*\(/, 'window.open'],
192
+ [/\blocation\s*=(?!=)/, 'navigation'],
193
+ ]) {
194
+ const match = plain.match(pattern);
195
+ if (match) error('frame-blocks', `line ${lineOf(match.index)}: ${what} is blocked in the frame.`);
196
+ }
197
+ for (const match of plain.matchAll(/\.(toFixed|toLocaleString)\s*\(/g)) {
198
+ error('number-format', `line ${lineOf(match.index)}: .${match[1]}() ignores the viewer's number locale. Use ctx.format(value, numberFormat).`);
199
+ }
200
+ for (const match of plain.matchAll(/\b(rows|cells)\[(\d+)\]/g)) {
201
+ if (match[1] === 'rows' && match[2] === '0') continue; // the one row of a query without rows
202
+ error('by-position', `line ${lineOf(match.index)}: ${match[0]} picks by position. Find rows and columns by label.`);
203
+ }
204
+ for (const match of plain.matchAll(/new\s+Date\s*\(|Date\.now\s*\(/g)) {
205
+ error('clock', `line ${lineOf(match.index)}: today's date decides nothing on a tile. The period of the numbers and of the title comes from the filter bar (picks) or from the model (the last closed month), never from the clock.`);
206
+ }
207
+ if (drawStart >= 0) {
208
+ const draw = plain.slice(drawStart);
209
+ const appends = draw.match(/element\.(appendChild|append|insertAdjacentHTML)\s*\(|element\.innerHTML\s*\+=/);
210
+ const clears = /element\.(replaceChildren|textContent\s*=|innerHTML\s*=(?!=))/.test(draw);
211
+ if (appends && !clears) error('grows', `line ${lineOf(drawStart + appends.index)}: the draw function appends to element without clearing it first.`);
212
+ }
213
+ for (const match of plain.matchAll(/(window|document)\.addEventListener\s*\(|set(Interval|Timeout)\s*\(/g)) {
214
+ const around = plain.slice(match.index, match.index + 400);
215
+ if (!/signal/.test(around) && !/ctx\.onCleanup/.test(plain)) {
216
+ warn('listeners', `line ${lineOf(match.index)}: a listener or timer with no ctx.signal or ctx.onCleanup outlives the run.`);
217
+ }
218
+ }
219
+ for (const match of plain.matchAll(/\.reduce\s*\(/g)) {
220
+ const line = code.split('\n')[lineOf(match.index) - 1] ?? '';
221
+ if (/\/\/\s*(display only|remainder|simulation)/.test(line)) continue;
222
+ error('own-arithmetic', `line ${lineOf(match.index)}: a reduce over query results. A total, average or ratio shown to the reader must come from the model, not from adding cells.`);
223
+ }
224
+ for (const match of code.matchAll(/['"`][+-]?#,##0\.0+[;'"`]/g)) {
225
+ error('decimals', `line ${lineOf(match.index)}: ${match[0]} shows an amount in cents. Amounts are whole units, kEUR as '#,##0,' (design.md, one number format per unit); decimals are for rates and percentages.`);
226
+ }
227
+ for (const match of code.matchAll(/(?:textContent\s*=|cells:\s*\[[^\]]*|\?|:|push\()\s*['"`](OK|Loaded|Missing|Pass|Fail|Passed|Failed)['"`]/g)) {
228
+ warn('status-words', `line ${lineOf(match.index)}: "${match[1]}" as a status in a grid. A check or status grid shows Farseer's Tick and Close icons, with the value on hover (design.md, examples/data-checks.js).`);
229
+ }
230
+ if (/charts\.farseer\s*\(/.test(code)) {
231
+ for (const match of code.matchAll(/\{[^{}\n]*\b(?:formula|filter)\s*:[^{}\n]*\}/g)) {
232
+ if (/numberFormat/.test(match[0]) || !/label\s*:/.test(match[0])) continue;
233
+ warn('chart-format', `line ${lineOf(match.index)}: a column or row with no numberFormat. Farseer's chart then labels it with two decimals ("1,500.00"); give every number its format ('#,##0', or '#,##0,' for kEUR).`);
234
+ }
235
+ }
236
+ // the control block draws Farseer's own inputs, selects and buttons, whose colours are the app's, not the tile's
237
+ const controlBlock = /const CONTROL_CSS = `[\s\S]*?`;/.exec(code);
238
+ const inControls = (i) => controlBlock && i >= controlBlock.index && i < controlBlock.index + controlBlock[0].length;
239
+ for (const match of code.matchAll(/(?:color|background(?:-color)?|border(?:-[a-z]+)?|fill)\s*:\s*['"]?(#[0-9a-fA-F]{3,8}|rgba?\([^)]*\)|white|black)/g)) {
240
+ if (/^#fff(fff)?$/i.test(match[1])) continue; // white text on a dark fill is what design.md asks for
241
+ if (inControls(match.index)) continue;
242
+ warn('typed-colour', `line ${lineOf(match.index)}: "${match[0]}". Text, background and lines take the theme tokens; a typed colour is only for a data mark (design.md).`);
243
+ }
244
+
245
+ // the look (anti-patterns.md): charts go through ctx.charts, not by hand
246
+ for (const [pattern, what] of [
247
+ [/createElementNS\s*\(/, 'an SVG element made by hand'],
248
+ [/<\s*(svg|path|polygon|polyline)\b/i, 'SVG markup'],
249
+ [/getContext\s*\(|createElement\s*\(\s*['"]canvas/, 'a canvas'],
250
+ ]) {
251
+ const match = code.match(pattern);
252
+ if (match) error('hand-drawn', `line ${lineOf(match.index)}: ${what}. Every chart goes through ctx.charts.farseer or ctx.charts.echarts (anti-patterns.md, A chart drawn by hand).`);
253
+ }
254
+ if (/registerMap\s*\([^)]*\{\s*svg/.test(plain)) error('made-up-map', 'registerMap with an SVG drawn in the code. Use real outlines from maps/pick-map.mjs.');
255
+ if (/type\s*:\s*['"]map['"]/.test(code) && !/Natural Earth|const MAP\s*=/.test(code)) warn('made-up-map', 'A map series without outlines from maps/pick-map.mjs.');
256
+ if (/splitLine\s*:\s*\{[^}]*show\s*:\s*true/.test(plain) || /showValueAxis\s*:\s*true/.test(plain)) error('marks', 'A value axis or gridlines: Farseer\'s chart tiles hide the value axis and draw no gridlines; label the values (totals on a stack) instead.');
257
+ if (/heading\s*\([^;]*·/.test(code) || /TITLE[^;]*·/.test(code)) error('header', 'A title joined with a middle dot: join the parts of a title with commas ("Net sales by region, year to date, Acme Serbia").');
258
+ if (/border-radius\s*:\s*(1[2-9]|[2-9]\d|\d{3,})px/.test(code) && /button|tab/i.test(code)) error('control', 'Rounded pill buttons: a choice of a few is a select or one row of underlined tabs (design.md, Forms).');
259
+ if (/border-left\s*:\s*\$?\{?[^;'"`]*?([2-9]|\d{2,})px\s+solid/.test(code.replace(/const TABLE_CSS = `[\s\S]*?`;/, ''))) warn('rail', 'A thick border down the left: a decorative rail no Farseer tile uses (anti-patterns.md, A decorative rail).');
260
+ if (/stack\s*:/.test(plain) && /PALETTE\s*\[/.test(plain)) error('colour', 'A stack coloured from PALETTE: the parts of one whole take steps of AC, the largest deepest (design.md, Colour by its job, Parts of one whole).');
261
+ if (/(createElement|el)\s*\(\s*['"]select['"]/.test(plain) && !/control\s*\(\s*['"]select['"]/.test(plain)) error('control', 'A select not made by control(): every select and input shares one look (design.md, Forms).');
262
+ if (/type\s*:\s*['"]dashed['"]/.test(code)) warn('chrome', 'Dashed lines: gridlines and axes are solid 1 px in the rule colour.');
263
+ if (/type\s*:\s*['"]bar['"]/.test(code) && /borderRadius/.test(code)) error('marks', 'Rounded bars: Farseer\'s chart tiles draw square bars (echarts-look.md, Marks).');
264
+ if (/type\s*:\s*['"]bar['"]/.test(code) && /barMaxWidth/.test(code)) warn('marks', 'barMaxWidth makes bars thinner than the chart tile\'s; leave the default width.');
265
+ if (/type\s*:\s*['"](treemap|map|gauge|sankey|heatmap)['"]/.test(code)) {
266
+ const usesPalette = /#81A9FF|#457DFF|#0D4BC2|#043288|PALETTE|RAMP|FILL|\bAC\b/i.test(code);
267
+ if (!usesPalette) error('grey', 'A treemap, map, gauge, sankey or heatmap without PALETTE or RAMP: it will read as a grey sketch (anti-patterns.md, A grey tile).');
268
+ }
269
+ if (/font-size:\s*1[5-9]px[^'"`]*font-weight:\s*(6|7)00/.test(code) && !/KPI|value/i.test(code.slice(0, 200))) error('header', 'A big bold title: a Code tile\'s header takes the tile header style (12 px ink, regular), as the chart tiles beside it.');
270
+ if (/createElement\s*\(\s*['"]table['"]|el\s*\(\s*['"]table['"]/.test(code) && !/fs-table/.test(code)) error('table', 'A table not built by farseerTable: tables take the table tile\'s look (farseer-table.md).');
271
+ for (const match of plain.matchAll(/\.width\s*=\s*`?\$\{|width:\s*\$\{[^}]*\}%/g)) {
272
+ warn('html-bar', `line ${lineOf(match.index)}: an element sized from a value. Bars are drawn by ctx.charts, not by HTML (anti-patterns.md, A chart drawn by hand).`);
273
+ }
274
+ if (/type\s*:\s*['"]treemap['"]/.test(code) && /colorSaturation|colorAlpha/.test(code) && !/visualMap/.test(code)) warn('shades', 'Treemap shades with no value behind them: one colour per group (anti-patterns.md, Colours that mean nothing).');
275
+ if (/(label|th)\s*\{[^}]*color:\s*var\(--code-tile-muted\)/.test(code)) warn('pale', 'Labels or headers in muted ink: labels and headers are ink, muted only for units, footnotes and prompts (anti-patterns.md, Pale text).');
276
+ if (/\.fs-table\s+t[hd][^{]*\{[^}]*border-bottom/.test(code.replace(/const TABLE_CSS = `[\s\S]*?`;/, ''))) warn('table', 'A border on table cells outside farseerTable pushes headers out of line (anti-patterns.md, Table headers out of line).');
277
+ if (/placeholder\s*=\s*['"]\d/.test(code) || /placeholder\s*:\s*['"]\d/.test(code)) warn('form', 'A numeric placeholder reads as a typed value; describe the field instead.');
278
+ if (/yAxis\s*:\s*\[[^\]]*\{[^\]]*\}\s*,\s*\{/.test(plain)) warn('two-scales', 'Two y-axes on one chart: make two charts.');
279
+ // any colour list the code defines is measured, not trusted
280
+ // Only the listed colours (design.md, the colour block): a typed list of other hues is a palette nobody checked
281
+ const LISTED = new Set(['#323232', '#A6A6A6', '#ED7D16', '#1BB5D7', '#8A2FE5', '#BFA812', '#E52FCD', '#F5B87F', '#82D6E9', '#BF8DF1', '#DCCF7D', '#F18DE4', '#81A9FF', '#457DFF', '#0D4BC2', '#043288', '#1A66FF', '#0CB955', '#E21E09']);
282
+ for (const match of code.matchAll(/const\s+(\w+)\s*=\s*\[((?:\s*['"]#[0-9a-fA-F]{6}['"]\s*,?)+)\]/g)) {
283
+ const unlisted = [...match[2].matchAll(/#[0-9a-fA-F]{6}/g)].map((m) => m[0].toUpperCase()).filter((hex) => !LISTED.has(hex));
284
+ if (unlisted.length) error('palette', `${match[1]} (line ${lineOf(match.index)}) types colours that aren't in design.md's colour block (${unlisted.join(', ')}). Use PALETTE, FILL, RAMP or the steps of AC.`);
285
+ }
286
+
287
+ // 3. The parts that run the tile's code: the reads its readTable and ctx.query calls name, and a run with made-up
288
+ // data. Without a browser the run is the only way to see that the code starts at all: a name that is never declared
289
+ // (a constant from another example) crashes the tile before it draws anything. A saved tile's code is untrusted, and
290
+ // node's vm is no boundary, so both run in a child node with the permission model on, no grants, an empty
291
+ // environment and a time limit: the code can't read a file, a key or the environment, start a process, or hang the check.
292
+ async function sandboxMain({ code, specs, width, height }, vm) {
293
+ const findings = [];
294
+ const error = (check, message) => findings.push({ level: 'error', check, message });
295
+ const warn = (check, message) => findings.push({ level: 'warning', check, message });
296
+ const queries = [];
297
+ const anything = new Proxy({}, { has: () => true, get: (_t, key) => (key === Symbol.unscopables ? undefined : 0) });
298
+ for (const { line, src } of specs) {
299
+ try {
300
+ const value = vm.runInNewContext(`with (scope) { (${src}) }`, { scope: anything }, { timeout: 200 });
301
+ const query = Array.isArray(value) ? { columns: value.filter((q) => q?.type === 'VARIABLE').map((q) => ({ formula: q.formula })) } : value;
302
+ if (query && typeof query === 'object') queries.push({ line, query: JSON.parse(JSON.stringify(query)) });
303
+ } catch {
304
+ // a spec built elsewhere: the detectors can't read it
305
+ }
306
+ }
307
+ // a node that takes any call: the run looks for the code's own mistakes, not for what a page would draw
308
+ const either = (k) => {
309
+ let inner;
310
+ return new Proxy(function () {}, {
311
+ apply: (_t, _this, a) => ((k.startsWith('append') || k === 'insertBefore' || k === 'replaceChildren') && a[0] ? a[0] : node()),
312
+ get: (_t, key) => (inner ??= node())[key],
313
+ set: (_t, key, v) => (((inner ??= node())[key] = v), true),
314
+ });
315
+ };
316
+ const node = () => {
317
+ const own = {
318
+ style: new Proxy({}, { get: (t, k) => (k === 'setProperty' ? () => {} : t[k] ?? ''), set: (t, k, v) => ((t[k] = v), true) }),
319
+ dataset: {}, children: [], childNodes: [], options: [], value: '', textContent: '', innerHTML: '', className: '',
320
+ clientWidth: width, clientHeight: height, offsetWidth: width, offsetHeight: height, scrollHeight: height,
321
+ classList: { add() {}, remove() {}, toggle() {}, contains: () => false },
322
+ getBoundingClientRect: () => ({ x: 0, y: 0, top: 0, left: 0, width, height, right: width, bottom: height }),
323
+ querySelector: () => null, querySelectorAll: () => [], getElementsByTagName: () => [], closest: () => null,
324
+ contains: () => false, getAttribute: () => null, hasAttribute: () => false, cloneNode: () => node(),
325
+ addEventListener: (_type, fn) => typeof fn === 'function' && handlers.push(fn),
326
+ };
327
+ return new Proxy(own, {
328
+ // an unknown member works both as a method (append, focus) and as a node (head, parentNode)
329
+ get: (t, k) => (k in t ? t[k] : typeof k === 'symbol' || k === 'then' ? undefined : either(k)),
330
+ set: (t, k, v) => (k.startsWith?.('on') && typeof v === 'function' && handlers.push(v), (t[k] = v), true),
331
+ });
332
+ };
333
+ const handlers = [];
334
+ const answer = (queries) => queries.map((q, i) => ({ ...q, value: q.type === 'DTABLE' ? ['NULL (Table)', 'Member A', 'Member B', 'Member C'] : 1000 * (i + 1) }));
335
+ // a handle refuses to be awaited, as the runtime's does
336
+ const refuse = () => { const e = new Error("A handle can't be awaited; read its current, loading and error when the tile draws again"); e.name = 'AwaitedHandle'; throw e; };
337
+ const handle = (queries) => ({ loading: false, error: null, close() {}, then: refuse, current: answer(queries) });
338
+ const writeHandle = (current) => ({ loading: false, error: null, then: refuse, current });
339
+ const cell = (initial) => ({ value: initial, set() {} });
340
+ const ctx = {
341
+ query: (queries) => handle(Array.isArray(queries) ? queries : [queries]), getEntities: (keys) => handle(keys ?? []),
342
+ read: async (queries) => answer(Array.isArray(queries) ? queries : [queries]),
343
+ write: () => writeHandle(undefined), addMembers: (_t, members) => writeHandle(members.map((m, i) => ({ id: i + 1, name: m.name }))),
344
+ updateMembers: () => writeHandle(undefined),
345
+ charts: { farseer() {}, echarts() {}, registerMap() {} },
346
+ format: (v) => (v == null ? '' : String(v)), frame: { width, height },
347
+ theme: { tokens: { text: '#020810', background: '#FFFFFF', muted: '#687C95', border: '#E6EBF2', focus: '#1A66FF' }, palette: ['#323232', '#ED7D16', '#1BB5D7'], numberLocale: 'en-US', colorBlind: false },
348
+ loading() {}, state: (_k, initial) => cell(initial), snapshot: (_k, initial) => cell(initial),
349
+ render() {}, onCleanup() {}, signal: new AbortController().signal,
350
+ };
351
+ const document = node();
352
+ for (const k of ['createElement', 'createElementNS', 'createTextNode', 'createDocumentFragment']) document[k] = () => node();
353
+ const sandbox = {
354
+ ctx, document, console: { log() {}, warn() {}, error() {} }, navigator: { userActivation: { isActive: false }, language: 'en' },
355
+ window: { addEventListener() {}, removeEventListener() {}, matchMedia: () => ({ matches: false, addEventListener() {} }) },
356
+ getComputedStyle: () => new Proxy({}, { get: () => '' }), requestAnimationFrame: () => 0, cancelAnimationFrame() {},
357
+ setTimeout: (fn) => (typeof fn === 'function' && setImmediate(fn), 0), clearTimeout() {}, setInterval: () => 0, clearInterval() {},
358
+ ResizeObserver: class { observe() {} disconnect() {} }, MutationObserver: class { observe() {} disconnect() {} },
359
+ Intl, Math, Date, JSON, Number, String, Array, Object, Map, Set, Promise, Symbol, Error, RegExp, isFinite, isNaN, parseFloat, parseInt,
360
+ };
361
+ sandbox.window.document = document;
362
+ // the browser's own names, so only a name the code itself never declared fails the run
363
+ const Stub = class { constructor() { return node(); } };
364
+ Object.assign(Stub, { ELEMENT_NODE: 1, TEXT_NODE: 3, DOCUMENT_FRAGMENT_NODE: 11 });
365
+ for (const k of ['Node', 'Element', 'HTMLElement', 'SVGElement', 'Text', 'DocumentFragment', 'Event', 'CustomEvent',
366
+ 'KeyboardEvent', 'MouseEvent', 'PointerEvent', 'FocusEvent', 'InputEvent', 'DOMParser', 'Image', 'Option', 'IntersectionObserver'])
367
+ sandbox[k] = Stub;
368
+ for (const k of Object.getOwnPropertyNames(globalThis))
369
+ if (/^(HTML|SVG|CSS|DOM)/.test(k) || ['URL', 'URLSearchParams', 'Blob', 'TextEncoder', 'TextDecoder', 'AbortController',
370
+ 'structuredClone', 'queueMicrotask', 'performance', 'BigInt', 'WeakMap', 'WeakSet', 'Reflect', 'Proxy', 'TypeError',
371
+ 'RangeError', 'encodeURIComponent', 'decodeURIComponent', 'atob', 'btoa', 'Uint8Array', 'Float64Array', 'ArrayBuffer'].includes(k))
372
+ sandbox[k] ??= globalThis[k];
373
+ sandbox.CSS ??= { escape: (s) => String(s), supports: () => true };
374
+ sandbox.location = { hash: '', href: '' };
375
+ sandbox.window = new Proxy(sandbox.window, { get: (t, k) => (k in t ? t[k] : sandbox[k]) });
376
+ sandbox.globalThis = sandbox.window;
377
+ sandbox.self = sandbox.window;
378
+ const body = code.replace(/export\s+default\s+/, '__tile.main = ');
379
+ try {
380
+ const tileExports = {};
381
+ vm.runInNewContext(body + '\n;', { ...sandbox, __tile: tileExports }, { timeout: 2000 });
382
+ const draw = typeof tileExports.main === 'function' ? tileExports.main(ctx) : null;
383
+ if (typeof draw === 'function') {
384
+ draw(node());
385
+ draw(node());
386
+ // every click and key handler once, as a viewer would: a name missing there fails on the first click
387
+ for (const fn of handlers.slice(0, 200)) {
388
+ const event = { preventDefault() {}, stopPropagation() {}, key: 'Enter', target: node(), currentTarget: node() };
389
+ await Promise.race([
390
+ Promise.resolve(fn(event)).catch((e) => { if (e?.name === 'ReferenceError' || e?.name === 'AwaitedHandle') throw e; }),
391
+ new Promise((resolve) => setTimeout(resolve, 500)),
392
+ ]);
393
+ await new Promise((resolve) => setImmediate(resolve)); // let a ctx.read in the handler answer
394
+ }
395
+ } else {
396
+ error('run', 'The default export returned no draw function, so the tile draws nothing.');
397
+ }
398
+ } catch (e) {
399
+ const where = String(e?.stack ?? '').match(/evalmachine\.<anonymous>:(\d+)/)?.[1];
400
+ if (e?.name === 'ReferenceError' || e?.name === 'SyntaxError' || e?.name === 'AwaitedHandle') {
401
+ error('run', `The tile crashes: ${e.name}: ${e.message}${where ? ` (line ${where})` : ''}. The viewer sees only this error, on load or on the first click.`);
402
+ } else {
403
+ warn('run', `A run with made-up data threw ${e?.name ?? 'an error'}: ${e?.message ?? e}${where ? ` (line ${where})` : ''}. Make sure real data can't do the same.`);
404
+ }
405
+ }
406
+ return { queries, findings };
407
+ }
408
+ const sandboxScript = `${sandboxMain}
409
+ // a click handler's promise (a ctx.read(...).then) that rejects later is a crash on that click
410
+ const late = [];
411
+ process.on('unhandledRejection', (e) => late.push({ name: e?.name ?? 'Error', message: String(e?.message ?? e) }));
412
+ let input = '';
413
+ process.stdin.on('data', (d) => (input += d)).on('end', async () => {
414
+ const result = await sandboxMain(JSON.parse(input), require('node:vm'));
415
+ await new Promise((resolve) => setTimeout(resolve, 50));
416
+ for (const e of late) {
417
+ const crash = e.name === 'ReferenceError' || e.name === 'AwaitedHandle';
418
+ result.findings.push({ level: crash ? 'error' : 'warning', check: 'run', message: crash
419
+ ? 'The tile crashes on a click: ' + e.name + ': ' + e.message + '. The viewer sees only this error.'
420
+ : 'A click with made-up data threw ' + e.name + ': ' + e.message + ". Make sure real data can't do the same." });
421
+ }
422
+ // exit once the whole answer is written: a pipe takes it in chunks
423
+ process.stdout.write(JSON.stringify(result), () => process.exit(0));
424
+ });`;
425
+ // the readTable specs and ctx.query lists, as source text for the child to evaluate
426
+ const specs = [];
427
+ for (const match of plain.matchAll(/(?<!function\s)\b(readTable|ctx\.query)\s*\(/g)) {
428
+ let i = match.index + match[0].length;
429
+ let depth = 0;
430
+ const start = i;
431
+ for (; i < plain.length; i++) {
432
+ if ('({['.includes(plain[i])) depth++;
433
+ else if (')}]'.includes(plain[i])) {
434
+ if (depth === 0) break;
435
+ depth--;
436
+ }
437
+ if (depth === 0 && plain[i] === ',') break;
438
+ }
439
+ specs.push({ line: lineOf(match.index), src: code.slice(start, i) });
440
+ }
441
+ const flags = process.allowedNodeEnvironmentFlags;
442
+ const permissionFlag = flags.has('--permission') ? '--permission' : flags.has('--experimental-permission') ? '--experimental-permission' : null;
443
+ let queries = [];
444
+ if (!permissionFlag) {
445
+ error('run', `Node ${process.versions.node} has no permission model, so the tile's code was not run. Run the check with Node 20 or later.`);
446
+ } else {
447
+ const width = 30 * (tile.gridPlacements?.absolute?.w ?? 24) - 24;
448
+ const height = 30 * (tile.gridPlacements?.absolute?.h ?? 10) - 24;
449
+ const child = spawnSync(process.execPath, [permissionFlag, '--no-warnings', '-e', sandboxScript], {
450
+ input: JSON.stringify({ code, specs, width, height }),
451
+ env: {},
452
+ encoding: 'utf8',
453
+ timeout: 8000,
454
+ maxBuffer: 16 * 1024 * 1024,
455
+ });
456
+ if (child.error?.code === 'ETIMEDOUT' || child.signal) {
457
+ error('run', 'The tile\'s code did not finish within 8 seconds with made-up data: a loop that never ends freezes the tile ("stopped responding").');
458
+ } else {
459
+ let result = null;
460
+ try {
461
+ result = JSON.parse(child.stdout);
462
+ } catch {
463
+ // no answer, or a cut one
464
+ }
465
+ if (child.status !== 0 || !result) {
466
+ const why = (child.stderr || '').trim().split('\n').find((l) => /Error|error:/.test(l)) ?? `exit ${child.status}`;
467
+ error('run', `The run with made-up data didn't finish, so the tile wasn't checked: ${why}. Fix the cause, or check the tile on the dashboard.`);
468
+ } else {
469
+ queries = result.queries;
470
+ findings.push(...result.findings);
471
+ }
472
+ }
473
+ }
474
+ // the dashboard's filters are known only when the dashboard is read through the API (section 3)
475
+ const dashboardFilterTables = null;
476
+ for (const { line, query } of queries) {
477
+ const texts = [
478
+ ...(query.columns ?? []).flatMap((c) => [c.formula, c.filter]),
479
+ ...(Array.isArray(query.rows) ? query.rows.map((r) => r.formula) : []),
480
+ ].filter(Boolean);
481
+ const filters = (query.columns ?? []).map((c) => c.filter).filter(Boolean);
482
+ for (const column of [...(query.columns ?? []), ...(Array.isArray(query.rows) ? query.rows : [])]) {
483
+ // a variable's name is a quoted string; outside sum() it isn't summed over the filters the way the tiles are
484
+ const formula = column.formula ?? '';
485
+ if (formula && /^\s*"[^"]+"/.test(formula.replace(/^\s*\(/, ''))) error('sum', `line ${line}: "${formula}" names a variable outside sum(). Write sum("Variable", …).`);
486
+ }
487
+ // one measure across the scenario columns of a query: AC from one variable and PL or FC from another don't compare
488
+ const scenarioCols = (query.columns ?? []).filter((c) => c.formula && /\b(AC|PL|PY|FC|Actual|Budget|Forecast|Plan)\b/i.test(c.label ?? ''));
489
+ const byMeasure = {};
490
+ for (const c of scenarioCols) {
491
+ const v = c.formula.match(/sum\(\s*"([^"]+)"/)?.[1];
492
+ const stem = (c.label ?? '').replace(/\b(AC|PL|PY|FC|Actual|Budget|Forecast|Plan)\b.*$/i, '').trim() || '(value)';
493
+ if (v) (byMeasure[stem] ??= new Set()).add(v);
494
+ }
495
+ for (const [stem, vars] of Object.entries(byMeasure)) {
496
+ if (vars.size > 1) error('mixed-measure', `line ${line}: the scenario columns of "${stem}" read different variables (${[...vars].join(', ')}). Compare one measure across AC, PL, PY and FC.`);
497
+ }
498
+ for (const text of [...texts, ...filters]) {
499
+ // a version's Reporting period member alone spans every year the version holds
500
+ if (/"?Reporting period"?\s*>\s*"?(Current budget|Current forecast)/.test(text) && !/Current year|"?Years"?\s*>/.test(text)) {
501
+ error('period', `line ${line}: "${text}" names Current budget or Current forecast without Current year: it adds up every year that version holds. Add "Reporting period">"Current year".`);
502
+ }
503
+ if (/"?Versions"?\s*>/.test(text) && !/Years|Reporting period|Year to date|Months|Quarters/.test(text) && dashboardFilterTables?.size === 0) {
504
+ warn('period', `line ${line}: "${text}" names a version and no year on a dashboard without filters: it adds up every year the version holds.`);
505
+ }
506
+ }
507
+ }
508
+
509
+ // 4. Report
510
+ // the run draws twice and clicks every button it drew, so the same finding can come twice
511
+ const seen = new Set();
512
+ findings.splice(0, findings.length, ...findings.filter((f) => !seen.has(f.level + f.check + f.message) && seen.add(f.level + f.check + f.message)));
513
+ const report = { tileId, name: tile.name, placement: tile.gridPlacements, findings };
514
+ fs.writeFileSync(path.join(out, 'check.json'), JSON.stringify(report, null, 2));
515
+ const errors = findings.filter((f) => f.level === 'error');
516
+ const warnings = findings.filter((f) => f.level === 'warning');
517
+ console.log(`Tile ${tileId ?? ''} "${tile.name ?? ''}": ${errors.length} errors, ${warnings.length} warnings`);
518
+ for (const f of findings) console.log(` ${f.level === 'error' ? 'ERROR' : 'warn '} [${f.check}] ${f.message}`);
519
+ console.log(`\nThe check reads code, not numbers or the picture. Check a few cells with farseer formula eval. Look at the tile on the dashboard, or ask the user to, at its own width and in a narrow window.`);
520
+ console.log(`Full report: ${path.join(out, 'check.json')}`);
521
+ process.exit(errors.length > 0 ? 1 : 0);