@enspirit/opspicy 0.3.2 → 0.4.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/dist/upgrade.js CHANGED
@@ -5,20 +5,14 @@
5
5
  // (upgrading.ts). Run again, it finds nothing to do: 0. A suite with no specification/ is told
6
6
  // so: 2.
7
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
8
  const suite = process.argv.slice(2).find((arg) => !arg.startsWith('-')) ?? '.';
15
9
  try {
16
- const { rewritten, found } = upgrade(suite);
10
+ const { rewritten, found, unseen } = upgrade(suite);
17
11
  const lines = rewritten.length ? [`${suite} is upgraded:`, ...rewritten.map((one) => ` ${one}`)] : [`${suite} is already in the form this opspicy reads: nothing to rewrite.`];
18
12
  if (found.length)
19
13
  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.');
14
+ if (unseen.length)
15
+ lines.push('', 'And what no file shows:', ...unseen.map((one) => ` ${one}`), '', 'CHANGELOG.md says everything that changed.');
22
16
  console.log(lines.join('\n'));
23
17
  }
24
18
  catch (error) {
@@ -0,0 +1,197 @@
1
+ // What `opspicy upgrade` does to a suite of opspicy 0.3, whose state.yml said the routes of the
2
+ // state and, apart, the relations of the database: it is one state, which mechanisms observe.
3
+ //
4
+ // a state says its route as `web`, no longer as `formaldef`
5
+ // a relation is the `db` of the state of its name, or a state of its own that the database
6
+ // alone shows
7
+ // an item a function that finds one item of a state by its key, `board(id)`, is said by
8
+ // the state, as its `item`, and no longer by a functions.yml; a state the database
9
+ // shows, and that no function reads so, is given one after its name
10
+ // monitors, the keys that said what an operation reads and changes are removed: what its
11
+ // controls clauses read is derived from them, and nothing says what it changes
12
+ //
13
+ // Each file is kept as it was written otherwise: its comments, its order, its quotes.
14
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { parse as elo } from '@enspirit/elo';
17
+ import { isMap, isScalar, isSeq, parseDocument } from 'yaml';
18
+ import { signatureOf } from './notation.js';
19
+ /** What changed from 0.3 and that no file of a suite shows. */
20
+ const UNSEEN = [
21
+ 'What an example alone also shows, and an input the state gives, are read by the clauses that say them only: a case reads what its clauses read, and nothing more.',
22
+ 'What the database shows is read by the (+) clauses of a complete run, and by no fast run: a row is read where a clause reads it.',
23
+ 'What an operation changed is not checked: a clause that said nothing else moved, or that a state was controlled, may go with the keys that said so.',
24
+ ];
25
+ /**
26
+ * A document, written as it was: a list said in a line has no space within its brackets, and
27
+ * stays in its line however long it is.
28
+ */
29
+ function written(document) {
30
+ const inLine = (_all, key, items) => `${key} [${items.split('\n').map((item) => item.trim().replace(/,$/, '')).filter(Boolean).join(', ')}]`;
31
+ return document.toString({ flowCollectionPadding: false }).replace(/^(\s*[\w-]+:)\n\s*\[\n((?:[^\n\]]*\n)+?)\s*\]$/gm, inLine);
32
+ }
33
+ const text = (map, key) => String(map.get(key) ?? '').trim();
34
+ const items = (list) => (isSeq(list) ? list.items.filter(isMap) : []);
35
+ /** A YAML file as it is written, when it is there and reads. */
36
+ function documentAt(path) {
37
+ if (!existsSync(path))
38
+ return null;
39
+ const document = parseDocument(readFileSync(path, 'utf8'));
40
+ return document.errors.length ? null : document;
41
+ }
42
+ /** What a collection is read whole by, in a formaldef: its name, or its name with what stands for it when nobody is told it. */
43
+ const names = (node, state) => (node.type === 'variable' && node.name === state) || (node.type === 'alternative' && node.alternatives[0] !== undefined && names(node.alternatives[0], state));
44
+ /** The attribute a lambda finds one item by, `b ~> b.id == id`, given the one thing the function is given. */
45
+ function keyFound(lambda, given) {
46
+ if (lambda?.type !== 'lambda' || lambda.body.type !== 'binary' || lambda.body.operator !== '==')
47
+ return null;
48
+ const [each = ''] = lambda.params;
49
+ const column = (node) => (node.type === 'member_access' && node.object.type === 'variable' && node.object.name === each ? node.property : null);
50
+ const isGiven = (node) => node.type === 'variable' && node.name === given;
51
+ const { left, right } = lambda.body;
52
+ return isGiven(right) ? column(left) : isGiven(left) ? column(right) : null;
53
+ }
54
+ /** The key a function finds one item of a state by, when that is all it does: `find(boards, b ~> b.id == id)`, or the first of those a filter keeps. */
55
+ function findsBy(formaldef, given, state) {
56
+ if (given.length !== 1)
57
+ return null;
58
+ try {
59
+ const tree = elo(formaldef);
60
+ const found = tree.type === 'function_call' && tree.name === 'first' && tree.args.length === 1 ? tree.args[0] : tree;
61
+ if (found.type !== 'function_call' || !['find', 'filter'].includes(found.name) || (found.name === 'filter') !== (found !== tree))
62
+ return null;
63
+ return found.args[0] && names(found.args[0], state) ? keyFound(found.args[1], given[0]) : null;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** The predicates and the functions of every area, each where it is written. */
70
+ function wordsOf(root) {
71
+ const areas = readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
72
+ return areas.flatMap((area) => ['functions.yml', 'predicates.yml'].flatMap((name) => {
73
+ const file = join(area, name);
74
+ const document = documentAt(join(root, file));
75
+ if (!document || !isSeq(document.contents))
76
+ return [];
77
+ const list = document.contents;
78
+ return items(list).flatMap((at) => {
79
+ try {
80
+ const { name: called, parameters } = signatureOf(text(at, 'name'));
81
+ return [{ file, document, list, at, name: called, given: parameters }];
82
+ }
83
+ catch {
84
+ return [];
85
+ }
86
+ });
87
+ }));
88
+ }
89
+ /** One of a collection, after its name: `board` of `boards`, `category` of `categories`. */
90
+ const one = (name) => (name.endsWith('ies') ? `${name.slice(0, -3)}y` : name.endsWith('s') ? name.slice(0, -1) : `${name}Item`);
91
+ /** Says something of a state right after its description. */
92
+ function said(document, state, key, value) {
93
+ const after = state.items.findIndex((pair) => isScalar(pair.key) && pair.key.value === 'description');
94
+ state.items.splice(after + 1, 0, document.createPair(key, value));
95
+ }
96
+ /**
97
+ * A list of citizens without those of these names, as it was written otherwise: each goes with
98
+ * the comment right above it. Nothing when the file is not written as a list of `- name:` at
99
+ * the margin, or holds nothing else: it is then written anew.
100
+ */
101
+ function without(file, gone) {
102
+ const lines = file.split('\n');
103
+ const starts = lines.flatMap((line, at) => (/^- /.test(line) ? [at] : []));
104
+ const cut = new Set();
105
+ for (const name of gone) {
106
+ const at = starts.find((start) => lines[start].replace(/\s+/g, '') === `-name:${name.replace(/\s+/g, '')}`);
107
+ if (at === undefined)
108
+ return null;
109
+ let [first, last] = [at, at + 1];
110
+ while (first > 0 && /^#/.test(lines[first - 1]))
111
+ first--;
112
+ while (last < lines.length && !/^(- |#)/.test(lines[last]))
113
+ last++;
114
+ for (let line = first; line < last; line++)
115
+ cut.add(line);
116
+ }
117
+ const kept = lines.filter((_line, at) => !cut.has(at)).join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '');
118
+ return starts.length > gone.length ? kept : null;
119
+ }
120
+ /**
121
+ * The keys that said what an operation monitors and controls are removed, in a list or in a block:
122
+ * what its clauses read is derived from them, and nothing says what it changes. Each file keeps the
123
+ * rest of its text, its comments included.
124
+ */
125
+ function keysRemoved(root) {
126
+ const files = readdirSync(root, { recursive: true, encoding: 'utf8' }).filter((file) => /[\\/](operations|observations)[\\/][^\\/]+\.yml$/.test(file)).sort();
127
+ return files.flatMap((file) => {
128
+ const before = readFileSync(join(root, file), 'utf8');
129
+ const after = before.replace(/^(monitors|controls):.*(?:\n[ \t]+[^\n]*)*\n?/gm, '');
130
+ if (after !== before)
131
+ writeFileSync(join(root, file), after);
132
+ return after !== before ? [`specification/${file}: "monitors" and "controls" are removed: what its clauses read is derived from them, and nothing says what it changes`] : [];
133
+ });
134
+ }
135
+ /** Rewrites the state of a suite of opspicy 0.3, and what follows from it: says what it rewrote, what is left to look at, and what no file shows. */
136
+ export function stateUpgraded(root) {
137
+ const document = documentAt(join(root, 'state.yml'));
138
+ const states = items(document?.get('state', true));
139
+ const relations = items(document?.get('relations', true));
140
+ if (!document || !isMap(document.contents) || (!relations.length && !states.some((state) => state.has('formaldef')) && !document.has('relations')))
141
+ return { rewritten: keysRemoved(root), found: [], unseen: [] };
142
+ const words = wordsOf(root);
143
+ const taken = new Set([...states.map((state) => text(state, 'name')), ...relations.map((relation) => text(relation, 'name')), ...words.map((word) => word.name)]);
144
+ const [found, rewritten, touched] = [[], ['specification/state.yml: each state says what observes it, its route as "web" and its table as "db", and a collection its item'], new Set()];
145
+ if (!isSeq(document.get('state', true)))
146
+ document.set('state', document.createNode([]));
147
+ const list = document.get('state', true);
148
+ for (const state of states) {
149
+ const route = state.items.find((pair) => isScalar(pair.key) && pair.key.value === 'formaldef');
150
+ if (route && isScalar(route.key))
151
+ route.key.value = 'web';
152
+ const name = text(state, 'name');
153
+ const word = words.find((each) => findsBy(text(each.at, 'formaldef'), each.given, name));
154
+ if (!word)
155
+ continue;
156
+ said(document, state, 'item', `${word.name}(${findsBy(text(word.at, 'formaldef'), word.given, name)})`);
157
+ word.list.items.splice(word.list.items.indexOf(word.at), 1);
158
+ touched.add(word);
159
+ }
160
+ for (const relation of relations) {
161
+ const name = text(relation, 'name');
162
+ const key = relation.toJSON().key ?? [];
163
+ const existing = states.find((state) => text(state, 'name') === name);
164
+ // A relation that is no state yet becomes one as it was written, its comments and its place among the others kept.
165
+ const state = existing ?? relation;
166
+ if (!existing)
167
+ list.add(relation);
168
+ if (!state.has('item')) {
169
+ const item = taken.has(one(name)) ? `${one(name)}Kept` : one(name);
170
+ taken.add(item);
171
+ said(document, state, 'item', `${item}(${key.join(', ')})`);
172
+ found.push(`specification/state.yml: state "${name}": its item is called "${item}", after its name: call it as the suite would, and say a function that reads one so no longer`);
173
+ }
174
+ const known = signatureOf(text(state, 'item')).parameters;
175
+ if (String(known) !== String(key))
176
+ found.push(`specification/state.yml: state "${name}": its item is known by its ${known.join(', ')}, and its rows by their ${key.join(', ')}: "db" says, as its "key", the columns that hold the ${known.join(', ')} of the item`);
177
+ const shown = document.createNode({});
178
+ for (const said of ['table', 'key', 'attributes']) {
179
+ const pair = relation.items.find((each) => isScalar(each.key) && each.key.value === said);
180
+ if (pair && (said !== 'key' || String(known) !== String(key)))
181
+ shown.items.push(pair);
182
+ relation.delete(said);
183
+ }
184
+ state.add(document.createPair('db', shown));
185
+ }
186
+ document.delete('relations');
187
+ writeFileSync(join(root, 'state.yml'), written(document));
188
+ for (const file of new Set([...touched].map((word) => word.file))) {
189
+ const gone = [...touched].filter((word) => word.file === file);
190
+ writeFileSync(join(root, file), without(readFileSync(join(root, file), 'utf8'), gone.map((word) => text(word.at, 'name'))) ?? (gone[0].list.items.length ? written(gone[0].document) : '[]\n'));
191
+ rewritten.push(`specification/${file}: ${gone.map((word) => `"${word.name}"`).join(', ')} ${gone.length === 1 ? 'is' : 'are'} said by the state, as the item of a collection`);
192
+ }
193
+ const whole = items(document.get('state', true)).filter((state) => !state.has('item')).map((state) => text(state, 'name'));
194
+ if (whole.length)
195
+ found.push(`specification/state.yml: ${whole.map((name) => `"${name}"`).join(', ')} say${whole.length === 1 ? 's' : ''} no item, and ${whole.length === 1 ? 'is' : 'are'} read whole: one that is a collection says what an item of it is known by, as in \`item: board(id)\``);
196
+ return { rewritten: [...rewritten, ...keysRemoved(root)], found, unseen: UNSEEN };
197
+ }
package/dist/upgrading.js CHANGED
@@ -7,12 +7,16 @@
7
7
  // under its key, as it was. What it cannot decide, it finds and says: a counterexample whose input
8
8
  // is not of its operation's type, a description that was a value of the world. What no file shows
9
9
  // (a script that runs `opspicy` alone, a state an operation changes and does not control) it says too.
10
+ //
11
+ // From 0.3: state.yml said the routes of the state and, apart, the relations of the database.
12
+ // It is one state, which mechanisms observe (upgrading-state.ts).
10
13
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
11
14
  import { join } from 'node:path';
12
15
  import { YAMLMap, isSeq, parseDocument } from 'yaml';
13
16
  import { readSuite } from './files.js';
14
17
  import { meaningOf } from './meaning.js';
15
18
  import { isForType } from './suite.js';
19
+ import { stateUpgraded } from './upgrading-state.js';
16
20
  /** The files that were a list, and the key their list is now under. */
17
21
  const LISTS = { 'areas.yml': 'areas', 'agents.yml': 'agents', 'backgrounds.yml': 'backgrounds' };
18
22
  /** A file as this opspicy reads it, or nothing when it already is: its list, as it was written, under its key. */
@@ -33,6 +37,12 @@ export function upgraded(text, key) {
33
37
  document.contents = map;
34
38
  return document.toString();
35
39
  }
40
+ /** What changed from 0.2 and that no file of a suite shows: told once, when the suite is rewritten from that form. */
41
+ const UNSEEN = [
42
+ '`opspicy` alone now says how it is used: a script that ran it with no argument, for the suite of its directory, runs `opspicy .`.',
43
+ 'A case checks what its clauses say, and nothing else: a state that changed and that no clause speaks of is not told. What an operation changes is not said, and not checked.',
44
+ '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.',
45
+ ];
36
46
  /** 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
47
  function worldDescribed(root) {
38
48
  const path = join(root, 'world.yml');
@@ -71,6 +81,7 @@ export function upgrade(suite) {
71
81
  writeFileSync(path, text);
72
82
  return [`specification/${file}: its list is now under "${key}", beside the description it may say`];
73
83
  });
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)] };
84
+ const state = stateUpgraded(root);
85
+ // What a suite of an earlier form said its own way is told when it is rewritten from that form, and once.
86
+ return { rewritten: [...rewritten, ...state.rewritten], found: [...(rewritten.length ? worldDescribed(root) : []), ...state.found, ...inputsOutOfType(suite)], unseen: [...(rewritten.length ? UNSEEN : []), ...state.unseen] };
76
87
  }
@@ -0,0 +1,62 @@
1
+ const quoted = (text) => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
2
+ /**
3
+ * An expression as Elo reads it again, for those a key is made of: names, members, calls, and the
4
+ * plain values. Nothing when it is made of anything else (a lambda, a `let`, a date): such a key
5
+ * is not one a link can say.
6
+ */
7
+ export function unparsed(node) {
8
+ const all = (nodes) => {
9
+ const texts = nodes.map(unparsed);
10
+ return texts.every((text) => text !== null) ? texts : null;
11
+ };
12
+ const join = (nodes, write) => {
13
+ const texts = all(nodes);
14
+ return texts ? write(texts) : null;
15
+ };
16
+ switch (node.type) {
17
+ case 'literal': return String(node.value);
18
+ case 'null': return 'null';
19
+ case 'string': return quoted(node.value);
20
+ case 'variable': return node.name;
21
+ case 'member_access': return join([node.object], ([object]) => `${object}.${node.property}`);
22
+ case 'function_call': return join(node.args, (args) => `${node.name}(${args.join(', ')})`);
23
+ case 'binary': return join([node.left, node.right], ([left, right]) => `(${left} ${node.operator} ${right})`);
24
+ case 'unary': return join([node.operand], ([operand]) => `(${node.operator}${operand})`);
25
+ case 'array': return join(node.elements, (elements) => `[${elements.join(', ')}]`);
26
+ default: return null;
27
+ }
28
+ }
29
+ /** A reference as it is written. */
30
+ export function refText(ref, key = ref.key) {
31
+ const attribute = ref.attribute ? `.${ref.attribute}` : '';
32
+ if (ref.of === 'every')
33
+ return `${ref.variable}(*)${attribute}`;
34
+ return ref.of === 'item' ? `${ref.variable}(${(key ?? []).join(', ')})${attribute}` : `${ref.variable}${attribute}`;
35
+ }
36
+ const named = ({ state }, name) => state.find((one) => one.name === name);
37
+ /** How a reference is written with the names of the suite: an item by the name of its item, `board(1)`, anything else by the variable's. */
38
+ export function shown(ref, variables, key = ref.key) {
39
+ const item = named(variables, ref.variable)?.item?.name;
40
+ return ref.of === 'item' && item ? refText({ ...ref, variable: item }, key) : refText(ref, key);
41
+ }
42
+ /**
43
+ * A key as a text: what two keys are the same by. One mechanism tells a number where another tells
44
+ * the text of it (a row of number 7, an item of key "7"), and both name one item, as Elo reads `7 == '7'`.
45
+ */
46
+ export const keyText = (key) => JSON.stringify(key.map(String));
47
+ const isPlain = (value) => ['string', 'number', 'boolean'].includes(typeof value);
48
+ /**
49
+ * The items a key names, from what each part of it gave: one item, or one for each of those a
50
+ * part lists, `balance(input.sharedBy)`; of a key of several parts, one for each way to take one
51
+ * of each. Nothing when a part gave nothing that names an item.
52
+ */
53
+ export function itemsNamed(parts) {
54
+ let keys = [[]];
55
+ for (const part of parts) {
56
+ const each = Array.isArray(part) ? part : [part];
57
+ if (!each.every(isPlain))
58
+ return null;
59
+ keys = keys.flatMap((key) => each.map((one) => [...key, one]));
60
+ }
61
+ return keys;
62
+ }
package/dist/world.js CHANGED
@@ -1,7 +1,7 @@
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.
1
+ // What a suite does to the world: it sets a Background and calls the front door as somebody.
2
+ // Everything that specifies anything goes through the front door; the Background is set as the
3
+ // configuration says; the database is opened behind the front door, to read and never to write.
4
+ // What is observed of the state, and how, is in observing.ts.
5
5
  import pg from 'pg';
6
6
  import { Unrunnable } from './finding.js';
7
7
  function remember(jar, cookies) {
@@ -44,7 +44,8 @@ export function browser({ api, originHeader }, origin, hears) {
44
44
  return answer;
45
45
  };
46
46
  const header = (name, value) => void held.set(name.toLowerCase(), value);
47
- return { call, header };
47
+ const cookie = (name, value) => void jar.set(name, value);
48
+ return { call, header, cookie };
48
49
  }
49
50
  /** The browser of an actor: signed in when they have something to sign in with, as a visitor's otherwise. */
50
51
  export async function browserOf(config, origin, name, actor, hears) {
@@ -96,37 +97,5 @@ export async function atRest({ config, database }, forMs = 15_000) {
96
97
  await pause(25);
97
98
  }
98
99
  }
99
- async function tuples(database, { table, key, attributes }) {
100
- const { rows } = await database.query(`SELECT ${[...key, ...attributes].join(', ')} FROM ${table} ORDER BY ${key.join(', ')}`);
101
- return JSON.parse(JSON.stringify(rows));
102
- }
103
- /**
104
- * What a route of the state tells somebody: what it answers, and nothing where it refuses them.
105
- * A route that fails (a 5xx) refused nobody and told nothing: read as nothing, "nothing changed"
106
- * would hold of a system that is broken, before and after. The state was not observed, and the
107
- * case cannot be judged.
108
- */
109
- export function toldBy({ name, path }, answer) {
110
- if (answer.status >= 500)
111
- throw new Unrunnable(`the state "${name}" could not be observed: GET ${path} answered ${answer.status}`);
112
- return answer.status === 200 ? answer.body : null;
113
- }
114
- /** What one browser is told by the routes of the state. */
115
- async function seenBy(model, theirs) {
116
- const seen = {};
117
- for (const one of model.state)
118
- seen[one.name] = toldBy(one, await theirs.call('GET', one.path));
119
- return seen;
120
- }
121
- /** 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. */
122
- export async function observe(reach, model, requester, witnesses, only) {
123
- const observed = only ? { ...model, state: model.state.filter((one) => only.includes(one.name)) } : model;
124
- const state = await seenBy(observed, requester);
125
- const others = {};
126
- for (const [name, theirs] of Object.entries(witnesses))
127
- others[name] = await seenBy(observed, theirs);
128
- const db = {};
129
- for (const relation of model.relations)
130
- db[relation.name] = reach.database && reach.relations ? await tuples(reach.database, relation) : null;
131
- return { ...state, seenBy: others, db };
132
- }
100
+ /** The database as what observes the state asks it: one statement, its rows. Nothing where the run reads nothing behind the front door. */
101
+ export const asking = ({ database, complete }) => (database && complete ? async (sql, values) => (await database.query(sql, values)).rows : null);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enspirit/opspicy",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "description": "Specifies the operations of a system by their clauses, as sentences that Elo gives a meaning, and runs them black-box",
6
6
  "repository": {