@enspirit/opspicy 0.3.2 → 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.
Files changed (50) hide show
  1. package/README.md +56 -34
  2. package/bin/help.js +8 -2
  3. package/dist/configuration.d.ts +8 -2
  4. package/dist/explorer/api.js +162 -12
  5. package/dist/explorer/asking.js +51 -0
  6. package/dist/explorer/dependencies.js +117 -0
  7. package/dist/explorer/depending.js +139 -0
  8. package/dist/explorer/diagrams.js +176 -0
  9. package/dist/explorer/document.js +1 -0
  10. package/dist/explorer/elo-refs.js +6 -3
  11. package/dist/explorer/elo.js +18 -0
  12. package/dist/explorer/index.js +1 -2
  13. package/dist/explorer/operation.js +2 -4
  14. package/dist/explorer/pages.js +14 -16
  15. package/dist/explorer/script/depending.js +41 -0
  16. package/dist/explorer/script/main.js +1 -0
  17. package/dist/explorer/script/ranking.js +2 -2
  18. package/dist/explorer/script/review.js +1 -1
  19. package/dist/explorer/script/run.js +4 -1
  20. package/dist/explorer/script/runner.js +420 -0
  21. package/dist/explorer/script/running.js +111 -0
  22. package/dist/explorer/script/sending.js +1 -1
  23. package/dist/explorer/script/served.js +4 -2
  24. package/dist/explorer/serve.js +1 -1
  25. package/dist/explorer/server.js +28 -6
  26. package/dist/explorer/site.js +1 -1
  27. package/dist/explorer/style.css +91 -1
  28. package/dist/explorer/telling.js +2 -0
  29. package/dist/explorer/tests.js +51 -18
  30. package/dist/explorer/wiki.js +5 -3
  31. package/dist/files.js +27 -16
  32. package/dist/judging.js +2 -34
  33. package/dist/main.js +1 -1
  34. package/dist/meaning.js +2 -2
  35. package/dist/modelling.js +99 -25
  36. package/dist/naming.js +44 -15
  37. package/dist/notation.js +18 -3
  38. package/dist/observing.js +112 -0
  39. package/dist/planning.js +3 -3
  40. package/dist/reach.js +244 -140
  41. package/dist/reading.js +14 -18
  42. package/dist/running.js +18 -8
  43. package/dist/starting.js +4 -3
  44. package/dist/suite.js +8 -1
  45. package/dist/upgrade.js +3 -9
  46. package/dist/upgrading-state.js +197 -0
  47. package/dist/upgrading.js +13 -2
  48. package/dist/variables.js +62 -0
  49. package/dist/world.js +8 -39
  50. package/package.json +3 -2
@@ -2,6 +2,7 @@
2
2
  // every citizen at home on one of them, under an anchor of its own. What the suite says, and
3
3
  // nothing of a run: that is in tests.ts. Pure: the wiki is given, markup is what comes out.
4
4
  import { isA } from '../suite.js';
5
+ import { aroundShown, dependenciesPage } from './dependencies.js';
5
6
  import { citizens, described, elo, esc, link, list, mono, plural, said } from './html.js';
6
7
  import { areaTitle, crumbs, operationPage } from './operation.js';
7
8
  import { idOf } from './wiki.js';
@@ -71,12 +72,14 @@ const typeShown = (one, refs) => {
71
72
  const id = idOf('type', one.name);
72
73
  return { id, source: one.source, name: mono(one.name), description: said(one.description), formaldef: elo(`${one.name} = ${one.formaldef}`, refs, { self: id }) };
73
74
  };
74
- function areaPage(area, refs) {
75
+ function areaPage(area, wiki) {
76
+ const { refs } = wiki;
75
77
  const id = idOf('area', area.name);
76
78
  const operations = area.operations.map((one) => operationListed(id, one, [mono(`${one.entry.method} ${one.entry.path}`), esc(one.observes ? 'Observation' : 'Operation'), link(`#${idOf('agent', one.agent)}`, one.agent)]));
77
79
  const body = `${crumbs(link('#home', 'Specification'))}<h1>${esc(areaTitle(area.name))}</h1>
78
80
  <p class="lead">${said(area.description)}</p>
79
81
  <p class="sub">${esc(plural(area.operations.length, 'operation'))}, from ${mono(`${area.name}/`)}.</p>
82
+ ${aroundShown(wiki, area.name)}
80
83
  ${citizens('Operations', operations, { columns: ['Operation', '', 'Route', 'Kind', 'Performed by'], widths: ['20%', '40%', '22%', '9%', '9%'] })}
81
84
  ${citizens('Predicates', area.predicates.map((one) => definitionShown(one, refs)), { widths: WIDTHS })}
82
85
  ${citizens('Functions', area.functions.map((one) => definitionShown(one, refs)), { widths: WIDTHS })}
@@ -84,13 +87,7 @@ function areaPage(area, refs) {
84
87
  ${citizens('Types', area.types.map((one) => typeShown(one, refs)), { widths: WIDTHS })}`;
85
88
  return { id, kind: 'Area', title: areaTitle(area.name), source: area.source, said: area.description, area: area.name, quote: area.description, body };
86
89
  }
87
- const statesLinked = (names) => names.map((name) => link(`#${idOf('state', name)}`, name)).join(', ') || '<span class="m">none</span>';
88
90
  const operationsLinked = (all) => all.map((one) => link(`#${idOf('op', one.name)}`, one.name)).join(', ') || '<span class="m">none</span>';
89
- /** What an agent monitors, or controls: what the operations it performs do, in the order of the state. */
90
- const reachOfAgent = (agent, wiki, of) => {
91
- const all = new Set(performedBy(agent, wiki).flatMap((one) => one.reach[of]));
92
- return wiki.state.map((one) => one.name).filter((name) => all.has(name));
93
- };
94
91
  /** What an agent performs: the operations that name it, and those that name an agent it also is. */
95
92
  const performedBy = (agent, { agents, operations }) => operations.filter((one) => isA(agents, agent.name, one.agent));
96
93
  /** An agent, on a page of its own: what it is, who of the actors is one, and what it performs, itself or as an agent it also is. */
@@ -101,7 +98,7 @@ function agentPage(agent, wiki) {
101
98
  const performed = performedBy(agent, wiki).map((one) => operationListed(id, one, [link(`#${idOf('area', one.area)}`, areaTitle(one.area)), as(one)]));
102
99
  const body = `${crumbs(link('#home', 'Specification'), link('#agents', 'Agents'))}<h1>${esc(agent.name)}</h1>
103
100
  <p class="lead">${said(agent.description)}</p>
104
- <dl class="meta"><dt>Is also</dt><dd>${agent.is ? link(`#${idOf('agent', agent.is)}`, agent.is) : '<span class="m">nothing else</span>'}</dd><dt>Actors</dt><dd>${actors.join(', ') || '<span class="m">none</span>'}</dd><dt>Monitors</dt><dd>${statesLinked(reachOfAgent(agent, wiki, 'monitors'))}</dd><dt>Controls</dt><dd>${statesLinked(reachOfAgent(agent, wiki, 'controls'))}</dd></dl>
101
+ <dl class="meta"><dt>Is also</dt><dd>${agent.is ? link(`#${idOf('agent', agent.is)}`, agent.is) : '<span class="m">nothing else</span>'}</dd><dt>Actors</dt><dd>${actors.join(', ') || '<span class="m">none</span>'}</dd></dl>
105
102
  ${citizens('Performs', performed, { columns: ['Operation', '', 'Area', 'As'], widths: ['22%', '52%', '13%', '13%'] })}`;
106
103
  return { id, kind: 'Agent', title: agent.name, nav: 'agents', source: agent.source, said: agent.description, quote: agent.description, body };
107
104
  }
@@ -135,12 +132,13 @@ function typesPage(wiki) {
135
132
  return { id: 'types', kind: 'Types', title: 'Types', said: lead, body };
136
133
  }
137
134
  function statePage(wiki) {
138
- const by = (name, of) => operationsLinked(wiki.operations.filter((one) => one.reach[of].includes(name)));
139
- const state = wiki.state.map((one) => ({ id: idOf('state', one.name), source: one.source, name: mono(one.name), description: said(one.description), more: [mono(`GET ${one.path}`), one.type ? link(`#${idOf('type', one.type)}`, one.type) : '', by(one.name, 'monitors'), by(one.name, 'controls')] }));
140
- const relations = wiki.relations.map((one) => ({ id: idOf('relation', one.name), source: one.source, name: mono(`db.${one.name}`), description: said(one.description), more: [mono(one.table), esc(one.key.join(', ')), esc(one.attributes.join(', '))] }));
141
- const how = 'What is observed: by the routes that tell it, and behind them, in the database. Each state says the operations that must read it to meet their clauses (monitored by) and those that may change it (controlled by).';
142
- return homePage(wiki, 'state', 'state', 'State', how, `${citizens('State', state, { columns: ['State', '', 'Route', 'Type', 'Monitored by', 'Controlled by'], widths: ['11%', '27%', '18%', '10%', '17%', '17%'] })}
143
- ${citizens('Relations', relations, { columns: ['Relation', '', 'Table', 'Key', 'Attributes'], widths: ['14%', '40%', '12%', '8%', '26%'] })}`);
135
+ const typed = (type) => (type ? ` → ${link(`#${idOf('type', type)}`, type)}` : '');
136
+ const told = ({ web }) => (web ? [`${mono(`GET ${web.path}`)}${typed(web.type)}${web.member ? mono(`.${web.member.join('.')}`) : ''}`, ...(web.one ? [`${mono(`GET ${web.one.path}`)}${typed(web.one.type)}`] : [])] : []);
137
+ const kept = ({ db }) => (db ? [`<span class="m">db</span> ${mono(db.table)} <span class="m">by</span> ${esc(db.key.join(', '))}${db.attributes.length ? `<span class="m">:</span> ${esc(db.attributes.map((column) => (db.named?.[column] ? `${column} as ${db.named[column]}` : column)).join(', '))}` : ''}`] : []);
138
+ const named = (one) => `${mono(one.name)}${one.item ? `<br>${mono(`${one.item.name}(${one.item.key.join(', ')})`)}` : ''}`;
139
+ const state = wiki.state.map((one) => ({ id: idOf('state', one.name), source: one.source, name: named(one), description: said(one.description), more: [[...told(one), ...kept(one)].join('<br>')] }));
140
+ const how = 'What the system keeps, as state variables: a collection is named whole, and one item at a time by its key. Each says what observes it, the route that tells it through the front door and the table that shows it behind (read as db.<state>), ';
141
+ return homePage(wiki, 'state', 'state', 'State', how, citizens('State', state, { columns: ['State', '', 'Observed by'], widths: ['12%', '26%', '62%'] }));
144
142
  }
145
143
  function worldPage(wiki) {
146
144
  const actors = wiki.actors.map((one) => ({ id: idOf('actor', one.name), source: one.source, name: mono(one.name), description: said(one.description), more: [link(`#${idOf('agent', one.is)}`, one.is), one.signsIn ? 'signs in' : '<span class="m">not signed in</span>'] }));
@@ -154,6 +152,6 @@ function backgroundsPage(wiki) {
154
152
  }
155
153
  /** The pages of the specification, in the order the navigation shows them. */
156
154
  export function specPagesOf(wiki) {
157
- const around = { types: new Map(wiki.areas.flatMap((area) => area.types).map((one) => [one.name, one])), conditions: wiki.areas.flatMap((area) => area.conditions), refs: wiki.refs };
158
- return [overviewPage(wiki), agentsPage(wiki), statePage(wiki), ...wiki.areas.map((area) => areaPage(area, wiki.refs)), ...wiki.operations.map((one) => operationPage(one, around)), ...wiki.agents.map((one) => agentPage(one, wiki)), definitionsPage(wiki), typesPage(wiki), worldPage(wiki), backgroundsPage(wiki)];
155
+ const around = { types: new Map(wiki.areas.flatMap((area) => area.types).map((one) => [one.name, one])), conditions: wiki.areas.flatMap((area) => area.conditions), state: wiki.state, refs: wiki.refs };
156
+ return [overviewPage(wiki), agentsPage(wiki), statePage(wiki), ...wiki.areas.map((area) => areaPage(area, wiki)), ...wiki.operations.map((one) => operationPage(one, around)), ...wiki.agents.map((one) => agentPage(one, wiki)), definitionsPage(wiki), typesPage(wiki), dependenciesPage(wiki), worldPage(wiki), backgroundsPage(wiki)];
159
157
  }
@@ -0,0 +1,41 @@
1
+ // The drawings of what the areas depend on, on the Dependencies page and on the page of each area:
2
+ // an area, an operation or a name that is pointed at, or reached by the keyboard, shows what it is
3
+ // joined to, and the rest steps back. The drawings read without this: every arc is there.
4
+
5
+ /** What an element of a drawing is joined by: the arcs of an area, the wires of an operation or of a name. */
6
+ function joinedTo(drawing, element) {
7
+ const { area, dep } = element.dataset;
8
+ return $$('[data-from]', drawing).filter((wire) => (area ? wire.dataset.from === area || wire.dataset.to === area : wire.dataset.from === dep || wire.dataset.to === dep));
9
+ }
10
+
11
+ /** Lights what an element is joined to, and what is at the other end; nothing, when no element is given. */
12
+ function lightDependencies(drawing, element) {
13
+ for (const lit of $$('.lit', drawing)) lit.classList.remove('lit');
14
+ drawing.classList.toggle('lighting', Boolean(element));
15
+ if (!element) return;
16
+ element.classList.add('lit');
17
+ for (const wire of joinedTo(drawing, element)) {
18
+ wire.classList.add('lit');
19
+ for (const end of [wire.dataset.from, wire.dataset.to]) for (const other of $$('[data-area], [data-dep]', drawing)) if ((other.dataset.area || other.dataset.dep) === end) other.classList.add('lit');
20
+ }
21
+ }
22
+
23
+ for (const drawing of $$('svg.dep')) {
24
+ const pointed = (event) => event.target.closest('[data-area], [data-dep]');
25
+ drawing.addEventListener('pointerover', (event) => lightDependencies(drawing, pointed(event)));
26
+ drawing.addEventListener('pointerleave', () => lightDependencies(drawing, null));
27
+ drawing.addEventListener('focusin', (event) => lightDependencies(drawing, pointed(event)));
28
+ drawing.addEventListener('focusout', () => lightDependencies(drawing, null));
29
+ }
30
+
31
+ // The switch of the drawing of an area shows it in detail with no script. With it, the choice is
32
+ // that of every area, and is remembered.
33
+ const detailed = $$('.dep-detail-on');
34
+
35
+ function setDetailed(on) {
36
+ for (const one of detailed) one.checked = on;
37
+ local.set('opspicy.detailed', on);
38
+ }
39
+
40
+ for (const one of detailed) one.addEventListener('change', () => setDetailed(one.checked));
41
+ setDetailed(local.get('opspicy.detailed', false) === true);
@@ -41,6 +41,7 @@ function route() {
41
41
  hidePeek();
42
42
  showNotes(page);
43
43
  addCall(page);
44
+ addRunner(page);
44
45
  if (named && named.matches('tr.has-fd')) toggleRow(named, true);
45
46
  if (page.id === 'review') renderReview();
46
47
  $('#pnote').hidden = formalButton.hidden = !page.dataset.kind;
@@ -12,12 +12,12 @@ const SCOPES = {
12
12
  Definitions: ['Predicate', 'Function', 'Condition'],
13
13
  Clauses: ['Clause'],
14
14
  Cases: ['Case'],
15
- State: ['State', 'Relation'],
15
+ State: ['State'],
16
16
  Tests: ['Tests'],
17
17
  };
18
18
 
19
19
  /** The order the kinds are shown in; one that is not named here comes last. */
20
- const ORDER = ['Operation', 'Observation', 'Area', 'Type', 'Predicate', 'Function', 'Condition', 'Clause', 'Case', 'State', 'Relation', 'Agent', 'Actor', 'Background', 'Tests'];
20
+ const ORDER = ['Operation', 'Observation', 'Area', 'Type', 'Predicate', 'Function', 'Condition', 'Clause', 'Case', 'State', 'Agent', 'Actor', 'Background', 'Tests'];
21
21
 
22
22
  /** The words of what was typed: all of them must be found. */
23
23
  const wordsOf = (text) => text.trim().toLowerCase().split(/\s+/).filter(Boolean);
@@ -83,7 +83,7 @@ function downloadReview() {
83
83
 
84
84
  /** Has the server write the review to its disk, and says where; false, after saying why, when it did not. */
85
85
  async function writeReview() {
86
- const answer = await serverFetch('/api/review', { method: 'PUT', headers: { 'content-type': 'text/markdown' }, body: reviewText() }, WAITS.review);
86
+ const answer = await serverFetch('api/review', { method: 'PUT', headers: { 'content-type': 'text/markdown' }, body: reviewText() }, WAITS.review);
87
87
  const data = answer && answer.data;
88
88
  if (answer && answer.status === 200 && data && data.path) {
89
89
  toast(`Review written to ${data.path}`);
@@ -114,7 +114,10 @@ async function sendRun(box, ref, health) {
114
114
  button.disabled = true;
115
115
  out.innerHTML = '<p class="m">Running…</p>';
116
116
  try {
117
- out.innerHTML = answeredHtml(await serverFetch('/api/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ case: ref, mode: modeOfRun(health, mode) }) }, WAITS.run));
117
+ const answer = await serverFetch('api/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ case: ref, mode: modeOfRun(health, mode) }) }, WAITS.run);
118
+ out.innerHTML = answeredHtml(answer);
119
+ // The table of the tests says it too: the case has a row there, which tells its last run.
120
+ if (answer && answer.status === 200 && isRecord(answer.data)) tellRows({ is: 'ran', ref, ...answer.data });
118
121
  } catch {
119
122
  out.innerHTML = '<p class="err">What the server answered is not the telling of a run.</p>';
120
123
  } finally {
@@ -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
+ });