@enspirit/opspicy 0.4.0 → 0.6.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.
@@ -0,0 +1,420 @@
1
+ // The runner: the table of the Tests page and of the tests page of each area, every case a row
2
+ // under its operation, and every operation under its area. The document holds the rows as the last
3
+ // run left them; this part folds them (an operation is folded unless a case of it failed), counts
4
+ // each row that holds others, and opens a case on what its run told. Served, every row has a ▶
5
+ // that runs what it names, the bar above the table runs all of it, and the server tells each case
6
+ // as it is run: the rows say where the run is, and a case that was run opens on its call, its
7
+ // answer and its log, which the server keeps. Not served, the bar says the command of a terminal.
8
+ // What is decided (what is asked, how a row stands, the words) is in running.js.
9
+
10
+ const CHEVRON = '<svg aria-hidden="true" width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3l4 4-4 4"></path></svg>';
11
+ const PLAY = '<svg aria-hidden="true" width="12" height="12" viewBox="0 0 14 14" fill="currentColor"><path d="M4 2.5v9l7.5-4.5z"></path></svg>';
12
+
13
+ /** What stops the run that is under way, when one is. */
14
+ let stopsRun = null;
15
+
16
+ /** How a case stands, as its row says it: where a run is with it, or what the last one decided. */
17
+ const standingOf = (row) => row.dataset.state || row.dataset.result || 'notrun';
18
+
19
+ /** The rows of a case, wherever the document has it: on the Tests page and on the page of its area. */
20
+ const caseRows = (ref) => $$('tr.rn-case').filter((row) => row.dataset.ref === ref);
21
+
22
+ /** The runners that were made ready: those of the pages that were shown. */
23
+ const runnersReady = () => $$('.runner[data-filled]');
24
+
25
+ /** The cases under a row that holds others: those of an operation, or of the operations of an area. */
26
+ function casesUnder(box, row) {
27
+ const within = (ref) => $$('tr.rn-case', box).filter((one) => one.dataset.in === ref);
28
+ if (row.matches('.rn-op')) return within(row.dataset.ref);
29
+ return $$('tr.rn-op', box).filter((one) => one.dataset.in === row.dataset.ref).flatMap((one) => within(one.dataset.ref));
30
+ }
31
+
32
+ /** The rows that hold a case: its operation, and the area of that operation where the table has areas. */
33
+ function holding(box, ref) {
34
+ const groups = $$('tr.rn-area, tr.rn-op', box);
35
+ const kase = $$('tr.rn-case', box).find((row) => row.dataset.ref === ref);
36
+ const found = [];
37
+ for (let within = kase && kase.dataset.in; within; within = found.at(-1).dataset.in) {
38
+ const row = groups.find((one) => one.dataset.ref === within);
39
+ if (!row) break;
40
+ found.push(row);
41
+ }
42
+ return found;
43
+ }
44
+
45
+ /** The time of some cases together, as it reads; nothing when none of them was timed. */
46
+ function timeTogether(rows) {
47
+ const timed = rows.filter((row) => row.dataset.ms !== undefined);
48
+ return timed.length ? timeText(timed.reduce((sum, row) => sum + Number(row.dataset.ms), 0)) : '';
49
+ }
50
+
51
+ /** A bar of how some cases went: what passed, what did not, and what is left to run. */
52
+ const meterHtml = (standing) => `<span class="rn-meter" aria-hidden="true"><i class="ok" style="width:${standing.passedShare}"></i><i class="ko" style="width:${standing.badShare}"></i></span>`;
53
+
54
+ /** A case says how it stands, and its time. */
55
+ function paintCase(row) {
56
+ const standing = caseStanding(standingOf(row));
57
+ $('.rn-res', row).innerHTML = `<span class="res ${standing.cls}">${standing.glyph} ${standing.word}</span>`;
58
+ $('.rn-time', row).textContent = row.dataset.state ? '' : timeTogether([row]);
59
+ }
60
+
61
+ /** A row that holds others says how its cases stand: a bar, the counts, their time. */
62
+ function paintGroup(box, row) {
63
+ const cases = casesUnder(box, row);
64
+ const standing = rowStanding(cases.map(standingOf));
65
+ row.classList.toggle('bad', standing.bad > 0);
66
+ row.classList.toggle('busy', standing.busy);
67
+ $('.rn-res', row).innerHTML = `${meterHtml(standing)}<span class="rn-count">${esc(standing.words)}</span>`;
68
+ $('.rn-time', row).textContent = timeTogether(cases);
69
+ }
70
+
71
+ /** What is above the table says how all its cases stand: the bar of the whole, and the counts of the page when it has them. */
72
+ function paintWhole(box) {
73
+ const standing = rowStanding($$('tr.rn-case', box).map(standingOf));
74
+ const whole = $('.rn-whole', box);
75
+ if (whole) whole.innerHTML = meterHtml(standing);
76
+ const counts = { ran: standing.ran, passed: standing.passed, failed: standing.bad, notrun: standing.total - standing.ran };
77
+ for (const tile of $$('[data-tile]', box.closest('.page'))) {
78
+ $('b', tile).textContent = counts[tile.dataset.tile];
79
+ if (tile.dataset.tile === 'failed') tile.className = `tile ${standing.bad ? 'ko' : 'ok'}`;
80
+ }
81
+ }
82
+
83
+ /** Every row of a runner says how it stands. */
84
+ function paintRunner(box) {
85
+ for (const row of $$('tr.rn-case', box)) paintCase(row);
86
+ for (const row of $$('tr.rn-area, tr.rn-op', box)) paintGroup(box, row);
87
+ paintWhole(box);
88
+ }
89
+
90
+ /** Opens or folds a row, and says so on its button. */
91
+ function setOpen(row, open) {
92
+ row.classList.toggle('open', open);
93
+ const button = $('.rn-tw', row);
94
+ if (button) button.setAttribute('aria-expanded', String(open));
95
+ }
96
+
97
+ /**
98
+ * Shows the rows that are to be seen: an operation when its area is open, a case when its
99
+ * operation is, what a case told when the case is open. With the failures alone, a case that did
100
+ * not fail is hidden, and so is a row that holds none that did.
101
+ */
102
+ function showRunner(box) {
103
+ const only = box.classList.contains('only-bad');
104
+ const failed = (row) => ['failed', 'error'].includes(standingOf(row));
105
+ let [area, operation, kase] = [true, true, true];
106
+ let shown = 0;
107
+ for (const row of $$('tbody > tr', box)) {
108
+ if (row.matches('.rn-area')) {
109
+ row.hidden = only && !row.classList.contains('bad');
110
+ area = !row.hidden && row.classList.contains('open');
111
+ } else if (row.matches('.rn-op')) {
112
+ row.hidden = !area || (only && !row.classList.contains('bad'));
113
+ operation = !row.hidden && row.classList.contains('open');
114
+ } else if (row.matches('.rn-case')) {
115
+ row.hidden = !area || !operation || (only && !failed(row));
116
+ kase = !row.hidden && row.classList.contains('open');
117
+ if (!row.hidden || (only && failed(row))) shown += 1;
118
+ } else if (row.matches('.rn-more')) row.hidden = !kase;
119
+ else if (row.matches('.rn-none')) row.hidden = !only || shown > 0;
120
+ }
121
+ }
122
+
123
+ /** What the system was asked by a case, and what it answered: the call in a line, what was sent, the status, the body. */
124
+ function exchangeHtml(told) {
125
+ const { request, answer } = told;
126
+ const sent = request && request.sent !== undefined ? bodyText(request.sent) : '';
127
+ const call = request ? `<p class="mono">${esc(`${request.method} ${request.path}`)} <span class="m">as ${esc(request.actor)}</span></p>${sent ? `<pre class="out">${esc(sent)}</pre>` : ''}` : '<p class="m">The system was not called.</p>';
128
+ const body = answer ? bodyText(answer.body) : '';
129
+ const said = answer ? `<p class="mono"><b>${esc(answer.status)}</b></p>${body ? `<pre class="out">${esc(body)}</pre>` : '<p class="m">No body.</p>'}` : '<p class="m">The system gave no answer.</p>';
130
+ return `<h4>Call</h4>${call}<h4>Answer</h4>${said}`;
131
+ }
132
+
133
+ /** What did not hold, as a list in the tint of what fails; nothing when everything held. */
134
+ const heldHtml = (failed) => (failed.length ? `<div class="fail"><h4>What did not hold</h4><ul>${failed.map(failedLine).join('')}</ul></div>` : '');
135
+
136
+ /** What a case told when it was run, as the server keeps it: what did not hold, the call and its answer, and beside them the whole log. */
137
+ function toldHtml(ref, told) {
138
+ const from = `<p class="m s">Run in the ${esc(told.mode)} mode, from the Background <span class="mono">${esc(told.background)}</span>, in ${esc(timeText(told.seconds * 1000))}.</p>`;
139
+ return `<div class="rn-told"><div>${heldHtml(Array.isArray(told.failed) ? told.failed : [])}${exchangeHtml(told)}${from}${toCase(ref)}</div><div><h4>Log</h4><pre class="rn-log" tabindex="0">${esc((told.log || []).join('\n'))}</pre></div></div>`;
140
+ }
141
+
142
+ /** What is said of a case whose run the server does not keep: what the document knows did not hold, and why there is no more. */
143
+ function untoldHtml(row, why) {
144
+ return `${heldHtml(failedOf(row.dataset.failed))}${why}${toCase(row.dataset.ref)}`;
145
+ }
146
+
147
+ /** The way from what a case told to the case itself, as its operation writes it. */
148
+ const toCase = (ref) => `<p class="s"><a href="#${esc(ref)}">This case, in the specification</a></p>`;
149
+
150
+ /** Fills what is under a case that is open: what its run told, asked of the server when the page is served, or what stands for it. */
151
+ async function fillTold(row) {
152
+ const more = row.nextElementSibling;
153
+ const ref = row.dataset.ref;
154
+ const cell = $('.rn-detail', more);
155
+ if (row.dataset.state) {
156
+ cell.innerHTML = `<p class="m">${row.dataset.state === 'running' ? 'It is being run…' : 'It waits for the run to get to it.'}</p>`;
157
+ return;
158
+ }
159
+ await servedKnown;
160
+ const health = served();
161
+ if (!health) cell.innerHTML = untoldHtml(row, commandHtml(ref, whyNotServed(location.protocol)));
162
+ else if (health.protected) cell.innerHTML = untoldHtml(row, commandHtml(ref, whyNoRunHere(servedHost())));
163
+ else {
164
+ if (!cell.innerHTML) cell.innerHTML = '<p class="m">Asking the server what it keeps of this case…</p>';
165
+ const answer = await serverFetch(`api/ran?case=${encodeURIComponent(ref)}`, {}, WAITS.review);
166
+ // The row may have been closed, or run again, while the server was asked.
167
+ if (row.nextElementSibling !== more || row.dataset.state) return;
168
+ if (answer && answer.status === 200 && isRecord(answer.data)) cell.innerHTML = toldHtml(ref, answer.data);
169
+ else if (answer && answer.status === 200) cell.innerHTML = untoldHtml(row, '<p class="m">The server keeps no log of this case: it did not run it since it started. Its ▶ runs it.</p>');
170
+ else cell.innerHTML = untoldHtml(row, `<p class="err">${esc(answer ? (answer.data && answer.data.refused) || `The server answered ${answer.status}.` : 'No answer from the server: it may have stopped.')}</p>`);
171
+ }
172
+ }
173
+
174
+ /** Opens a case on what its run told, or closes it. */
175
+ function toggleTold(box, row) {
176
+ const open = !row.classList.contains('open');
177
+ setOpen(row, open);
178
+ if (open) {
179
+ const more = document.createElement('tr');
180
+ more.className = 'rn-more';
181
+ more.innerHTML = `<td colspan="${row.cells.length}"><div class="rn-detail"></div></td>`;
182
+ row.after(more);
183
+ fillTold(row);
184
+ } else row.nextElementSibling.remove();
185
+ showRunner(box);
186
+ }
187
+
188
+ /** A case that is open tells again what the server keeps of it: it was run, or a run got to it. */
189
+ function retell(row) {
190
+ if (row.classList.contains('open')) fillTold(row);
191
+ }
192
+
193
+ /** What a run tells is put on the rows of the cases it names, and on the rows that hold them. */
194
+ function tellRows(message) {
195
+ const touched = new Set();
196
+ const each = (ref, change) => {
197
+ for (const row of caseRows(ref)) {
198
+ change(row);
199
+ const box = row.closest('.runner');
200
+ if (!box.dataset.filled) continue;
201
+ paintCase(row);
202
+ retell(row);
203
+ touched.add(box);
204
+ }
205
+ };
206
+ if (message.is === 'started') for (const ref of runsQueued(message)) each(ref, (row) => (row.dataset.state = 'queued'));
207
+ else if (message.is === 'running') each(String(message.ref), (row) => (row.dataset.state = 'running'));
208
+ else if (message.is === 'ran') {
209
+ const result = ['passed', 'failed'].includes(message.result) ? message.result : 'error';
210
+ each(String(message.ref), (row) => {
211
+ delete row.dataset.state;
212
+ row.dataset.result = result;
213
+ row.dataset.ms = String(Math.round((Number(message.seconds) || 0) * 1000));
214
+ row.dataset.failed = JSON.stringify(Array.isArray(message.failed) ? message.failed : []);
215
+ });
216
+ }
217
+ for (const box of touched) {
218
+ for (const row of $$('tr.rn-area, tr.rn-op', box)) paintGroup(box, row);
219
+ // A case that failed is seen at once: what holds it is opened.
220
+ if (message.is === 'ran' && message.result !== 'passed') for (const row of holding(box, String(message.ref))) setOpen(row, true);
221
+ paintWhole(box);
222
+ showRunner(box);
223
+ }
224
+ }
225
+
226
+ /** The cases a run did not get to are as they were before it: what the last run decided of them still stands. */
227
+ function settleRows() {
228
+ for (const row of $$('tr.rn-case[data-state]')) delete row.dataset.state;
229
+ for (const box of runnersReady()) {
230
+ paintRunner(box);
231
+ for (const row of $$('tr.rn-case.open', box)) fillTold(row);
232
+ showRunner(box);
233
+ }
234
+ }
235
+
236
+ /** A run is under way, or none is: while one is, nothing else is run, and it can be stopped. */
237
+ function setRunning(on) {
238
+ running = on;
239
+ for (const button of $$('.runner .rn-go, .runner [data-go]')) button.disabled = on;
240
+ for (const button of $$('.runner [data-stop]')) button.hidden = !on;
241
+ }
242
+
243
+ /** What the bar says once a run ended: its result, its time, and whether it is kept. */
244
+ function endedHtml(told) {
245
+ const { ended } = told;
246
+ const verdict = runsVerdict(told);
247
+ let kept = '<span class="m">Nothing keeps this run: serve the explorer with <span class="mono">--report=</span>, and its pages tell the last one.</span>';
248
+ if (ended.report) kept = '<span>It is in the report of the explorer now.</span><button type="button" class="tb sm" data-show>Show it on every page</button>';
249
+ else if (ended.unwritten) kept = `<span class="err">${esc(ended.unwritten)}</span>`;
250
+ else if (ended.stopped) kept = `<span class="m">Stopped: ${told.done} of ${told.total} were run.</span>`;
251
+ return `<span class="res ${verdict.cls}">${verdict.glyph} ${esc(verdict.words)}</span><span class="m">${esc(secondsText(ended.seconds))} · ${esc(told.mode)} mode</span>${kept}`;
252
+ }
253
+
254
+ /** What the bar says of a run that did not get to its end: it was stopped from the page, or its server stopped telling. */
255
+ const cutHtml = (told, why) => `<span class="${why ? 'err' : 'm'}">${esc(why || 'Stopped.')} ${told.done} of ${told.total} were run.</span>`;
256
+
257
+ /** The Tests page says when the cases were last run, once a run from the page ended: what it said before was of the report it was written from. */
258
+ function sayLastRun(told) {
259
+ const lead = $('#tests > .lead');
260
+ if (lead && told.ended && !told.ended.stopped) lead.textContent = `Run ${new Date().toLocaleString('en-GB')}${told.mode === 'fast' ? ', the fast run' : ''}.`;
261
+ }
262
+
263
+ /**
264
+ * Asks the server to run what a row names, or every case of the table when none is named, and
265
+ * puts each thing it says on the rows as it comes. Whatever comes, or nothing, the run is over at
266
+ * the end: another may start.
267
+ */
268
+ async function sendRuns(box, ref) {
269
+ const health = served();
270
+ const mode = $('[data-mode]', box) ? $('[data-mode]', box).value : health.mode;
271
+ const [prog, out] = [$('.prog', box), $('.outcome', box)];
272
+ const stopping = new AbortController();
273
+ let told = runsStart();
274
+ stopsRun = () => stopping.abort();
275
+ setRunning(true);
276
+ prog.textContent = 'Starting…';
277
+ out.innerHTML = '';
278
+ try {
279
+ const response = await fetch('api/runs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ...runsScope(ref), mode: modeOfRun(health, mode) }), signal: stopping.signal });
280
+ if (!(response.headers.get('content-type') || '').includes('ndjson')) {
281
+ const refusal = await response.json().catch(() => null);
282
+ out.innerHTML = `<span class="err">${esc((refusal && refusal.refused) || `The server answered ${response.status}.`)}</span>`;
283
+ return;
284
+ }
285
+ const tell = (message) => {
286
+ told = runsTold(told, message);
287
+ if (isRecord(message)) tellRows(message);
288
+ prog.textContent = told.ended || told.broken ? '' : runsWords(told);
289
+ };
290
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
291
+ let kept = '';
292
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
293
+ const lines = runsLines(kept, read.value);
294
+ kept = lines.kept;
295
+ for (const message of lines.messages) tell(message);
296
+ }
297
+ // What ends without a line to end it is still a message: the last word of a server that failed.
298
+ for (const message of runsLines(kept, '\n').messages) tell(message);
299
+ out.innerHTML = told.ended ? endedHtml(told) : cutHtml(told, told.broken || 'The server stopped telling the run.');
300
+ sayLastRun(told);
301
+ } catch {
302
+ out.innerHTML = cutHtml(told, stopping.signal.aborted ? '' : 'No answer from the server: it may have stopped.');
303
+ } finally {
304
+ prog.textContent = '';
305
+ stopsRun = null;
306
+ setRunning(false);
307
+ settleRows();
308
+ }
309
+ }
310
+
311
+ /** What a ▶ does: refuses while a run is under way, asks again for a database on another machine, runs. */
312
+ function goRuns(box, ref, button) {
313
+ const health = served();
314
+ const problem = $('.rn-bar .err', box);
315
+ if (!health || health.protected) return;
316
+ problem.textContent = '';
317
+ if (running) problem.textContent = 'A run is under way: wait for it.';
318
+ else if (onOtherMachine(health.target) && box.dataset.armed !== ref) {
319
+ box.dataset.armed = ref;
320
+ problem.textContent = `A run replaces what the database of ${servedHost()} holds, which is on another machine: ask again to run anyway.`;
321
+ button.focus();
322
+ } else {
323
+ delete box.dataset.armed;
324
+ sendRuns(box, ref);
325
+ }
326
+ }
327
+
328
+ /** What folds the table and narrows it to the failures: on every runner, served or not. */
329
+ const VIEW = '<label class="rn-only"><input type="checkbox" data-bad> Failures only</label><button type="button" class="tb sm" data-unfold>Expand all</button><button type="button" class="tb sm" data-fold>Collapse all</button>';
330
+
331
+ /** The bar of a runner whose page cannot run: why, and the command of a terminal, with its button to copy. */
332
+ function barWithCommand(box, why) {
333
+ const { runner, run } = runMeta();
334
+ return `<div class="line"><span>${esc(why)}</span><span class="sp"></span>${VIEW}</div><div class="line"><pre class="cmd">${esc(runsCommand(box.dataset.area || '', runner, run && run.mode))}</pre><button type="button" class="tb sm" data-copy-run>Copy</button></div>`;
335
+ }
336
+
337
+ /** The bar of a runner whose page is served: the mode, what runs every case and what stops it, how all the cases stand, and what a run does to the database. */
338
+ function barThatRuns(box, health) {
339
+ return `<div class="line">${modeHtml(health)}<button type="button" class="tb primary" data-go>${box.dataset.area ? 'Run this area' : 'Run every case'}</button><button type="button" class="tb" data-stop hidden>Stop</button><span class="rn-whole"></span><span class="prog" aria-live="polite"></span><span class="sp"></span>${VIEW}</div>
340
+ <p class="m s">Each case starts from its Background, whose seed replaces what the database of <b class="mono">${esc(servedHost())}</b> holds. A ▶ runs the cases of its row alone.</p>
341
+ <p class="err s" role="alert"></p>
342
+ <div class="line outcome" aria-live="polite"></div>`;
343
+ }
344
+
345
+ /** The bar of a runner, once it is known whether the page is served; and the ▶ of its rows, when it is. */
346
+ async function fillBar(box) {
347
+ const bar = $('.rn-bar', box);
348
+ bar.innerHTML = `<div class="line"><span class="m">Asking whether this page is served by the explorer…</span><span class="sp"></span>${VIEW}</div>`;
349
+ await servedKnown;
350
+ const health = served();
351
+ const only = box.classList.contains('only-bad');
352
+ if (!health) bar.innerHTML = barWithCommand(box, whyNotServed(location.protocol));
353
+ else bar.innerHTML = health.protected ? barWithCommand(box, whyNoRunHere(servedHost())) : barThatRuns(box, health);
354
+ $('[data-bad]', bar).checked = only;
355
+ box.classList.toggle('runs', Boolean(health) && !health.protected);
356
+ paintWhole(box);
357
+ setRunning(running);
358
+ }
359
+
360
+ /** A cell for what runs a row: its ▶, named after what it runs. A row that holds no case has nothing to run, and no ▶. */
361
+ function runCell(box, row) {
362
+ if (!row.matches('.rn-case') && !casesUnder(box, row).length) return '<td class="rn-run"></td>';
363
+ const what = row.matches('.rn-area') ? 'this area' : row.matches('.rn-op') ? 'this operation' : 'this case';
364
+ return `<td class="rn-run"><button type="button" class="rn-go" title="Run ${what}" aria-label="Run ${what}: ${esc(txt($('.rn-what', row)))}">${PLAY}</button></td>`;
365
+ }
366
+
367
+ /** A runner made ready, once: its rows fold and open, say how they stand, and end with what runs them. */
368
+ function fillRunner(box) {
369
+ box.dataset.filled = '1';
370
+ for (const more of $$('tr.rn-more', box)) more.remove();
371
+ // The name of a case opens it here, as the rest of its row does: the way to the case itself is in what opens.
372
+ for (const named of $$('tr.rn-case .rn-what > a', box)) named.replaceWith(...named.childNodes);
373
+ $('thead tr', box).insertAdjacentHTML('beforeend', '<th class="rn-run">Run</th>');
374
+ for (const row of $$('tbody > tr', box)) {
375
+ const group = !row.matches('.rn-case');
376
+ $('.rn-name', row).insertAdjacentHTML('afterbegin', `<button type="button" class="rn-tw" aria-expanded="false" aria-label="${group ? 'Its cases' : 'What its run told'}: ${esc(txt($('.rn-what', row)))}">${CHEVRON}</button>`);
377
+ row.insertAdjacentHTML('beforeend', runCell(box, row));
378
+ }
379
+ $('tbody', box).insertAdjacentHTML('beforeend', '<tr class="rn-none" hidden><td colspan="4" class="m">No case failed.</td></tr>');
380
+ paintRunner(box);
381
+ // An area shows its operations; an operation is folded, unless a case of it failed.
382
+ for (const row of $$('tr.rn-area', box)) setOpen(row, true);
383
+ for (const row of $$('tr.rn-op', box)) setOpen(row, row.classList.contains('bad'));
384
+ showRunner(box);
385
+ fillBar(box);
386
+ }
387
+
388
+ /** The runner of a page of tests, made ready the first time the page is shown. */
389
+ function addRunner(page) {
390
+ for (const box of $$('.runner', page)) if (!box.dataset.filled) fillRunner(box);
391
+ }
392
+
393
+ document.addEventListener('click', (event) => {
394
+ const box = event.target.closest('.runner');
395
+ if (!box) return;
396
+ const row = event.target.closest('tr.rn-area, tr.rn-op, tr.rn-case');
397
+ const button = event.target.closest('button');
398
+ if (button && button.matches('.rn-go')) goRuns(box, row.dataset.ref, button);
399
+ else if (button && button.matches('[data-go]')) goRuns(box, box.dataset.scope || '', button);
400
+ else if (button && button.matches('[data-stop]')) stopsRun && stopsRun();
401
+ else if (button && button.matches('[data-show]')) location.reload();
402
+ else if (button && button.matches('[data-copy-run]')) copy($('pre.cmd', button.closest('.rn-bar, .rn-detail')).textContent, 'Command copied');
403
+ else if (button && button.matches('[data-unfold], [data-fold]')) {
404
+ for (const one of $$('tr.rn-area, tr.rn-op', box)) setOpen(one, button.matches('[data-unfold]'));
405
+ showRunner(box);
406
+ } else if (row && (!button || button.matches('.rn-tw')) && !event.target.closest('a, input, select, label')) {
407
+ if (row.matches('.rn-case')) toggleTold(box, row);
408
+ else {
409
+ setOpen(row, !row.classList.contains('open'));
410
+ showRunner(box);
411
+ }
412
+ }
413
+ });
414
+
415
+ document.addEventListener('change', (event) => {
416
+ const box = event.target.closest('.runner');
417
+ if (!box || !event.target.matches('[data-bad]')) return;
418
+ box.classList.toggle('only-bad', event.target.checked);
419
+ showRunner(box);
420
+ });
@@ -64,3 +64,114 @@ function bodyText(body) {
64
64
 
65
65
  /** The mode a run takes: the one asked when the server runs it, else the one it takes when none is asked. */
66
66
  const modeOfRun = (health, asked) => (health.modes && health.modes.includes(asked) ? asked : health.mode);
67
+
68
+ /**
69
+ * The command that runs every case, of the suite or of one area: the area is asked by its
70
+ * directory, as the runner narrows a run, and the fast run when it was the last, or when there
71
+ * has been none.
72
+ */
73
+ function runsCommand(area, runner, lastMode) {
74
+ const fast = lastMode === undefined || lastMode === null || lastMode === 'fast';
75
+ return [...(area ? [`O=${plainWord(`${area}/`)}`] : []), ...(fast ? ['FAST=yes'] : []), runner].join(' ');
76
+ }
77
+
78
+ /** What a run of many cases has told, before it told anything. */
79
+ const runsStart = () => ({ mode: '', total: 0, done: 0, passed: 0, failed: 0, errors: 0, now: '', failures: [], ended: null, broken: '' });
80
+
81
+ /**
82
+ * What a run of many cases has told, once it told one thing more: what is to be run, the case
83
+ * that is being run, a case that was, with what did not hold when something did not, and the end.
84
+ * What is no message of a run is the server saying it failed: the run is broken, and says so.
85
+ */
86
+ function runsTold(told, message) {
87
+ if (!isRecord(message)) return told;
88
+ if (message.is === 'started') return { ...told, mode: String(message.mode || ''), total: Number(message.cases) || 0 };
89
+ if (message.is === 'running') return { ...told, now: String(message.ref || '') };
90
+ if (message.is === 'ran') {
91
+ const result = message.result === 'passed' ? 'passed' : message.result === 'failed' ? 'failed' : 'errors';
92
+ const failures = result === 'passed' ? told.failures : [...told.failures, { ref: String(message.ref || ''), result: message.result, failed: Array.isArray(message.failed) ? message.failed : [] }];
93
+ return { ...told, done: told.done + 1, [result]: told[result] + 1, now: '', failures };
94
+ }
95
+ if (message.is === 'ended') return { ...told, now: '', ended: message };
96
+ return typeof message.refused === 'string' ? { ...told, now: '', broken: message.refused } : told;
97
+ }
98
+
99
+ /**
100
+ * The messages a server sent, a line of JSON each, as they come in pieces that end anywhere: the
101
+ * lines that are whole, and what is kept for the piece that ends the last one. A line that is no
102
+ * JSON is not a message, and is left out.
103
+ */
104
+ function runsLines(kept, piece) {
105
+ const lines = (kept + piece).split('\n');
106
+ const rest = lines.pop();
107
+ const messages = [];
108
+ for (const line of lines) {
109
+ try {
110
+ if (line.trim()) messages.push(JSON.parse(line));
111
+ } catch {
112
+ /* not a message */
113
+ }
114
+ }
115
+ return { messages, kept: rest };
116
+ }
117
+
118
+ /** How far a run of many cases is, in words: how many of how many, and how they went. */
119
+ function runsWords(told) {
120
+ const went = [`${told.passed} passed`, `${told.failed} failed`, ...(told.errors ? [`${told.errors} could not be run`] : [])];
121
+ return `${told.done} of ${told.total} run · ${went.join(' · ')}`;
122
+ }
123
+
124
+ /** The result of a run of many cases, in a glyph and words: what failed first, since it is what is looked for. */
125
+ function runsVerdict(told) {
126
+ const bad = told.failed + told.errors;
127
+ const words = [...(told.failed ? [`${told.failed} failed`] : []), ...(told.errors ? [`${told.errors} could not be run`] : []), `${told.passed} passed`].join(', ');
128
+ return { glyph: bad ? '✗' : '✓', words, cls: bad ? 'ko' : 'ok' };
129
+ }
130
+
131
+ /** What is asked of the server so that it runs what a row names: an area, an operation or a case, by its anchor; the whole suite, by none. */
132
+ function runsScope(ref) {
133
+ if (ref.startsWith('area-')) return { area: ref };
134
+ if (ref.startsWith('op-')) return { operation: ref };
135
+ return ref.startsWith('case-') ? { case: ref } : {};
136
+ }
137
+
138
+ /** The cases a run is about to run, by their anchors, as its first message names them under their operations. */
139
+ const runsQueued = (message) => (isRecord(message) && Array.isArray(message.operations) ? message.operations.flatMap((one) => (isRecord(one) && Array.isArray(one.cases) ? one.cases.map(String) : [])) : []);
140
+
141
+ /** How a case stands, in a glyph and a word: what the last run decided of it, or where a run that is under way is with it. */
142
+ function caseStanding(state) {
143
+ if (state === 'queued') return { glyph: '·', word: 'queued', cls: 'nr' };
144
+ if (state === 'running') return { glyph: '◌', word: 'running…', cls: 'on' };
145
+ return state === 'passed' || state === 'failed' || state === 'error' ? verdictOf(state) : { glyph: '○', word: 'not run', cls: 'nr' };
146
+ }
147
+
148
+ /**
149
+ * How the cases of a row stand together, from how each does: how many passed and how many did
150
+ * not, of how many, as counts, as shares of a bar and in words. A case that waits for a run, or
151
+ * is being run, is not counted as run: the bar of its row grows again as the run gets to it.
152
+ */
153
+ function rowStanding(states) {
154
+ const count = (what) => states.filter((one) => one === what).length;
155
+ const [total, passed, failed, errors] = [states.length, count('passed'), count('failed'), count('error')];
156
+ const ran = passed + failed + errors;
157
+ const share = (of) => (total ? `${Math.round((of / total) * 1000) / 10}%` : '0%');
158
+ const words = [...(failed ? [`${failed} failed`] : []), ...(errors ? [`${errors} could not be run`] : []), `${ran} / ${total}`].join(' · ');
159
+ return { total, passed, bad: failed + errors, ran, busy: states.some((one) => one === 'queued' || one === 'running'), passedShare: share(passed), badShare: share(failed + errors), words };
160
+ }
161
+
162
+ /** What did not hold, as a list of what each says and the clause it is said of: a run tells it so, and the document keeps the sentences alone. */
163
+ function failedOf(text) {
164
+ try {
165
+ const kept = JSON.parse(text || '[]');
166
+ return Array.isArray(kept) ? kept.map((one) => (typeof one === 'string' ? { says: one } : one)).filter((one) => isRecord(one) && typeof one.says === 'string') : [];
167
+ } catch {
168
+ return [];
169
+ }
170
+ }
171
+
172
+ /** The time of a case, or of several together, as a column of them reads: in milliseconds under a second, in seconds from there. */
173
+ function timeText(ms) {
174
+ const value = Number(ms);
175
+ if (!Number.isFinite(value)) return '';
176
+ return value < 1000 ? `${Math.round(value)} ms` : secondsText(value / 1000);
177
+ }
@@ -60,5 +60,5 @@ async function sendThrough(panel, input, result) {
60
60
  const actor = $('[data-actor]', panel.body);
61
61
  const body = { operation: panel.page, input: input === null || input === undefined ? {} : input, ...(actor ? { actor: actor.value } : {}) };
62
62
  result.innerHTML = '<p class="m">Calling…</p>';
63
- result.innerHTML = servedAnswerHtml(await serverFetch('/api/call', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }, WAITS.call));
63
+ result.innerHTML = servedAnswerHtml(await serverFetch('api/call', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }, WAITS.call));
64
64
  }
@@ -1,6 +1,8 @@
1
1
  // Whether the page is served: by the server of the explorer, which answers a few calls from the
2
2
  // same origin (running a case, calling an operation, saving the review). The page finds out by
3
- // asking `/api/health` once, when it came over http(s); a file asks nothing. What it answers
3
+ // asking `api/health` once, when it came over http(s); a file asks nothing. The API is asked
4
+ // beside the page, `api/…` from where it is, so that an explorer served under a path of a larger
5
+ // site (`/spec/`) asks its own server there, and not whatever is at the root. What it answers
4
6
  // (`name`, `target`, `protected`, `modes`, `mode`) is kept, and `opspicy:served` tells when it is
5
7
  // known. A page that is not served says so with nothing, and reads as it always did.
6
8
 
@@ -35,7 +37,7 @@ async function serverFetch(path, init, within) {
35
37
  /** Asked once; settled when it is known whether the page is served, with the answer or with nothing. */
36
38
  const servedKnown = (async () => {
37
39
  if (!/^https?:$/.test(location.protocol)) return null;
38
- const answer = await serverFetch('/api/health', {}, WAITS.health);
40
+ const answer = await serverFetch('api/health', {}, WAITS.health);
39
41
  health = healthOf(answer, META.name);
40
42
  document.dispatchEvent(new Event('opspicy:served'));
41
43
  return health;
@@ -27,7 +27,7 @@ async function benchOf(options) {
27
27
  const report = reportAt(options.report);
28
28
  return report ? (report.fast ? 'fast' : 'complete') : null;
29
29
  };
30
- return { root, config, name: options.name ?? nameOf(options.suite), version: options.version, lastMode };
30
+ return { root, config, name: options.name ?? nameOf(options.suite), version: options.version, lastMode, ...(options.report ? { report: resolve(options.report) } : {}) };
31
31
  }
32
32
  const options = optionsOf(process.argv.slice(2));
33
33
  if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)
@@ -8,7 +8,7 @@
8
8
  // refused, and so is a body that is not what the page sends (machine.ts). The page itself is
9
9
  // refused to a host that is not this machine, wherever the server is offered on this machine only.
10
10
  import { createServer } from 'node:http';
11
- import { call, health, review, run } from './api.js';
11
+ import { call, health, isStreamed, ran, review, run, runs } from './api.js';
12
12
  import { isLoopback, ownPage } from './machine.js';
13
13
  import { documentKept } from './site.js';
14
14
  // Nothing served is shown inside another page: a page that frames this one could have its
@@ -68,11 +68,18 @@ function oneAtATime() {
68
68
  if (busy)
69
69
  return refused(409, 'A case is being run, or an operation called: one at a time.');
70
70
  busy = true;
71
+ let telling = false;
71
72
  try {
72
- return await work();
73
+ const answer = await work();
74
+ if (!isStreamed(answer))
75
+ return answer;
76
+ // What is told as it comes is under way until its last word: the next is refused until then.
77
+ telling = true;
78
+ return { ...answer, stream: (say, gone) => answer.stream(say, gone).finally(() => (busy = false)) };
73
79
  }
74
80
  finally {
75
- busy = false;
81
+ if (!telling)
82
+ busy = false;
76
83
  }
77
84
  };
78
85
  }
@@ -85,17 +92,32 @@ function apiOf(bench) {
85
92
  const asked = `${request.method} ${path}`;
86
93
  if (asked === 'GET /api/health')
87
94
  return health(bench);
95
+ if (asked === 'GET /api/ran')
96
+ return ran(bench, new URL(request.url ?? '/', 'http://x').searchParams.get('case'));
88
97
  if (asked === 'PUT /api/review')
89
98
  return written(bench, await bodyOf(request));
90
- if (asked !== 'POST /api/run' && asked !== 'POST /api/call')
99
+ const work = { 'POST /api/run': run, 'POST /api/runs': runs, 'POST /api/call': call }[asked];
100
+ if (!work)
91
101
  return refused(404, `The API has no ${asked}.`);
92
102
  const body = await jsonOf(request);
93
103
  if (!('asked' in body))
94
104
  return body;
95
- return alone(() => (asked === 'POST /api/run' ? run(bench, body.asked) : call(bench, body.asked)));
105
+ return alone(() => work(bench, body.asked));
96
106
  };
97
107
  }
98
108
  const ELSEWHERE = 'This explorer is served on this machine, and read there by a name of it: localhost, 127.0.0.1, [::1].\n';
109
+ /**
110
+ * What is told as it comes, over HTTP: a line of JSON for each message, sent as it is said. Who
111
+ * asked may leave before the end, which the connection says: nothing more is written, and what
112
+ * tells is told so.
113
+ */
114
+ function streamed(response, answer, failed) {
115
+ let gone = false;
116
+ response.on('close', () => (gone = true));
117
+ response.writeHead(200, { ...SECURED, 'content-type': 'application/x-ndjson; charset=utf-8', 'x-accel-buffering': 'no' });
118
+ const say = (message) => void (gone || response.write(`${JSON.stringify(message)}\n`));
119
+ answer.stream(say, () => gone).then(() => response.end(), failed);
120
+ }
99
121
  const READ_ONLY = async () => refused(404, 'This explorer is served to be read: it runs nothing. Serve it with --api, on this machine.');
100
122
  function page(request, response, path, written) {
101
123
  if (request.method !== 'GET' && request.method !== 'HEAD')
@@ -129,7 +151,7 @@ export function serverOf(options, bench) {
129
151
  const path = (request.url ?? '/').split('?')[0] ?? '/';
130
152
  if (path.startsWith('/api/')) {
131
153
  const failed = failing(response, 'application/json', JSON.stringify({ refused: 'The server failed: see its log.' }));
132
- return void api(request, path).then(({ status, body }) => response.writeHead(status, { ...SECURED, 'content-type': 'application/json' }).end(JSON.stringify(body)), failed);
154
+ return void api(request, path).then((answer) => (isStreamed(answer) ? streamed(response, answer, failed) : response.writeHead(answer.status, { ...SECURED, 'content-type': 'application/json' }).end(JSON.stringify(answer.body))), failed);
133
155
  }
134
156
  if (here && !isLoopback(request.headers.host ?? ''))
135
157
  return void response.writeHead(403, TEXT).end(ELSEWHERE);