@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.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +325 -2
  3. package/bin/entry.js +48 -0
  4. package/bin/help.js +115 -0
  5. package/bin/opspicy +27 -0
  6. package/dist/addresses.js +27 -0
  7. package/dist/behind.js +64 -0
  8. package/dist/citizens.js +71 -0
  9. package/dist/configuration.d.ts +56 -0
  10. package/dist/configuration.js +66 -0
  11. package/dist/explorer/afresh.js +43 -0
  12. package/dist/explorer/api.js +101 -0
  13. package/dist/explorer/asking.js +59 -0
  14. package/dist/explorer/build.js +11 -0
  15. package/dist/explorer/calls.js +42 -0
  16. package/dist/explorer/document.js +117 -0
  17. package/dist/explorer/elo-refs.js +153 -0
  18. package/dist/explorer/elo.js +95 -0
  19. package/dist/explorer/fonts/OFL.txt +93 -0
  20. package/dist/explorer/fonts/dm-sans-latin.woff2 +0 -0
  21. package/dist/explorer/html.js +104 -0
  22. package/dist/explorer/index.js +62 -0
  23. package/dist/explorer/json.js +33 -0
  24. package/dist/explorer/machine.js +34 -0
  25. package/dist/explorer/masking.js +57 -0
  26. package/dist/explorer/operation.js +97 -0
  27. package/dist/explorer/pages.js +159 -0
  28. package/dist/explorer/script/base.js +103 -0
  29. package/dist/explorer/script/call.js +161 -0
  30. package/dist/explorer/script/calling.js +103 -0
  31. package/dist/explorer/script/connection.js +83 -0
  32. package/dist/explorer/script/copying.js +75 -0
  33. package/dist/explorer/script/filter.js +56 -0
  34. package/dist/explorer/script/formaldef.js +37 -0
  35. package/dist/explorer/script/main.js +82 -0
  36. package/dist/explorer/script/markdown.js +143 -0
  37. package/dist/explorer/script/notes.js +184 -0
  38. package/dist/explorer/script/noting.js +38 -0
  39. package/dist/explorer/script/peek.js +62 -0
  40. package/dist/explorer/script/peeking.js +19 -0
  41. package/dist/explorer/script/ranking.js +91 -0
  42. package/dist/explorer/script/review.js +126 -0
  43. package/dist/explorer/script/rows.js +58 -0
  44. package/dist/explorer/script/run.js +168 -0
  45. package/dist/explorer/script/running.js +66 -0
  46. package/dist/explorer/script/search.js +122 -0
  47. package/dist/explorer/script/sending.js +64 -0
  48. package/dist/explorer/script/served.js +51 -0
  49. package/dist/explorer/serve.js +41 -0
  50. package/dist/explorer/server.js +143 -0
  51. package/dist/explorer/site.js +78 -0
  52. package/dist/explorer/style.css +247 -0
  53. package/dist/explorer/telling.js +30 -0
  54. package/dist/explorer/tests.js +78 -0
  55. package/dist/explorer/wiki.js +90 -0
  56. package/dist/files.js +178 -0
  57. package/dist/finding.js +17 -0
  58. package/dist/judging.js +99 -0
  59. package/dist/lines.js +30 -0
  60. package/dist/main.js +128 -0
  61. package/dist/meaning.js +100 -0
  62. package/dist/modelling.js +173 -0
  63. package/dist/naming.js +84 -0
  64. package/dist/notation.js +119 -0
  65. package/dist/planning.js +41 -0
  66. package/dist/reach.js +177 -0
  67. package/dist/reading.js +135 -0
  68. package/dist/report-file.js +42 -0
  69. package/dist/report.js +63 -0
  70. package/dist/running.js +105 -0
  71. package/dist/selecting.js +71 -0
  72. package/dist/starting.js +41 -0
  73. package/dist/suite.js +32 -0
  74. package/dist/upgrade.js +27 -0
  75. package/dist/upgrading.js +76 -0
  76. package/dist/words.js +103 -0
  77. package/dist/world.js +129 -0
  78. package/package.json +57 -4
@@ -0,0 +1,105 @@
1
+ // One case, run: the Background is set, the state observed, the operation called once, the
2
+ // state observed again, and the whole judged.
3
+ //
4
+ // Given the Background is set, once the server is at rest, and who calls is signed in (and
5
+ // whoever else looks on)
6
+ //
7
+ // What it did is kept in order, when the run asks to see it: its calls, and the steps that put
8
+ // it where it starts (the Background set, the server waited for), each with how long it took.
9
+ // When the entry is called with the input, and what it started is done
10
+ // Then judging.ts says what does not hold
11
+ import { Unrunnable, unrun, whole } from './finding.js';
12
+ import { inputMisfit, judge } from './judging.js';
13
+ import { observedIn } from './reach.js';
14
+ import { addressed, queryOf } from './notation.js';
15
+ import { witnessesOf } from './planning.js';
16
+ import { credentialsOf } from './suite.js';
17
+ import { atRest, browserOf, observe } from './world.js';
18
+ function ears(listening) {
19
+ const wire = [];
20
+ let now = 'signs in';
21
+ const step = async (said, work) => {
22
+ const started = Date.now();
23
+ try {
24
+ await work();
25
+ }
26
+ finally {
27
+ if (listening)
28
+ wire.push({ ...said, ms: Date.now() - started });
29
+ }
30
+ };
31
+ return { wire, doing: (what) => void (now = what), of: (who) => (listening ? (called) => void wire.push({ who, doing: now, ...called }) : undefined), step };
32
+ }
33
+ /** Waits for the server to have nothing under way, where the suite can tell: said as a step only then. */
34
+ const rested = (reach, heard) => (reach.database && reach.config.atRest ? heard.step({ doing: 'waits for the server' }, () => atRest(reach)) : atRest(reach));
35
+ /** An origin nobody called from before: where a system counts by origin (wrong guesses, say), a case answers for its own only. */
36
+ const originOf = (run, n) => `10.${run % 256}.${Math.floor(n / 256) % 256}.${n % 256}`;
37
+ /** What a formaldef reads as `world`: what the suite says of it, what each actor signs in with, and who calls. */
38
+ export function worldOf(model, kase) {
39
+ const actors = credentialsOf(model);
40
+ // Their name last: somebody who signs in with a `name` is still called what the world calls them.
41
+ return { ...model.world, actors, requester: { ...actors[kase.given.actor], name: kase.given.actor } };
42
+ }
43
+ async function call(api, operation, input) {
44
+ const { path, rest } = addressed(operation.entry.path, input);
45
+ if (operation.entry.method === 'GET')
46
+ return api.call('GET', `${path}${queryOf(rest)}`);
47
+ // Nothing left to say is said as an empty object: what is sent is JSON, whatever the method.
48
+ return api.call(operation.entry.method, path, rest ?? {});
49
+ }
50
+ /**
51
+ * Who a case signs in: who calls, and whoever looks on. Each is somebody of the world. A name the
52
+ * world does not have is nobody, and so is one that every record has something under
53
+ * (`constructor`): asked before the Background is set, since such a case cannot run.
54
+ */
55
+ export function callersOf(model, operation, kase) {
56
+ const held = credentialsOf(model);
57
+ const caller = (name) => {
58
+ if (!Object.hasOwn(held, name))
59
+ throw new Unrunnable(`nobody is called "${name}" in the world`);
60
+ return [name, held[name] ?? null];
61
+ };
62
+ return { requester: caller(kase.given.actor), witnesses: witnessesOf(operation, kase).map(caller) };
63
+ }
64
+ async function browsers(reach, callers, origin, heard) {
65
+ const witnesses = {};
66
+ for (const [name, held] of callers.witnesses)
67
+ witnesses[name] = await browserOf(reach.config, origin, name, held, heard.of(name));
68
+ const [actor, held] = callers.requester;
69
+ return { requester: await browserOf(reach.config, origin, actor, held, heard.of(actor)), witnesses };
70
+ }
71
+ /** Setting a Background empties the database. Whoever runs a case asks before; it is asked again here, where it is done, so that no caller sets one by forgetting to. */
72
+ function mayEmpty(config) {
73
+ if (config.mayEmptyTheDatabase !== true)
74
+ throw new Unrunnable('the configuration does not say that the database may be emptied, and setting a Background empties it');
75
+ }
76
+ async function run(reach, model, meaning, operation, kase, origin, heard) {
77
+ mayEmpty(reach.config);
78
+ const callers = callersOf(model, operation, kase);
79
+ await rested(reach, heard);
80
+ await heard.step({ doing: 'sets the Background', seed: kase.given.seed }, () => reach.config.background(kase.given.seed));
81
+ const { requester, witnesses } = await browsers(reach, callers, origin, heard);
82
+ const world = worldOf(model, kase);
83
+ // The fast run observes what the operation monitors and controls; the complete run, every state.
84
+ const only = reach.relations ? undefined : observedIn(operation.reach, model.state.map((one) => one.name));
85
+ heard.doing('observes, before');
86
+ const before = await observe(reach, model, requester, witnesses, only);
87
+ const input = typeof kase.input === 'string' ? meaning.value(kase.input, { before, world }, 'given') : kase.input;
88
+ heard.doing('calls');
89
+ const answer = await call(requester, operation, input);
90
+ // What an operation starts and does not wait for is part of what it brings about: the state is observed once it is done.
91
+ if (operation.entry.method !== 'GET' && answer.status < 400)
92
+ await rested(reach, heard);
93
+ heard.doing('observes, after');
94
+ const after = await observe(reach, model, requester, witnesses, only);
95
+ return [...inputMisfit(operation, kase, input, meaning), ...judge(operation, kase, { input, world, before, after, status: answer.status, body: answer.body }, meaning, reach.config.refusal)];
96
+ }
97
+ /** What a case decided, from what was found: told whole to who runs it, and kept without what was seen. */
98
+ export const outcomeOf = (kase, found, ms, wire = []) => ({ kase, findings: found.map(whole), kept: found.map((one) => one.says), ms, wire });
99
+ /** Runs a case. What keeps it from running at all is told as a finding, in other words than a failure of the product. */
100
+ export async function runCase(reach, model, meaning, operation, kase, at) {
101
+ const started = Date.now();
102
+ const heard = ears(at.listening ?? false);
103
+ const found = await run(reach, model, meaning, operation, kase, originOf(at.run, at.n), heard).catch((error) => [unrun(error)]);
104
+ return outcomeOf(kase, found, Date.now() - started, heard.wire);
105
+ }
@@ -0,0 +1,71 @@
1
+ export const ROBUST = ['all', 'no', 'only', 'generated'];
2
+ export const LEVELS = ['warn', 'info', 'debug', 'trace'];
3
+ const METHODS = ['GET', 'POST', 'PUT', 'DELETE'];
4
+ const YES = ['yes', 'true', '1', 'on'];
5
+ const NO = ['', 'no', 'false', '0', 'off'];
6
+ /** What was asked, and what of it cannot be understood: nothing is run on a guess. */
7
+ export function askedOf(env, flags = []) {
8
+ const problems = [];
9
+ const said = (name) => (env[name] ?? '').trim();
10
+ const yes = (name) => {
11
+ if (![...YES, ...NO].includes(said(name).toLowerCase()))
12
+ problems.push(`${name}=${said(name)}: yes or no`);
13
+ return YES.includes(said(name).toLowerCase());
14
+ };
15
+ const among = (name, known, otherwise) => {
16
+ const given = said(name).toLowerCase();
17
+ if (said(name) && !known.includes(given))
18
+ problems.push(`${name}=${said(name)}: one of ${known.filter((one) => one !== otherwise).join(', ')}`);
19
+ return said(name) && known.includes(given) ? given : otherwise;
20
+ };
21
+ const method = said('METHOD').toUpperCase();
22
+ if (method && !METHODS.includes(method))
23
+ problems.push(`METHOD=${said('METHOD')}: one of ${METHODS.join(', ')}`);
24
+ const asked = { operation: said('O'), method, kase: said('CASE'), robust: among('ROBUST', ROBUST, 'all'), failfast: yes('FAILFAST'), fast: yes('FAST') || flags.includes('--fast'), log: among('LOG_LEVEL', LEVELS, 'info') };
25
+ return { asked, problems };
26
+ }
27
+ const FLAGS = ['--check', '--fast'];
28
+ const REPORT = '--report=';
29
+ /**
30
+ * What the command is given, and what of it cannot be understood. A flag is held to what the
31
+ * environment is: one misspelt (`--chek`) would otherwise be a run where a reading was asked.
32
+ */
33
+ export function commandOf(args) {
34
+ const flags = args.filter((one) => one.startsWith('-'));
35
+ const suites = args.filter((one) => !one.startsWith('-'));
36
+ const reports = flags.filter((flag) => flag.startsWith(REPORT)).map((flag) => flag.slice(REPORT.length));
37
+ const problems = [
38
+ ...flags.filter((flag) => !FLAGS.includes(flag) && !flag.startsWith(REPORT)).map((flag) => `${flag}: one of ${FLAGS.join(', ')}, ${REPORT}<file>`),
39
+ ...(reports.some((file) => !file) ? [`${REPORT}: the file the report is written to`] : []),
40
+ ...(suites.length > 1 ? [`${suites.join(' ')}: one suite, a directory`] : []),
41
+ ];
42
+ return { command: { suite: suites[0] ?? '.', check: flags.includes('--check'), ...(reports.at(-1) ? { report: reports.at(-1) } : {}) }, problems };
43
+ }
44
+ const holds = (text, part) => text.toLowerCase().includes(part.toLowerCase());
45
+ /** Whether an operation is one of those asked for: by its name, its file or its route, and by its method. */
46
+ export const operationAsked = (operation, asked) => holds(`${operation.file} ${operation.name} ${operation.entry.path}`, asked.operation) && (!asked.method || operation.entry.method === asked.method);
47
+ /**
48
+ * What cannot be read, of what is run: a run narrowed to some operations is not stopped by the
49
+ * file of another. A problem is that of the file it begins with, whole: what
50
+ * `boards/operations/Read.yml` cannot say is not what `keyboards/operations/Read.yml` cannot.
51
+ */
52
+ export function problemsAsked(problems, operations, asked) {
53
+ const others = operations.filter((operation) => !operationAsked(operation, asked)).map((operation) => `${operation.file}: `);
54
+ return problems.filter((problem) => !others.some((file) => problem.startsWith(file)));
55
+ }
56
+ const KINDS = {
57
+ all: () => true,
58
+ no: (kase) => kase.kind === 'example',
59
+ only: (kase) => kase.kind === 'counterexample',
60
+ generated: (kase) => kase.generated,
61
+ };
62
+ /** The cases asked for, of those an operation has. */
63
+ export const casesAsked = (cases, asked) => cases.filter((kase) => KINDS[asked.robust](kase) && holds(kase.description, asked.kase));
64
+ /**
65
+ * Whether an operation that ran no case is told all the same: it has none at all, and that
66
+ * nothing shows it is a gap to tell. Not when the run was narrowed to some cases: it then says
67
+ * nothing of an operation, whether it has other cases or none.
68
+ */
69
+ export const toldWithNoCase = (all, asked) => all.length === 0 && !asked.kase && asked.robust === 'all';
70
+ /** Whether a run is of the whole suite: one that is not says so, since it passes less. */
71
+ export const narrowed = (asked) => [asked.operation && `O=${asked.operation}`, asked.method && `METHOD=${asked.method}`, asked.kase && `CASE=${asked.kase}`, asked.robust !== 'all' && `ROBUST=${asked.robust}`].filter((one) => Boolean(one));
@@ -0,0 +1,41 @@
1
+ // What a run needs before its first case: somewhere to write its report, the database it reads,
2
+ // a system that answers. Each that is missing is told in a sentence, as a `NotStarted`, and
3
+ // nothing is run: a run that dies on one of them after its cases has told nothing.
4
+ import { closeSync, openSync } from 'node:fs';
5
+ import { reader } from './world.js';
6
+ /** What keeps a run from starting: said in a line. */
7
+ export class NotStarted extends Error {
8
+ }
9
+ /** Why something failed, in a line: what is under a failure that only says it failed (`fetch failed`), and its code where it says nothing. */
10
+ export function why(error) {
11
+ const { message, code, cause } = (error ?? {});
12
+ if (cause)
13
+ return why(cause);
14
+ return (message || code || String(error)).split('\n')[0] ?? '';
15
+ }
16
+ /** A report can be written there: asked by opening the file as the run will, without touching what it holds. */
17
+ export function writable(file) {
18
+ try {
19
+ closeSync(openSync(file, 'a'));
20
+ }
21
+ catch (error) {
22
+ throw new NotStarted(`The report cannot be written to ${file}: ${why(error)}`);
23
+ }
24
+ }
25
+ /** How the run reaches what it reads: the database, when the configuration names one. Its address is not told: it holds a password. */
26
+ export async function reachOf(suite, config, fast) {
27
+ if (suite.model.relations.length > 0 && !fast && !config.database)
28
+ throw new NotStarted('The state names relations, and the configuration no database to read them from.');
29
+ const unreached = (error) => {
30
+ throw new NotStarted(`The database cannot be reached: ${why(error)}`);
31
+ };
32
+ return { config, database: config.database ? await reader(config.database).catch(unreached) : null, relations: !fast };
33
+ }
34
+ /** The system answers at its front door, whatever it answers: asked once, so that a system that is not there is one sentence and not every case. */
35
+ export async function answering(config, withinMs = 15_000) {
36
+ const silent = (error) => {
37
+ throw new NotStarted(`The system does not answer at ${config.api}: ${why(error)}`);
38
+ };
39
+ const response = await fetch(config.api, { redirect: 'manual', signal: AbortSignal.timeout(withinMs) }).catch(silent);
40
+ await response.body?.cancel();
41
+ }
package/dist/suite.js ADDED
@@ -0,0 +1,32 @@
1
+ export const PRE = ['DomPre', 'ReqPre'];
2
+ export const POST = ['DomPost', 'ReqPost'];
3
+ /** The four that can be checked, then when an operation is performed without being asked: told, since one call shows nothing of it. */
4
+ export const KINDS = [...PRE, ...POST];
5
+ export const TRIGGER = 'ReqTrig';
6
+ /** The clauses an operation says, each under its key, in the order they are shown: what it is, then what the rules demand of it. */
7
+ export const SAID = ['DomPre', 'DomPost', 'ReqPre', 'ReqPost', TRIGGER];
8
+ /** How a mark is written. */
9
+ export const MARKS = { x: 'checked', '+': 'complete', ' ': 'told' };
10
+ /** A suite that says nothing. */
11
+ export const NOTHING_SAID = { system: {}, descriptions: {}, areas: [], agents: [], backgrounds: [], actors: [], world: {}, state: [], relations: [], definitions: [], conditions: [], types: [] };
12
+ /** Two sentences are the same whatever their case and spacing. */
13
+ export const sameSentence = (a, b) => normal(a) === normal(b);
14
+ const normal = (sentence) => sentence.trim().replace(/\s+/g, ' ').toLowerCase();
15
+ export const isPre = (clause) => PRE.includes(clause.kind);
16
+ /**
17
+ * Whether a counterexample is for the type of the input: its input is not one, on purpose. Every
18
+ * operation refuses what is not of its type, a precondition no operation says; a counterexample
19
+ * that shows it refused names the type, `for: BoardGiven`, where another names a precondition.
20
+ */
21
+ export const isForType = (operation, kase) => kase.kind === 'counterexample' && Boolean(operation.input) && kase.for === operation.input;
22
+ /** The citizen of that name, among those of one kind. */
23
+ export const named = (all, name) => all.find((one) => one.name === name);
24
+ /** What each actor signs in with, by name: `world.actors`. */
25
+ export const credentialsOf = (model) => Object.fromEntries(model.actors.map((actor) => [actor.name, actor.with]));
26
+ /** Whether an agent is another, itself or through what it is: an Administrator is a Member, who is a Visitor. */
27
+ export function isA(agents, name, other, seen = []) {
28
+ if (name === other)
29
+ return true;
30
+ const next = named(agents, name)?.is;
31
+ return next !== undefined && !seen.includes(name) && isA(agents, next, other, [...seen, name]);
32
+ }
@@ -0,0 +1,27 @@
1
+ // node src/upgrade.ts [<suite>]
2
+ //
3
+ // Rewrites a suite written for an earlier opspicy in the form this one reads, in place, and says
4
+ // what it changed, then what it found and cannot decide, and, the first time, what no file shows
5
+ // (upgrading.ts). Run again, it finds nothing to do: 0. A suite with no specification/ is told
6
+ // so: 2.
7
+ import { upgrade } from './upgrading.js';
8
+ /** What changed and that no file of a suite shows: told once, when the suite is rewritten from an earlier form. */
9
+ const UNSEEN = [
10
+ '`opspicy` alone now says how it is used: a script that ran it with no argument, for the suite of its directory, runs `opspicy .`.',
11
+ 'After an example, every state that changed must be one the operation controls: a run tells `"<state>" changed, which <Operation> does not control`. The operation then says what it controls (`controls: [...]`), or a postcondition speaks of that state.',
12
+ 'The explorer goes by the name `system.yml` gives the system, when it gives one: the notes of a reader are kept under the name of the specification, which `--name=` still sets.',
13
+ ];
14
+ const suite = process.argv.slice(2).find((arg) => !arg.startsWith('-')) ?? '.';
15
+ try {
16
+ const { rewritten, found } = upgrade(suite);
17
+ const lines = rewritten.length ? [`${suite} is upgraded:`, ...rewritten.map((one) => ` ${one}`)] : [`${suite} is already in the form this opspicy reads: nothing to rewrite.`];
18
+ if (found.length)
19
+ lines.push('', 'To look at, which it cannot decide:', ...found.map((one) => ` ${one}`));
20
+ if (rewritten.length)
21
+ lines.push('', 'And what no file shows:', ...UNSEEN.map((one) => ` ${one}`), '', 'CHANGELOG.md says everything that changed.');
22
+ console.log(lines.join('\n'));
23
+ }
24
+ catch (error) {
25
+ console.error(error instanceof Error ? error.message : String(error));
26
+ process.exit(2);
27
+ }
@@ -0,0 +1,76 @@
1
+ // What `opspicy upgrade` does (upgrade.ts): rewrites a suite written for an earlier opspicy in
2
+ // the form this one reads, in place, and says what it changed. What it rewrites it keeps as it
3
+ // was written: its comments, its order, its quotes. Run again, it finds nothing to do.
4
+ //
5
+ // From 0.1 and 0.2, whose suites are written alike: areas.yml, agents.yml and backgrounds.yml were
6
+ // a list each. Each is now a map, of its description and its list (CHANGELOG.md): the list is moved
7
+ // under its key, as it was. What it cannot decide, it finds and says: a counterexample whose input
8
+ // is not of its operation's type, a description that was a value of the world. What no file shows
9
+ // (a script that runs `opspicy` alone, a state an operation changes and does not control) it says too.
10
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { YAMLMap, isSeq, parseDocument } from 'yaml';
13
+ import { readSuite } from './files.js';
14
+ import { meaningOf } from './meaning.js';
15
+ import { isForType } from './suite.js';
16
+ /** The files that were a list, and the key their list is now under. */
17
+ const LISTS = { 'areas.yml': 'areas', 'agents.yml': 'agents', 'backgrounds.yml': 'backgrounds' };
18
+ /** A file as this opspicy reads it, or nothing when it already is: its list, as it was written, under its key. */
19
+ export function upgraded(text, key) {
20
+ const document = parseDocument(text);
21
+ if (document.errors.length || !isSeq(document.contents))
22
+ return null;
23
+ const map = new YAMLMap();
24
+ map.add(document.createPair(key, document.contents));
25
+ // What was said above the list is said above the file, still: the parser gives it to the list,
26
+ // or to its first item.
27
+ const list = document.contents;
28
+ const first = list.items[0];
29
+ document.commentBefore = [document.commentBefore, list.commentBefore, first?.commentBefore].filter(Boolean).join('\n') || null;
30
+ list.commentBefore = undefined;
31
+ if (first)
32
+ first.commentBefore = undefined;
33
+ document.contents = map;
34
+ return document.toString();
35
+ }
36
+ /** What `world.yml` says as its `description`, when it says one: in 0.2, a value of the world; now, the text of its page. */
37
+ function worldDescribed(root) {
38
+ const path = join(root, 'world.yml');
39
+ if (!existsSync(path))
40
+ return [];
41
+ const world = parseDocument(readFileSync(path, 'utf8')).toJS();
42
+ return world && typeof world === 'object' && 'description' in world ? ['specification/world.yml: its "description" was a value of the world; it is now the text the World page leads with, in Markdown, and a formaldef no longer reads it as `world.description`: rename it, if a formaldef reads it'] : [];
43
+ }
44
+ /**
45
+ * The counterexamples whose input, written as data, is not of the type of their operation's input,
46
+ * and which are for a precondition: in 0.2 they passed, now they violate more than what they are
47
+ * for. Their input is corrected, or they say `for: <the type>`, where that is what they show.
48
+ */
49
+ function inputsOutOfType(suite) {
50
+ const read = readSuite(suite);
51
+ if (read.problems.length)
52
+ return read.problems.map((problem) => `it cannot be read: ${problem}`);
53
+ const meaning = meaningOf(read.types);
54
+ return read.operations.flatMap((operation) => operation.cases.flatMap((kase) => {
55
+ if (kase.kind !== 'counterexample' || !operation.input || isForType(operation, kase) || typeof kase.input === 'string')
56
+ return [];
57
+ const misfit = meaning.misfit(operation.input, kase.input);
58
+ return misfit ? [`specification/${operation.file}: counterexample "${kase.description}": its input is not a ${operation.input} (${misfit}): correct it, or say \`for: ${operation.input}\` where that is what it shows`] : [];
59
+ }));
60
+ }
61
+ /** Rewrites the files of a suite that are in an earlier form, and says which it rewrote, and what it found that it cannot decide. */
62
+ export function upgrade(suite) {
63
+ const root = join(suite, 'specification');
64
+ if (!existsSync(root))
65
+ throw new Error(`${suite} holds no specification/: nothing to upgrade`);
66
+ const rewritten = Object.entries(LISTS).flatMap(([file, key]) => {
67
+ const path = join(root, file);
68
+ const text = existsSync(path) ? upgraded(readFileSync(path, 'utf8'), key) : null;
69
+ if (text === null)
70
+ return [];
71
+ writeFileSync(path, text);
72
+ return [`specification/${file}: its list is now under "${key}", beside the description it may say`];
73
+ });
74
+ // What a suite of 0.2 said its own way is told when it is rewritten from that form, and once.
75
+ return { rewritten, found: [...(rewritten.length ? worldDescribed(root) : []), ...inputsOutOfType(suite)] };
76
+ }
package/dist/words.js ADDED
@@ -0,0 +1,103 @@
1
+ // The words an area says, as they are written, become citizens: its predicates and functions,
2
+ // its conditions, its types. Pure: what cannot be read is told as a problem, and never guessed.
3
+ import { citizenOf, listOf, sentenceOf } from './citizens.js';
4
+ import { placeOf } from './lines.js';
5
+ import { RESERVED, definitionsUsed } from './naming.js';
6
+ import { NO_REFUSAL, refuses, signatureOf, violatedOf } from './notation.js';
7
+ import { sameSentence } from './suite.js';
8
+ const FILES = { predicate: 'predicates', function: 'functions' };
9
+ const under = (where, problems) => problems.map((problem) => `${where}: ${problem}`);
10
+ /** A predicate or a function: its name says what it is given, `board(id)`, and its formaldef is in Elo. */
11
+ function definitionOf(kind, item, area, problems, source) {
12
+ const written = citizenOf(kind, item, problems, { formaldef: true });
13
+ if (!written.name || !written.formaldef)
14
+ return null;
15
+ try {
16
+ return { kind, ...signatureOf(written.name), description: written.description, formaldef: written.formaldef, area, source };
17
+ }
18
+ catch (error) {
19
+ problems.push(`${kind} "${written.name}": ${error instanceof Error ? error.message : error}`);
20
+ return null;
21
+ }
22
+ }
23
+ /** The predicates and the functions of every area, each under a name of its own that nothing else has, and none said in terms of itself. */
24
+ export function definitionsOf(areas, states, problems) {
25
+ const read = (said, kind) => {
26
+ const mine = [];
27
+ const place = placeOf(`${said.area}/${FILES[kind]}.yml`, said.lines?.[FILES[kind]]);
28
+ const found = listOf('the file', said[FILES[kind]], mine).map((item, at) => definitionOf(kind, item, said.area, mine, place(at))).filter((one) => one !== null);
29
+ problems.push(...under(`${said.area}/${FILES[kind]}.yml`, mine));
30
+ return found;
31
+ };
32
+ const all = areas.flatMap((said) => [...read(said, 'predicate'), ...read(said, 'function')]);
33
+ const names = all.map((one) => one.name);
34
+ for (const name of new Set(names.filter((one, at) => names.indexOf(one) !== at)))
35
+ problems.push(`"${name}" is said twice, of the predicates and the functions`);
36
+ for (const one of all)
37
+ if (RESERVED.includes(one.name) || states.includes(one.name))
38
+ problems.push(`${one.kind} "${one.name}": the name is taken by ${states.includes(one.name) ? 'a state' : 'the suite'}`);
39
+ for (const one of all) {
40
+ try {
41
+ definitionsUsed(one.name, all);
42
+ }
43
+ catch (error) {
44
+ problems.push(error instanceof Error ? error.message : String(error));
45
+ }
46
+ }
47
+ return all;
48
+ }
49
+ /** A condition: a sentence with its formaldef, and for some how it is violated. Named after where it stands when it gives itself no name. */
50
+ function conditionOf(item, area, at, problems, source) {
51
+ try {
52
+ const { name, description, formaldef, mark, raw } = sentenceOf('a condition', item, ['violated']);
53
+ if (!formaldef)
54
+ throw new Error(`condition "${description}" says its "formaldef": what several operations say in the same words is decided once`);
55
+ if (mark)
56
+ problems.push(`condition "${description}" says no mark: the clause that says it does`);
57
+ const violated = raw.violated === undefined ? undefined : violatedOf(raw.violated);
58
+ if (violated && !refuses(violated.then))
59
+ problems.push(`condition "${description}": "violated": ${NO_REFUSAL}`);
60
+ return { name: name ?? `${area}/conditions/${at + 1}`, description, formaldef, area, source, ...(violated ? { violated } : {}) };
61
+ }
62
+ catch (error) {
63
+ problems.push(error instanceof Error ? error.message : String(error));
64
+ return null;
65
+ }
66
+ }
67
+ /** The conditions of every area: a sentence is said once, wherever. */
68
+ export function conditionsOf(areas, problems) {
69
+ const all = areas.flatMap((said) => {
70
+ const mine = [];
71
+ const place = placeOf(`${said.area}/conditions.yml`, said.lines?.conditions);
72
+ const found = listOf('the file', said.conditions, mine).map((item, at) => conditionOf(item, said.area, at, mine, place(at))).filter((one) => one !== null);
73
+ problems.push(...under(`${said.area}/conditions.yml`, mine));
74
+ return found;
75
+ });
76
+ for (const [at, one] of all.entries())
77
+ if (all.findIndex((other) => sameSentence(other.description, one.description)) !== at)
78
+ problems.push(`condition "${one.description}" is said twice: its formaldef is given once`);
79
+ return all;
80
+ }
81
+ const DECLARED = /^([A-Z]\w*)\s*=\s*/;
82
+ const COMMENT = /^#\s?/;
83
+ /**
84
+ * The types an area declares, each a citizen: the comment right above it describes it, its name
85
+ * is what it declares, and what follows `=` is its formaldef, up to the next declaration or comment.
86
+ */
87
+ export function typesOf(text, area, problems = []) {
88
+ const lines = text.split('\n');
89
+ const starts = lines.flatMap((line, at) => (DECLARED.test(line) ? [at] : []));
90
+ return starts.map((at) => {
91
+ let first = at;
92
+ while (first > 0 && COMMENT.test(lines[first - 1] ?? ''))
93
+ first--;
94
+ let last = at + 1;
95
+ while (last < lines.length && !DECLARED.test(lines[last] ?? '') && !COMMENT.test(lines[last] ?? ''))
96
+ last++;
97
+ const name = (lines[at] ?? '').match(DECLARED)?.[1] ?? '';
98
+ const description = lines.slice(first, at).map((line) => line.replace(COMMENT, '').trim()).join(' ').trim();
99
+ if (!description)
100
+ problems.push(`${area}/types.elo: type "${name}" says its description, in a comment right above it`);
101
+ return { name, description, formaldef: lines.slice(at, last).join('\n').replace(DECLARED, '').trimEnd(), area, source: `${area}/types.elo:${at + 1}` };
102
+ });
103
+ }
package/dist/world.js ADDED
@@ -0,0 +1,129 @@
1
+ // What a suite does to the world and sees of it: it sets a Background, calls the front door as
2
+ // somebody, and observes. Everything that specifies anything goes through the front door; the
3
+ // Background is set as the configuration says; the relations are read from the database,
4
+ // behind the front door, and never written.
5
+ import pg from 'pg';
6
+ import { Unrunnable } from './finding.js';
7
+ function remember(jar, cookies) {
8
+ for (const cookie of cookies) {
9
+ const [name = '', ...value] = (cookie.split(';')[0] ?? '').split('=');
10
+ if (value.join('='))
11
+ jar.set(name.trim(), value.join('='));
12
+ else
13
+ jar.delete(name.trim());
14
+ }
15
+ }
16
+ async function bodyOf(response) {
17
+ const told = await response.text();
18
+ const type = response.headers.get('content-type') ?? '';
19
+ if (!type.includes('json'))
20
+ return type.startsWith('text/') ? told : null;
21
+ try {
22
+ return JSON.parse(told);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** A browser nobody is signed in on, calling from an origin when the system is told one. */
29
+ export function browser({ api, originHeader }, origin, hears) {
30
+ const jar = new Map();
31
+ const call = async (method, path, body) => {
32
+ const headers = { cookie: [...jar].map(([name, value]) => `${name}=${value}`).join('; ') };
33
+ if (originHeader)
34
+ headers[originHeader] = origin;
35
+ if (body !== undefined)
36
+ headers['content-type'] = 'application/json';
37
+ const started = Date.now();
38
+ const response = await fetch(`${api}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual' });
39
+ remember(jar, response.headers.getSetCookie());
40
+ const answer = { status: response.status, body: await bodyOf(response) };
41
+ hears?.({ method, path, sent: body, ...answer, ms: Date.now() - started });
42
+ return answer;
43
+ };
44
+ return { call };
45
+ }
46
+ /** The browser of an actor: signed in when they have something to sign in with, as a visitor's otherwise. */
47
+ export async function browserOf(config, origin, name, actor, hears) {
48
+ const theirs = browser(config, origin, hears);
49
+ if (actor)
50
+ await signedIn(config, theirs, actor, name);
51
+ return theirs;
52
+ }
53
+ /**
54
+ * Signs somebody in, as the configuration does it. What it throws when they cannot is not told:
55
+ * it was written for who wrote the configuration, and may hold what the actor signs in with or
56
+ * what the system answered. The call itself is on the wire, with its status, for who asks to see.
57
+ */
58
+ async function signedIn(config, theirs, actor, name) {
59
+ try {
60
+ await config.signIn(theirs, actor, name);
61
+ }
62
+ catch {
63
+ throw new Unrunnable(`"${name}" could not be signed in`);
64
+ }
65
+ }
66
+ /** The database, to read and nothing else. */
67
+ export async function reader(url) {
68
+ const client = new pg.Client({ connectionString: url, options: '-c default_transaction_read_only=on' });
69
+ await client.connect();
70
+ // A connection that drops while nothing is asked of it says so to whoever listens, and stops the
71
+ // run where it stands when nobody does. It is heard, and told by what is next asked of it: a
72
+ // case that could not be run.
73
+ client.on('error', () => { });
74
+ return client;
75
+ }
76
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
77
+ /**
78
+ * Waits for the server to have nothing under way, as the configuration tells it. Some
79
+ * operations start work that outlives their answer: seen at rest twice in a row, since such
80
+ * work may begin a moment after the answer.
81
+ */
82
+ export async function atRest({ config, database }, forMs = 15_000) {
83
+ if (!database || !config.atRest)
84
+ return;
85
+ const ask = async (sql) => (await database.query(sql)).rows;
86
+ const until = Date.now() + forMs;
87
+ let seenAtRest = 0;
88
+ while (seenAtRest < 2) {
89
+ if (Date.now() > until)
90
+ throw new Unrunnable('the server still has work under way');
91
+ seenAtRest = (await config.atRest(ask)) ? seenAtRest + 1 : 0;
92
+ if (seenAtRest < 2)
93
+ await pause(25);
94
+ }
95
+ }
96
+ async function tuples(database, { table, key, attributes }) {
97
+ const { rows } = await database.query(`SELECT ${[...key, ...attributes].join(', ')} FROM ${table} ORDER BY ${key.join(', ')}`);
98
+ return JSON.parse(JSON.stringify(rows));
99
+ }
100
+ /**
101
+ * What a route of the state tells somebody: what it answers, and nothing where it refuses them.
102
+ * A route that fails (a 5xx) refused nobody and told nothing: read as nothing, "nothing changed"
103
+ * would hold of a system that is broken, before and after. The state was not observed, and the
104
+ * case cannot be judged.
105
+ */
106
+ export function toldBy({ name, path }, answer) {
107
+ if (answer.status >= 500)
108
+ throw new Unrunnable(`the state "${name}" could not be observed: GET ${path} answered ${answer.status}`);
109
+ return answer.status === 200 ? answer.body : null;
110
+ }
111
+ /** What one browser is told by the routes of the state. */
112
+ async function seenBy(model, theirs) {
113
+ const seen = {};
114
+ for (const one of model.state)
115
+ seen[one.name] = toldBy(one, await theirs.call('GET', one.path));
116
+ return seen;
117
+ }
118
+ /** The state, now: as the requester sees it, as the witnesses do, and the relations of the database; only the states named, when some are. */
119
+ export async function observe(reach, model, requester, witnesses, only) {
120
+ const observed = only ? { ...model, state: model.state.filter((one) => only.includes(one.name)) } : model;
121
+ const state = await seenBy(observed, requester);
122
+ const others = {};
123
+ for (const [name, theirs] of Object.entries(witnesses))
124
+ others[name] = await seenBy(observed, theirs);
125
+ const db = {};
126
+ for (const relation of model.relations)
127
+ db[relation.name] = reach.database && reach.relations ? await tuples(reach.database, relation) : null;
128
+ return { ...state, seenBy: others, db };
129
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@enspirit/opspicy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "license": "MIT",
5
+ "description": "Specifies the operations of a system by their clauses, as sentences that Elo gives a meaning, and runs them black-box",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/enspirit/opspicy.git"
9
+ },
10
+ "homepage": "https://github.com/enspirit/opspicy",
11
+ "bugs": {
12
+ "url": "https://github.com/enspirit/opspicy/issues"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=22.18"
17
+ },
18
+ "bin": {
19
+ "opspicy": "bin/opspicy"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/configuration.d.ts",
24
+ "default": "./dist/configuration.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "bin",
29
+ "dist"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "scripts": {
35
+ "typecheck": "tsc -p tsconfig.json",
36
+ "test": "node --test --test-reporter=spec \"test/*.test.ts\"",
37
+ "test:browser": "node --test --test-reporter=spec \"test/browser/*.test.ts\"",
38
+ "test:package": "node --test --test-reporter=spec \"test/package/*.test.ts\"",
39
+ "build": "node build.ts",
40
+ "prepack": "npm run build",
41
+ "example": "node example/splitter.ts"
42
+ },
43
+ "dependencies": {
44
+ "@enspirit/elo": "1.2.4",
45
+ "@enspirit/elo-form": "0.3.0",
46
+ "@enspirit/highlightjs-elo": "1.0.0",
47
+ "highlight.js": "11.12.0",
48
+ "luxon": "3.7.2",
49
+ "pg": "8.23.1",
50
+ "yaml": "2.9.1"
51
+ },
52
+ "devDependencies": {
53
+ "@types/luxon": "3.7.6",
54
+ "@types/node": "22.20.7",
55
+ "@types/pg": "8.23.1",
56
+ "playwright-core": "1.65.1",
57
+ "typescript": "7.0.2"
58
+ }
59
+ }