@enspirit/opspicy 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +325 -2
- package/bin/entry.js +48 -0
- package/bin/help.js +115 -0
- package/bin/opspicy +27 -0
- package/dist/addresses.js +27 -0
- package/dist/behind.js +64 -0
- package/dist/citizens.js +71 -0
- package/dist/configuration.d.ts +56 -0
- package/dist/configuration.js +66 -0
- package/dist/explorer/afresh.js +43 -0
- package/dist/explorer/api.js +101 -0
- package/dist/explorer/asking.js +59 -0
- package/dist/explorer/build.js +11 -0
- package/dist/explorer/calls.js +42 -0
- package/dist/explorer/document.js +117 -0
- package/dist/explorer/elo-refs.js +153 -0
- package/dist/explorer/elo.js +95 -0
- package/dist/explorer/fonts/OFL.txt +93 -0
- package/dist/explorer/fonts/dm-sans-latin.woff2 +0 -0
- package/dist/explorer/html.js +104 -0
- package/dist/explorer/index.js +62 -0
- package/dist/explorer/json.js +33 -0
- package/dist/explorer/machine.js +34 -0
- package/dist/explorer/masking.js +57 -0
- package/dist/explorer/operation.js +97 -0
- package/dist/explorer/pages.js +159 -0
- package/dist/explorer/script/base.js +103 -0
- package/dist/explorer/script/call.js +161 -0
- package/dist/explorer/script/calling.js +103 -0
- package/dist/explorer/script/connection.js +83 -0
- package/dist/explorer/script/copying.js +75 -0
- package/dist/explorer/script/filter.js +56 -0
- package/dist/explorer/script/formaldef.js +37 -0
- package/dist/explorer/script/main.js +82 -0
- package/dist/explorer/script/markdown.js +143 -0
- package/dist/explorer/script/notes.js +184 -0
- package/dist/explorer/script/noting.js +38 -0
- package/dist/explorer/script/peek.js +62 -0
- package/dist/explorer/script/peeking.js +19 -0
- package/dist/explorer/script/ranking.js +91 -0
- package/dist/explorer/script/review.js +126 -0
- package/dist/explorer/script/rows.js +58 -0
- package/dist/explorer/script/run.js +168 -0
- package/dist/explorer/script/running.js +66 -0
- package/dist/explorer/script/search.js +122 -0
- package/dist/explorer/script/sending.js +64 -0
- package/dist/explorer/script/served.js +51 -0
- package/dist/explorer/serve.js +41 -0
- package/dist/explorer/server.js +143 -0
- package/dist/explorer/site.js +78 -0
- package/dist/explorer/style.css +247 -0
- package/dist/explorer/telling.js +30 -0
- package/dist/explorer/tests.js +78 -0
- package/dist/explorer/wiki.js +90 -0
- package/dist/files.js +178 -0
- package/dist/finding.js +17 -0
- package/dist/judging.js +99 -0
- package/dist/lines.js +30 -0
- package/dist/main.js +128 -0
- package/dist/meaning.js +100 -0
- package/dist/modelling.js +173 -0
- package/dist/naming.js +84 -0
- package/dist/notation.js +119 -0
- package/dist/planning.js +41 -0
- package/dist/reach.js +177 -0
- package/dist/reading.js +135 -0
- package/dist/report-file.js +42 -0
- package/dist/report.js +63 -0
- package/dist/running.js +105 -0
- package/dist/selecting.js +71 -0
- package/dist/starting.js +41 -0
- package/dist/suite.js +32 -0
- package/dist/upgrade.js +27 -0
- package/dist/upgrading.js +76 -0
- package/dist/words.js +103 -0
- package/dist/world.js +129 -0
- package/package.json +57 -4
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// The search of the sidebar: what it finds takes the place of the page for as long as the field
|
|
2
|
+
// holds something, by kind, with scopes to narrow it. What is found and in what order is
|
|
3
|
+
// ranking.js; this part shows it, and follows the keys.
|
|
4
|
+
|
|
5
|
+
const q = $('#q');
|
|
6
|
+
const results = $('#results');
|
|
7
|
+
const entries = searchable(JSON.parse($('#index').textContent));
|
|
8
|
+
|
|
9
|
+
/** How many of a kind are shown before "Show all". */
|
|
10
|
+
const SHOWN = 5;
|
|
11
|
+
|
|
12
|
+
let scope = 'All';
|
|
13
|
+
let inFormaldefs = true;
|
|
14
|
+
const opened = new Set();
|
|
15
|
+
|
|
16
|
+
const many = (kind) => (kind.endsWith('s') ? kind : `${kind}s`);
|
|
17
|
+
/** A sentence is read as text; a name, as code. */
|
|
18
|
+
const SENTENCES = ['Clause', 'Case', 'Condition'];
|
|
19
|
+
const isPage = (entry) => !entry.ctx;
|
|
20
|
+
|
|
21
|
+
function hitHtml({ entry, code }, words) {
|
|
22
|
+
const name = `<span class="n${isPage(entry) || SENTENCES.includes(entry.k) ? '' : ' mono'}">${marked(entry.n, words)}</span>`;
|
|
23
|
+
const where = entry.ctx ? `<span class="k">in ${esc(entry.ctx)}</span>` : '';
|
|
24
|
+
const said = code ? marked(around(entry.c, words.find((word) => entry.lc.includes(word))), words) : marked(entry.x, words);
|
|
25
|
+
return `<a class="hit" id="found-${esc(entry.h)}" href="#${esc(entry.h)}">${name}${where}<span class="x${code ? ' mono' : ''}">${said}</span></a>`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function groupHtml({ kind, hits }, words, alone) {
|
|
29
|
+
const all = alone || opened.has(kind) || hits.length <= SHOWN + 1;
|
|
30
|
+
const more = all ? '' : `<button type="button" class="more" data-more="${esc(kind)}">Show all ${hits.length} ${esc(many(kind).toLowerCase())}</button>`;
|
|
31
|
+
return `<h3>${esc(many(kind))} <span class="m s">${hits.length}</span></h3>${(all ? hits : hits.slice(0, SHOWN)).map((hit) => hitHtml(hit, words)).join('')}${more}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function scopesHtml(hits) {
|
|
35
|
+
const button = (name) => {
|
|
36
|
+
const count = scoped(hits, name).length;
|
|
37
|
+
return `<button type="button" class="tb sm" data-scope="${name}" aria-pressed="${name === scope}"${count ? '' : ' disabled'}>${name} <span class="m">${count}</span></button>`;
|
|
38
|
+
};
|
|
39
|
+
const formaldefs = `<button type="button" class="tb sm" data-code aria-pressed="${inFormaldefs}" title="Also look inside the formaldefs"><b>ƒ</b> in formaldefs</button>`;
|
|
40
|
+
return `<div class="scopes">${Object.keys(SCOPES).map(button).join('')}${formaldefs}</div>`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function search() {
|
|
44
|
+
const words = wordsOf(q.value);
|
|
45
|
+
document.body.classList.toggle('searching', words.length > 0);
|
|
46
|
+
if (!words.length) return;
|
|
47
|
+
const hits = found(entries, words, inFormaldefs);
|
|
48
|
+
if (!scoped(hits, scope).length) scope = 'All';
|
|
49
|
+
const groups = grouped(scoped(hits, scope));
|
|
50
|
+
const title = `${hits.length ? `${hits.length} result${hits.length > 1 ? 's' : ''}` : 'Nothing'} for “${esc(q.value.trim())}”`;
|
|
51
|
+
const nothing = hits.length ? '' : '<p class="empty">No page, row or formaldef has these words. Try fewer words, or a part of a name.</p>';
|
|
52
|
+
results.innerHTML = `<h1>${title}</h1>${scopesHtml(hits)}${groups.map((group) => groupHtml(group, words, groups.length === 1)).join('')}${nothing}`;
|
|
53
|
+
pointAt(null);
|
|
54
|
+
scrollTo(0, 0);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Leaves the search: the page the address names is shown again. */
|
|
58
|
+
function leaveSearch() {
|
|
59
|
+
q.value = '';
|
|
60
|
+
scope = 'All';
|
|
61
|
+
opened.clear();
|
|
62
|
+
document.body.classList.remove('searching');
|
|
63
|
+
pointAt(null);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The result the arrows are on, or none. The cursor stays in the field, so the field says which
|
|
68
|
+
* one it is on (`aria-activedescendant`) and that one says it is the current one: who does not
|
|
69
|
+
* see the tint hears the result named.
|
|
70
|
+
*/
|
|
71
|
+
function pointAt(hit) {
|
|
72
|
+
const current = $('a.hit.cur', results);
|
|
73
|
+
if (current) current.classList.remove('cur');
|
|
74
|
+
if (current) current.removeAttribute('aria-current');
|
|
75
|
+
if (!hit) return q.removeAttribute('aria-activedescendant');
|
|
76
|
+
hit.classList.add('cur');
|
|
77
|
+
hit.setAttribute('aria-current', 'true');
|
|
78
|
+
q.setAttribute('aria-activedescendant', hit.id);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Moves through the results from the field. */
|
|
82
|
+
function step(by) {
|
|
83
|
+
const hits = $$('a.hit', results);
|
|
84
|
+
const next = hits[Math.max(0, Math.min(hits.length - 1, hits.indexOf($('a.hit.cur', results)) + by))];
|
|
85
|
+
pointAt(next || null);
|
|
86
|
+
if (next) next.scrollIntoView({ block: 'nearest' });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
q.setAttribute('aria-controls', 'results');
|
|
90
|
+
|
|
91
|
+
q.addEventListener('input', () => {
|
|
92
|
+
opened.clear();
|
|
93
|
+
search();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
q.addEventListener('keydown', (event) => {
|
|
97
|
+
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
98
|
+
event.preventDefault();
|
|
99
|
+
step(event.key === 'ArrowDown' ? 1 : -1);
|
|
100
|
+
} else if (event.key === 'Enter') {
|
|
101
|
+
const hit = $('a.hit.cur', results) || $('a.hit', results);
|
|
102
|
+
if (hit) hit.click();
|
|
103
|
+
} else if (event.key === 'Escape') {
|
|
104
|
+
leaveSearch();
|
|
105
|
+
q.blur();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
results.addEventListener('click', (event) => {
|
|
110
|
+
const narrowed = event.target.closest('[data-scope]');
|
|
111
|
+
const more = event.target.closest('[data-more]');
|
|
112
|
+
const hit = event.target.closest('a.hit');
|
|
113
|
+
const code = event.target.closest('[data-code]');
|
|
114
|
+
if (narrowed) scope = narrowed.dataset.scope;
|
|
115
|
+
if (code) inFormaldefs = !inFormaldefs;
|
|
116
|
+
if (more) opened.add(more.dataset.more);
|
|
117
|
+
if (narrowed || more || code) search();
|
|
118
|
+
if (!hit) return;
|
|
119
|
+
const same = hit.getAttribute('href') === location.hash;
|
|
120
|
+
leaveSearch();
|
|
121
|
+
if (same) route();
|
|
122
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// How a call leaves the page, and what it says of where it goes. Two ways: straight to the target
|
|
2
|
+
// of the Connection, with what the Connection carries; or, when the page is served and the
|
|
3
|
+
// Connection names no target, through the server, which signs in as an actor of the suite and
|
|
4
|
+
// calls the system it runs against. The page sends that server nothing of the Connection.
|
|
5
|
+
|
|
6
|
+
/** Whether calls go through the server of the page: it is served, and the Connection names no target. */
|
|
7
|
+
const throughServer = () => Boolean(served()) && !connection().target;
|
|
8
|
+
|
|
9
|
+
/** The target calls go to, the Connection's or else the server's. */
|
|
10
|
+
const callTarget = () => connection().target || (served() ? served().target : '');
|
|
11
|
+
|
|
12
|
+
/** What the panel of a call says of where it goes. */
|
|
13
|
+
function connectionLine(call) {
|
|
14
|
+
const { target, token, headers, withheld } = connection();
|
|
15
|
+
const carried = [token && 'your token', Object.keys(headers).length && `${Object.keys(headers).length} header${Object.keys(headers).length > 1 ? 's' : ''}`].filter(Boolean).join(' and ');
|
|
16
|
+
const nothing = `with nothing to say who calls${withheld ? ': the token and the headers were saved for another target, and are not sent to this one' : ''}`;
|
|
17
|
+
let where = target ? `Calls go to <b class="mono">${esc(target)}</b>, ${carried ? `with ${carried}` : nothing}.` : 'No target yet: say where calls go.';
|
|
18
|
+
if (throughServer()) where = `Calls go through this server to <b class="mono">${esc(served().target)}</b>${call.actors.length ? ', signed in as the actor chosen' : ''}.`;
|
|
19
|
+
return `${where} <button type="button" class="tb sm" data-conf>Connection</button>`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The choice of who calls, when calls go through the server: the actors of the suite who may perform the operation, or a word that none may. */
|
|
23
|
+
function actorHtml(call) {
|
|
24
|
+
if (!throughServer()) return '';
|
|
25
|
+
if (!call.actors.length) return '<span class="m s">Nobody of the world may perform it: it is sent without an actor.</span>';
|
|
26
|
+
return `<select aria-label="Call as" data-actor>${call.actors.map((name) => `<option value="${esc(name)}">as ${esc(name)}</option>`).join('')}</select>`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** An answer: its status, its time, and its body as it came, indented when it is JSON. */
|
|
30
|
+
function answerHtml(status, label, text) {
|
|
31
|
+
return `<p><span class="status">${esc(status)}</span> <span class="m">${esc(label)}</span></p><pre class="out">${text ? esc(bodyText(text)) : '<span class="m">No body.</span>'}</pre>`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Sends a call from the page, straight to the target, and shows what is answered: its status, its time and its body. */
|
|
35
|
+
async function sendCall(request, result) {
|
|
36
|
+
const { target, token, headers } = connection();
|
|
37
|
+
const url = `${target}${request.path}`;
|
|
38
|
+
const sent = { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers, ...(hasBody(request) ? { 'Content-Type': 'application/json' } : {}) };
|
|
39
|
+
const started = performance.now();
|
|
40
|
+
result.innerHTML = '<p class="m">Calling…</p>';
|
|
41
|
+
try {
|
|
42
|
+
const response = await fetch(url, { method: request.method, headers: sent, body: hasBody(request) ? JSON.stringify(request.body) : undefined });
|
|
43
|
+
result.innerHTML = answerHtml(response.status, `${response.statusText} · ${Math.round(performance.now() - started)} ms`, await response.text());
|
|
44
|
+
} catch {
|
|
45
|
+
result.innerHTML = `<p class="err">No answer from <span class="mono">${esc(url)}</span>. The server may be down, or may refuse calls from this page. The command to copy still works.</p>`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What the server of the page answered to a call: the answer of the system, or the sentence that says why not. */
|
|
50
|
+
function servedAnswerHtml(answer) {
|
|
51
|
+
if (!answer) return '<p class="err">No answer from the server: it may have stopped.</p>';
|
|
52
|
+
if (answer.status !== 200 || !answer.data) return `<p class="err">${esc((answer.data && answer.data.refused) || `The server answered ${answer.status}.`)}</p>`;
|
|
53
|
+
const { status, seconds, body, actor } = answer.data;
|
|
54
|
+
const who = actor ? ` · as ${actor}` : '';
|
|
55
|
+
return answerHtml(status, `${secondsText(seconds)}${who}`, body);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Sends a call through the server of the page: the operation, its input, and the actor chosen, and nothing of the Connection. */
|
|
59
|
+
async function sendThrough(panel, input, result) {
|
|
60
|
+
const actor = $('[data-actor]', panel.body);
|
|
61
|
+
const body = { operation: panel.page, input: input === null || input === undefined ? {} : input, ...(actor ? { actor: actor.value } : {}) };
|
|
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));
|
|
64
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Whether the page is served: by the server of the explorer, which answers a few calls from the
|
|
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
|
|
4
|
+
// (`name`, `target`, `protected`, `modes`, `mode`) is kept, and `opspicy:served` tells when it is
|
|
5
|
+
// known. A page that is not served says so with nothing, and reads as it always did.
|
|
6
|
+
|
|
7
|
+
let health = null;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* How long the server is given to answer, in milliseconds: its health at once, a call or the
|
|
11
|
+
* review in the time one takes, a run in the time of the longest case. One that has not answered
|
|
12
|
+
* by then is told as one that does not answer: nothing on the page waits for ever.
|
|
13
|
+
*/
|
|
14
|
+
const WAITS = { health: 4_000, call: 60_000, review: 15_000, run: 600_000 };
|
|
15
|
+
|
|
16
|
+
/** What the server said of itself; nothing when the page is not served, or while it is not known. */
|
|
17
|
+
const served = () => health;
|
|
18
|
+
|
|
19
|
+
/** What the server answered: its status and its JSON (nothing when it was not JSON); nothing at all when it did not answer, or not within the time it is given. */
|
|
20
|
+
async function serverFetch(path, init, within) {
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetch(path, { ...init, signal: AbortSignal.timeout(within) });
|
|
23
|
+
let data = null;
|
|
24
|
+
try {
|
|
25
|
+
data = await response.json();
|
|
26
|
+
} catch {
|
|
27
|
+
/* not JSON */
|
|
28
|
+
}
|
|
29
|
+
return { status: response.status, data };
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Asked once; settled when it is known whether the page is served, with the answer or with nothing. */
|
|
36
|
+
const servedKnown = (async () => {
|
|
37
|
+
if (!/^https?:$/.test(location.protocol)) return null;
|
|
38
|
+
const answer = await serverFetch('/api/health', {}, WAITS.health);
|
|
39
|
+
health = healthOf(answer, META.name);
|
|
40
|
+
document.dispatchEvent(new Event('opspicy:served'));
|
|
41
|
+
return health;
|
|
42
|
+
})();
|
|
43
|
+
|
|
44
|
+
/** The host of the system the suite runs against, as the server says it. */
|
|
45
|
+
const servedHost = () => {
|
|
46
|
+
try {
|
|
47
|
+
return health ? new URL(health.target).host : '';
|
|
48
|
+
} catch {
|
|
49
|
+
return '';
|
|
50
|
+
}
|
|
51
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// node src/explorer/serve.ts <suite> [--report=<file>] [--name=<name>] [--version=<version>] [--runner=<command>] [--host=127.0.0.1] [--port=8080] [--api]
|
|
2
|
+
//
|
|
3
|
+
// Serves the wiki of a suite, and of the report of its last run, over HTTP: the same document as
|
|
4
|
+
// build.ts writes, of the suite as it is at each request: written again once a file changed.
|
|
5
|
+
// Read-only, and needing no database nor stack; in a container, --host=0.0.0.0.
|
|
6
|
+
//
|
|
7
|
+
// With --api it also runs what its page asks (server.ts, api.ts): one case, a call as an actor of
|
|
8
|
+
// the world, the review written beside the specification. It then meets the system as the runner
|
|
9
|
+
// does, by the suite's config.ts, and is offered on this machine only.
|
|
10
|
+
import { resolve } from 'node:path';
|
|
11
|
+
import { NotConfigured, configurationOf } from '../configuration.js';
|
|
12
|
+
import { isProtected } from './api.js';
|
|
13
|
+
import { urlOf, isLoopback } from './machine.js';
|
|
14
|
+
import { serverOf } from './server.js';
|
|
15
|
+
import { nameOf, optionsOf, reportAt } from './site.js';
|
|
16
|
+
function stop(line) {
|
|
17
|
+
console.error(line);
|
|
18
|
+
process.exit(2);
|
|
19
|
+
}
|
|
20
|
+
/** What the API runs on: the suite, how it meets its system, and the mode of its last run. */
|
|
21
|
+
async function benchOf(options) {
|
|
22
|
+
if (!isLoopback(options.host))
|
|
23
|
+
stop(`The API runs cases, which empties a database: it is offered on this machine only, not on ${options.host}.`);
|
|
24
|
+
const root = resolve(options.suite);
|
|
25
|
+
const config = await configurationOf(root).catch((error) => (error instanceof NotConfigured ? stop(error.message) : Promise.reject(error)));
|
|
26
|
+
const lastMode = () => {
|
|
27
|
+
const report = reportAt(options.report);
|
|
28
|
+
return report ? (report.fast ? 'fast' : 'complete') : null;
|
|
29
|
+
};
|
|
30
|
+
return { root, config, name: options.name ?? nameOf(options.suite), version: options.version, lastMode };
|
|
31
|
+
}
|
|
32
|
+
const options = optionsOf(process.argv.slice(2));
|
|
33
|
+
if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)
|
|
34
|
+
stop(`--port says where the explorer is served, a number: got ${process.argv.find((arg) => arg.startsWith('--port='))}.`);
|
|
35
|
+
const bench = options.api ? await benchOf(options) : null;
|
|
36
|
+
const server = serverOf(options, bench).listen(options.port, options.host, () => {
|
|
37
|
+
// The port it has, which is not the one asked for when none was (`--port=0`).
|
|
38
|
+
console.log(`The explorer of ${options.suite} is at ${urlOf(options.host, server.address().port)}`);
|
|
39
|
+
if (bench)
|
|
40
|
+
console.log(`It runs what its page asks, against ${bench.config.api}${isProtected(bench.config) ? ', whose database it does not empty: no case is run, and only what is entered by GET is called' : ''}.`);
|
|
41
|
+
});
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// The explorer over HTTP: the one document, as the files of the suite are at each request (it is
|
|
2
|
+
// written again when they changed, and kept otherwise: afresh.ts), and, when it is asked to, the
|
|
3
|
+
// API its page runs cases and calls operations through (api.ts). Without the API it is read-only:
|
|
4
|
+
// it answers GET and HEAD, and needs neither a database nor a stack.
|
|
5
|
+
//
|
|
6
|
+
// The API changes things: a run empties a database. So it is offered on this machine only, to
|
|
7
|
+
// the page this server gave: a request that names another host, or comes from another origin, is
|
|
8
|
+
// refused, and so is a body that is not what the page sends (machine.ts). The page itself is
|
|
9
|
+
// refused to a host that is not this machine, wherever the server is offered on this machine only.
|
|
10
|
+
import { createServer } from 'node:http';
|
|
11
|
+
import { call, health, review, run } from './api.js';
|
|
12
|
+
import { isLoopback, ownPage } from './machine.js';
|
|
13
|
+
import { documentKept } from './site.js';
|
|
14
|
+
// Nothing served is shown inside another page: a page that frames this one could have its
|
|
15
|
+
// reader click what runs a case, and that click would be the page's own.
|
|
16
|
+
const SECURED = {
|
|
17
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; font-src data:; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'self' http: https:; frame-ancestors 'none'",
|
|
18
|
+
'x-frame-options': 'DENY',
|
|
19
|
+
'x-content-type-options': 'nosniff',
|
|
20
|
+
'referrer-policy': 'no-referrer',
|
|
21
|
+
'cache-control': 'no-store',
|
|
22
|
+
};
|
|
23
|
+
const TEXT = { ...SECURED, 'content-type': 'text/plain; charset=utf-8' };
|
|
24
|
+
const LIMIT = 1_000_000;
|
|
25
|
+
const refused = (status, why) => ({ status, body: { refused: why } });
|
|
26
|
+
const NOT_JSON = refused(400, 'What is asked is JSON, said as application/json.');
|
|
27
|
+
const TOO_MUCH = refused(413, `What is asked is more than the API takes: ${LIMIT / 1_000_000} MB.`);
|
|
28
|
+
const written = (bench, markdown) => (markdown === null ? TOO_MUCH : review(bench, markdown));
|
|
29
|
+
/**
|
|
30
|
+
* What a request carries, as text; nothing when it is more than the API takes, in bytes. What is
|
|
31
|
+
* over is read and not kept: the refusal waits for the end of what is sent, so that whoever sent
|
|
32
|
+
* it is there to read it.
|
|
33
|
+
*/
|
|
34
|
+
function bodyOf(request) {
|
|
35
|
+
return new Promise((resolve) => {
|
|
36
|
+
let chunks = [];
|
|
37
|
+
let bytes = 0;
|
|
38
|
+
request.on('data', (chunk) => {
|
|
39
|
+
bytes += chunk.length;
|
|
40
|
+
chunks = bytes > LIMIT ? [] : [...chunks, chunk];
|
|
41
|
+
});
|
|
42
|
+
request.on('end', () => resolve(bytes > LIMIT ? null : Buffer.concat(chunks).toString('utf8')));
|
|
43
|
+
request.on('error', () => resolve(null));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** What a request asks, as JSON said as such; a refusal otherwise. */
|
|
47
|
+
async function jsonOf(request) {
|
|
48
|
+
if (!(request.headers['content-type'] ?? '').startsWith('application/json'))
|
|
49
|
+
return NOT_JSON;
|
|
50
|
+
const text = await bodyOf(request);
|
|
51
|
+
if (text === null)
|
|
52
|
+
return TOO_MUCH;
|
|
53
|
+
try {
|
|
54
|
+
return { asked: JSON.parse(text) };
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return NOT_JSON;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* One at a time. A call changes the state a case is judged on, and a case puts back the state a
|
|
62
|
+
* call was made on: whatever reaches the system is alone to do so, and what is asked meanwhile
|
|
63
|
+
* is refused.
|
|
64
|
+
*/
|
|
65
|
+
function oneAtATime() {
|
|
66
|
+
let busy = false;
|
|
67
|
+
return async (work) => {
|
|
68
|
+
if (busy)
|
|
69
|
+
return refused(409, 'A case is being run, or an operation called: one at a time.');
|
|
70
|
+
busy = true;
|
|
71
|
+
try {
|
|
72
|
+
return await work();
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
busy = false;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** What the API answers a request: a refusal for what is not the page's own, not understood, or asked while a case runs or an operation is called. */
|
|
80
|
+
function apiOf(bench) {
|
|
81
|
+
const alone = oneAtATime();
|
|
82
|
+
return async (request, path) => {
|
|
83
|
+
if (!ownPage(request.headers.host, request.headers.origin))
|
|
84
|
+
return refused(403, 'The API answers the page this server gave, on this machine, and nobody else.');
|
|
85
|
+
const asked = `${request.method} ${path}`;
|
|
86
|
+
if (asked === 'GET /api/health')
|
|
87
|
+
return health(bench);
|
|
88
|
+
if (asked === 'PUT /api/review')
|
|
89
|
+
return written(bench, await bodyOf(request));
|
|
90
|
+
if (asked !== 'POST /api/run' && asked !== 'POST /api/call')
|
|
91
|
+
return refused(404, `The API has no ${asked}.`);
|
|
92
|
+
const body = await jsonOf(request);
|
|
93
|
+
if (!('asked' in body))
|
|
94
|
+
return body;
|
|
95
|
+
return alone(() => (asked === 'POST /api/run' ? run(bench, body.asked) : call(bench, body.asked)));
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const ELSEWHERE = 'This explorer is served on this machine, and read there by a name of it: localhost, 127.0.0.1, [::1].\n';
|
|
99
|
+
const READ_ONLY = async () => refused(404, 'This explorer is served to be read: it runs nothing. Serve it with --api, on this machine.');
|
|
100
|
+
function page(request, response, path, written) {
|
|
101
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
102
|
+
return void response.writeHead(405, { ...TEXT, allow: 'GET, HEAD' }).end('Read-only.\n');
|
|
103
|
+
// A browser asks for an icon whatever the page says: there is none, and that is no error of the page.
|
|
104
|
+
if (path === '/favicon.ico')
|
|
105
|
+
return void response.writeHead(204, SECURED).end();
|
|
106
|
+
if (path !== '/' && path !== '/index.html')
|
|
107
|
+
return void response.writeHead(404, TEXT).end('Not found: the explorer is one page, at /.\n');
|
|
108
|
+
// Written before anything is said of it: a document that cannot be written is not answered as one.
|
|
109
|
+
const document = written();
|
|
110
|
+
response.writeHead(200, { ...SECURED, 'content-type': 'text/html; charset=utf-8' }).end(request.method === 'HEAD' ? undefined : document);
|
|
111
|
+
}
|
|
112
|
+
/** What went wrong is said in the log of the server, and the answer says only that something did: as text for the page, as a refusal for the API. */
|
|
113
|
+
function failing(response, type, said) {
|
|
114
|
+
return (error) => {
|
|
115
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
116
|
+
if (!response.headersSent)
|
|
117
|
+
response.writeHead(500, { ...SECURED, 'content-type': type });
|
|
118
|
+
response.end(said);
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** The server of an explorer: of its page, and of the API when a bench is given to run on. */
|
|
122
|
+
export function serverOf(options, bench) {
|
|
123
|
+
const api = bench ? apiOf(bench) : READ_ONLY;
|
|
124
|
+
// Offered on this machine, it is read by a name of this machine: a name of another site that
|
|
125
|
+
// was made to lead here (DNS rebinding) would let a page of that site read the specification.
|
|
126
|
+
const here = isLoopback(options.host);
|
|
127
|
+
const document = documentKept(options);
|
|
128
|
+
return createServer((request, response) => {
|
|
129
|
+
const path = (request.url ?? '/').split('?')[0] ?? '/';
|
|
130
|
+
if (path.startsWith('/api/')) {
|
|
131
|
+
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);
|
|
133
|
+
}
|
|
134
|
+
if (here && !isLoopback(request.headers.host ?? ''))
|
|
135
|
+
return void response.writeHead(403, TEXT).end(ELSEWHERE);
|
|
136
|
+
try {
|
|
137
|
+
page(request, response, path, document);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
failing(response, TEXT['content-type'], 'The explorer could not be written: see the log of its server.\n')(error);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The wiki of a suite on disk, and of the report of its last run: the one document both the file
|
|
2
|
+
// and the server give. An edited specification or a new run shows at the next asking: the suite
|
|
3
|
+
// is read again when its files are no longer what they were (afresh.ts).
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { basename, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { SPECIFICATION } from '../files.js';
|
|
8
|
+
import { parseReport } from '../report-file.js';
|
|
9
|
+
import { kept, stampOf, suiteAt } from './afresh.js';
|
|
10
|
+
import { documentOf } from './document.js';
|
|
11
|
+
import { wikiOf } from './wiki.js';
|
|
12
|
+
const here = (path) => new URL(path, import.meta.url);
|
|
13
|
+
/** The parts of the page's script, in the order they are read: a part names what those before it declare. The buttons of a row are in the order of the parts that add them: ƒ (rows), ▶ (run), ✎ (notes). */
|
|
14
|
+
const PARTS = ['base', 'formaldef', 'ranking', 'search', 'rows', 'filter', 'peeking', 'peek', 'markdown', 'noting', 'calling', 'copying', 'served', 'running', 'run', 'notes', 'review', 'connection', 'sending', 'call', 'main'];
|
|
15
|
+
/** The style, with its one font inside it: the page fetches nothing. */
|
|
16
|
+
const styleHere = () => {
|
|
17
|
+
const font = readFileSync(here('./fonts/dm-sans-latin.woff2')).toString('base64');
|
|
18
|
+
return `@font-face{font-family:"DM Sans";src:url(data:font/woff2;base64,${font}) format("woff2");font-weight:100 1000;font-style:normal;font-display:swap}\n${readFileSync(here('./style.css'), 'utf8')}`;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The script, its parts in one function: nothing of it is global. A part that throws while the
|
|
22
|
+
* page loads takes the mark of the script off the document, which then reads as it does with no
|
|
23
|
+
* script, every formaldef shown: half a script is worse than none. What was thrown is still told.
|
|
24
|
+
*/
|
|
25
|
+
const scriptHere = () => {
|
|
26
|
+
const parts = PARTS.map((part) => readFileSync(here(`./script/${part}.js`), 'utf8')).join('\n');
|
|
27
|
+
return `(() => {\n'use strict';\ntry {\n${parts}} catch (error) {\ndocument.documentElement.classList.remove('js');\nthrow error;\n}\n})();`;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* What builds the form an operation is called with: elo-form, the contrib of Elo, as its package
|
|
31
|
+
* gives it. Its standalone script, which defines `EloForm` with Elo and Luxon inside, and its
|
|
32
|
+
* style: the explorer is one document that fetches nothing, so it carries both.
|
|
33
|
+
*/
|
|
34
|
+
const packaged = (file) => readFileSync(fileURLToPath(import.meta.resolve(`@enspirit/elo-form/${file}`)), 'utf8');
|
|
35
|
+
const formHere = () => ({ css: packaged('elo-form.css'), script: packaged('standalone') });
|
|
36
|
+
/** What the document is dressed with, as this directory holds it. */
|
|
37
|
+
export const dressHere = () => ({ css: styleHere(), script: scriptHere(), form: formHere() });
|
|
38
|
+
/** The options of the command line: `<suite>`, `--report=`, `--out=`, `--name=`, `--version=`, `--runner=`, `--host=`, `--port=`, `--api`. */
|
|
39
|
+
export function optionsOf(args) {
|
|
40
|
+
const value = (name) => args.find((arg) => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
|
|
41
|
+
return {
|
|
42
|
+
suite: args.find((arg) => !arg.startsWith('--')) ?? '.',
|
|
43
|
+
report: value('report'),
|
|
44
|
+
out: value('out'),
|
|
45
|
+
name: value('name') || undefined,
|
|
46
|
+
version: value('version') || undefined,
|
|
47
|
+
runner: value('runner') || undefined,
|
|
48
|
+
host: value('host') ?? '127.0.0.1',
|
|
49
|
+
port: Number(value('port') ?? 8080),
|
|
50
|
+
api: args.includes('--api'),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** The report of a run, when there is one. A file that is not a report is a fault, not an absent run. */
|
|
54
|
+
export function reportAt(file) {
|
|
55
|
+
if (!file || !existsSync(file))
|
|
56
|
+
return null;
|
|
57
|
+
const report = parseReport(readFileSync(file, 'utf8'));
|
|
58
|
+
if (!report)
|
|
59
|
+
throw new Error(`${file} is not a report of opspicy`);
|
|
60
|
+
return report;
|
|
61
|
+
}
|
|
62
|
+
/** The name of a suite, when it is given none: that of the system its specification names, or of its directory. The page and its API say the same: the notes of one are kept under it. */
|
|
63
|
+
export const nameOf = (suite) => suiteAt(suite).model.system.name ?? basename(resolve(suite));
|
|
64
|
+
/** The whole wiki, as one HTML document, written now. */
|
|
65
|
+
export function documentAt({ suite, report, name, version, runner }) {
|
|
66
|
+
const read = suiteAt(suite);
|
|
67
|
+
const about = { name: name ?? read.model.system.name ?? basename(resolve(suite)), version, generated: new Date().toISOString(), runner: runner ?? `opspicy ${suite}` };
|
|
68
|
+
return documentOf(wikiOf(read, reportAt(report)), dressHere(), about);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The same document, as a server gives it: written again only when what it is made of is no
|
|
72
|
+
* longer what it was on disk (afresh.ts). That is what the suite says, how it is configured, the
|
|
73
|
+
* report of its last run, and what this directory dresses the document with.
|
|
74
|
+
*/
|
|
75
|
+
export function documentKept(options) {
|
|
76
|
+
const madeOf = [join(options.suite, SPECIFICATION), join(options.suite, 'config.ts'), options.report, fileURLToPath(here('.'))];
|
|
77
|
+
return kept(() => stampOf(...madeOf), () => documentAt(options));
|
|
78
|
+
}
|