@skillstech/thunderlang 1.2.0 → 1.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/CHANGELOG.md +190 -0
- package/dist/core.cjs +6718 -1232
- package/dist/index.cjs +17490 -12204
- package/dist/learn.cjs +5866 -497
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +54 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +59 -0
- package/src/core.mjs +14 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +34 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +32 -4
- package/src/model.mjs +72 -9
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +64 -5
- package/src/replay-cli.mjs +123 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +168 -13
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +443 -20
- package/src/term.mjs +43 -0
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
package/src/term.mjs
CHANGED
|
@@ -87,3 +87,46 @@ export function paintHelp(text, on = useColor()) {
|
|
|
87
87
|
return line;
|
|
88
88
|
}).join('\n');
|
|
89
89
|
}
|
|
90
|
+
|
|
91
|
+
// ── Thunder Core in the terminal: the same roles as the editor and the site ─────────────────────────────────────
|
|
92
|
+
const CORE_LEADS = new Set(['Set', 'say', 'Say', 'print', 'Keep', 'Increase', 'Decrease', 'Add', 'Remove', 'Sort', 'Reverse', 'When', 'If', 'Otherwise', 'For', 'Repeat', 'Stop', 'Give', 'Receive', 'Test', 'Expect', 'Use', 'Never', 'To', 'A', 'An']);
|
|
93
|
+
const CORE_JOIN = new Set(['to', 'with', 'by', 'from', 'as', 'at', 'least', 'most', 'more', 'less', 'than', 'each', 'while', 'until', 'times', 'of', 'where', 'sorted', 'descending', 'be', 'fail', 'fails', 'is', 'and', 'or', 'not', 'has', 'allow', 'back', 'in', 'when', 'if', 'this']);
|
|
94
|
+
const CORE_VALUES = new Set(['yes', 'no', 'nothing', 'true', 'false']);
|
|
95
|
+
const CORE_KINDS = new Set(['text', 'money', 'number', 'whole', 'date', 'optional', 'list', 'map']);
|
|
96
|
+
const TOKENS = /("(?:[^"\\]|\\.)*"?)|((?<=\s)#.*$)|(-?\$\d[\d,]*(?:\.\d+)?|\d+(?:\.\d+)?%?)|([A-Za-z_][A-Za-z0-9_]*)|(\s+)|(.)/g;
|
|
97
|
+
const ansi = (code, s, on) => (on ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
98
|
+
|
|
99
|
+
/** Color one line of Thunder Core: statement words, joining words, values, text (with its {holes}), names, comments. */
|
|
100
|
+
export function paintThunderLine(line, on = useColor()) {
|
|
101
|
+
if (!on) return line;
|
|
102
|
+
if (/^\s*#/.test(line)) return ansi('2', line, on);
|
|
103
|
+
const fnDef = /^\s*To [a-z]/.test(line);
|
|
104
|
+
const recDef = /^\s*An? [A-Z]\w*(?: [A-Z]\w*)* has:/.test(line);
|
|
105
|
+
const fieldLine = /^\s*[a-z][a-z0-9_]*(?: [a-z][a-z0-9_]*)*:\s+\S/.test(line);
|
|
106
|
+
const kindLine = /^\s+[A-Z][\w ]* is (?:an? )?(?:optional )?(?:text|money|number|whole number|date|yes\/no|list|map)\b/.test(line);
|
|
107
|
+
let out = '', leading = true, inName = false, beforeColon = fieldLine, first = true;
|
|
108
|
+
for (const m of line.matchAll(TOKENS)) {
|
|
109
|
+
const [t, str, comment, num, word, space] = m;
|
|
110
|
+
if (space) { out += t; continue; }
|
|
111
|
+
if (str) { out += ansi('32', t.replace(/\{[^{}"]+\}/g, (h) => `\x1b[1;33m${h}\x1b[0;32m`), on); leading = false; continue; }
|
|
112
|
+
if (comment) { out += ansi('2', t, on); continue; }
|
|
113
|
+
if (num) { out += ansi('33', t, on); leading = false; continue; }
|
|
114
|
+
if (!word) { if (t === ':') { beforeColon = false; inName = false; } out += t; leading = false; continue; }
|
|
115
|
+
let code = null;
|
|
116
|
+
if (beforeColon) code = '36';
|
|
117
|
+
else if (kindLine && first) code = '36';
|
|
118
|
+
else if (kindLine && (CORE_KINDS.has(t) || CORE_VALUES.has(t))) code = '36;1';
|
|
119
|
+
else if (leading && CORE_LEADS.has(t)) { code = '1;35'; inName = fnDef && t === 'To'; }
|
|
120
|
+
else if (inName) code = '34';
|
|
121
|
+
else if (CORE_VALUES.has(t)) code = '33';
|
|
122
|
+
else if (t === 'each' && /^\s*For each/.test(line)) code = '1;35';
|
|
123
|
+
else if (CORE_JOIN.has(t)) code = '35';
|
|
124
|
+
else if (/^[A-Z]/.test(t) && (recDef || !first)) code = '36';
|
|
125
|
+
out += code ? ansi(code, t, on) : t;
|
|
126
|
+
leading = false; first = false;
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Color a whole Thunder Core program (plain when color is off). */
|
|
132
|
+
export const paintThunder = (text, on = useColor()) => (on ? String(text).split('\n').map((l) => paintThunderLine(l, on)).join('\n') : text);
|
package/src/things-langs.mjs
CHANGED
|
@@ -66,8 +66,18 @@ function cDocAbove(src, idx) {
|
|
|
66
66
|
|
|
67
67
|
/** The body of a brace block with nested blocks removed: the type's own declarations, not its methods' bodies. */
|
|
68
68
|
function ownLevel(body) {
|
|
69
|
-
let depth = 0, own = '';
|
|
70
|
-
for (
|
|
69
|
+
let depth = 0, own = '', start = 0;
|
|
70
|
+
for (let i = 0; i < body.length; i++) {
|
|
71
|
+
const c = body[i];
|
|
72
|
+
if (c === '{') { if (depth === 0) start = i; depth++; }
|
|
73
|
+
if (depth === 0) own += c;
|
|
74
|
+
if (c === '}') {
|
|
75
|
+
depth--;
|
|
76
|
+
// A value's initializer (`= new() { ["a"] = 1 }`, `= new List<int> { 1, 2 }`, `= { 1, 2 }`) is kept as a
|
|
77
|
+
// mark, so a filled-in value never reads as empty; a method's body is dropped.
|
|
78
|
+
if (depth === 0 && /(?:=|\bnew\b[\w.<>,[\] ?]*(?:\([^()]*\))?)\s*$/.test(own) && body.slice(start + 1, i).trim()) own = `${own.replace(/\s+$/, '')} {…}`;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
71
81
|
return own;
|
|
72
82
|
}
|
|
73
83
|
|
|
@@ -95,7 +105,12 @@ function goDoc(src, at, name) {
|
|
|
95
105
|
const MODIFIERS = /^(?:(?:public|private|protected|internal|static|final|readonly|const|volatile|transient|override|open|abstract|sealed|lateinit|required|unsafe|mut|pub(?:\([^)]*\))?|var|val|let)\s+)*/;
|
|
96
106
|
|
|
97
107
|
export function makeThingReaders({ words, kindWords, startValue }) {
|
|
98
|
-
|
|
108
|
+
// (C#'s `new()` names no type: it is empty only when the declared type is a list or lookup table.)
|
|
109
|
+
const know = (name, type, start, params, line = null) => {
|
|
110
|
+
const kind = type ? kindWords(type) : null;
|
|
111
|
+
const said = start != null && start !== '' ? (/^new\(\)$/.test(String(start).trim()) && !/^(a list|a lookup table|a set)/.test(kind ?? '') ? 'worked out when it starts' : startValue(start, params)) : null;
|
|
112
|
+
return { name, label: words(name.replace(/^[_$]+|_$/g, '')), kind, start: said, line };
|
|
113
|
+
};
|
|
99
114
|
|
|
100
115
|
/** Java, C#, Kotlin, PHP: brace-bodied classes. */
|
|
101
116
|
function curlyThings(src, file, language) {
|
|
@@ -164,6 +179,8 @@ export function makeThingReaders({ words, kindWords, startValue }) {
|
|
|
164
179
|
thing.knows.push(know(f[2], f[1], f[3], params));
|
|
165
180
|
}
|
|
166
181
|
}
|
|
182
|
+
// A property that shows a field (`_orders` and `Orders`) is the same thing known twice: keep it once.
|
|
183
|
+
thing.knows = thing.knows.filter((k, i, all) => all.findIndex((x) => x.label === k.label) === i);
|
|
167
184
|
// Starting values set in the constructor: this.x = …; / $this->x = …; / x = … (Kotlin init blocks).
|
|
168
185
|
const ctorRe = language === 'php' ? /function\s+__construct\s*\(([^)]*)\)\s*\{/ : language === 'kotlin' ? /\binit\s*\{/ : new RegExp(`(?:public|private|protected|internal)?\\s*${name}\\s*\\(([^)]*)\\)\\s*(?::\\s*(?:this|base)\\([^)]*\\)\\s*)?\\{`);
|
|
169
186
|
const ctor = body.match(ctorRe);
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// thunder write across folders: one rule change written into every service that implements it (write-across.mjs).
|
|
2
|
+
// thunder write <folder…> --decision <name> --rule <n> --when "<condition>" [--write] [--run "part: cmd" …]
|
|
3
|
+
// [--passport passport.json] [--purpose "…"] [--json]
|
|
4
|
+
// Without --write it shows the plan and changes nothing. With --write it changes every implementation or none, then
|
|
5
|
+
// runs the --run commands and, with --passport, records the change and the runs as a Software Passport.
|
|
6
|
+
import { readFileSync, writeFileSync, statSync } from 'node:fs';
|
|
7
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
8
|
+
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import { collectReadableFiles } from './read-repo-fs.mjs';
|
|
10
|
+
import { writeRuleAcross, writeAcrossEvidence } from './write-across.mjs';
|
|
11
|
+
import { buildPassport } from './passport-fs.mjs';
|
|
12
|
+
import { renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
|
|
13
|
+
import { paint, useColor } from './term.mjs';
|
|
14
|
+
|
|
15
|
+
const USAGE = `usage: thunder write <folder…> --decision <name> --rule <n> --when "<condition>" [--write]
|
|
16
|
+
[--run "part: cmd" …] [--passport passport.json] [--purpose "…"] [--json]
|
|
17
|
+
Finds every implementation of the rule across the folders (each one part, in any language Thunder reads) and
|
|
18
|
+
changes its number, comparison, or text value in each of them. Without --write: the plan only. With --write: every
|
|
19
|
+
implementation changes, or none does. Test files are never edited; those that mention the old value are listed.
|
|
20
|
+
Exit codes: 0 done (or planned), 1 refused or a --run command failed, 2 usage.`;
|
|
21
|
+
|
|
22
|
+
/** Is this `thunder write` call about several folders (rather than one file)? */
|
|
23
|
+
export function isWriteAcross(argv) {
|
|
24
|
+
const paths = [];
|
|
25
|
+
for (let i = 0; i < argv.length; i++) {
|
|
26
|
+
if (argv[i].startsWith('--')) { if (!['--write', '--json', '-w'].includes(argv[i])) i++; continue; }
|
|
27
|
+
paths.push(argv[i]);
|
|
28
|
+
}
|
|
29
|
+
if (argv.includes('--edit')) return false;
|
|
30
|
+
return paths.length > 1 || paths.some((p) => { try { return statSync(p).isDirectory(); } catch { return false; } });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function writeAcrossMain(argv) {
|
|
34
|
+
const a = { _: [], decision: null, rule: null, when: null, write: false, run: [], passport: null, mdOut: null, purpose: null, json: false };
|
|
35
|
+
for (let i = 0; i < argv.length; i++) {
|
|
36
|
+
const x = argv[i];
|
|
37
|
+
const need = () => { const v = argv[++i]; if (v == null) throw new Error(`${x} needs a value.`); return v; };
|
|
38
|
+
try {
|
|
39
|
+
if (x === '--decision') a.decision = need();
|
|
40
|
+
else if (x === '--rule') a.rule = need();
|
|
41
|
+
else if (x === '--when') a.when = need();
|
|
42
|
+
else if (x === '--write' || x === '-w') a.write = true;
|
|
43
|
+
else if (x === '--run') a.run.push(need());
|
|
44
|
+
else if (x === '--passport') a.passport = need();
|
|
45
|
+
else if (x === '--md-out') a.mdOut = need();
|
|
46
|
+
else if (x === '--purpose') a.purpose = need();
|
|
47
|
+
else if (x === '--json') a.json = true;
|
|
48
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
|
|
49
|
+
else if (x === '--answer') { console.error('thunder write: across folders, only a rule\'s condition can change (--when). Each service may answer in its own way (a label on the page, an amount in billing), so one new answer would not fit them all.'); return 2; }
|
|
50
|
+
else if (x.startsWith('--')) { console.error(`thunder write: there is no option ${x} for a change across folders.\n${USAGE}`); return 2; }
|
|
51
|
+
else a._.push(x);
|
|
52
|
+
} catch (e) { console.error(`thunder write: ${e.message}\n${USAGE}`); return 2; }
|
|
53
|
+
}
|
|
54
|
+
if (!a.decision || !a.rule || a.when == null) { console.error(`thunder write: say which rule and its new condition.\n${USAGE}`); return 2; }
|
|
55
|
+
if (a.run.length && !a.write) { console.error('thunder write: --run runs your tests on the changed code, so it needs --write.'); return 2; }
|
|
56
|
+
if (a.passport && !a.write) { console.error('thunder write: --passport records a written change, so it needs --write.'); return 2; }
|
|
57
|
+
|
|
58
|
+
const parts = [];
|
|
59
|
+
for (const p of a._) {
|
|
60
|
+
let dir = false;
|
|
61
|
+
try { dir = statSync(p).isDirectory(); } catch { console.error(`thunder write: there is no folder called ${p} here.`); return 2; }
|
|
62
|
+
if (!dir) { console.error(`thunder write: ${p} is a file. Across services, name the folders (each one part); for one file use thunder write <file> --decision …`); return 2; }
|
|
63
|
+
parts.push({ name: basename(resolve(p)), dir: p });
|
|
64
|
+
}
|
|
65
|
+
if (new Set(parts.map((p) => p.name)).size !== parts.length) { console.error('thunder write: two folders have the same name; give folders with different names.'); return 2; }
|
|
66
|
+
const files = parts.flatMap((p) => collectReadableFiles(p.dir).map((f) => ({ part: p.name, path: f.path, source: f.source })));
|
|
67
|
+
const r = writeRuleAcross(files, { decision: a.decision, rule: a.rule, when: a.when });
|
|
68
|
+
const dirOf = (k) => { const [part, ...rest] = k.split('/'); return join(parts.find((p) => p.name === part).dir, rest.join('/')); };
|
|
69
|
+
|
|
70
|
+
// Write every file, or none (a failed write puts back the ones already written).
|
|
71
|
+
let written = false;
|
|
72
|
+
if (r.ok && a.write) {
|
|
73
|
+
const done = [];
|
|
74
|
+
try {
|
|
75
|
+
for (const [k, src] of Object.entries(r.files)) { const path = dirOf(k); const old = readFileSync(path, 'utf8'); writeFileSync(path, src); done.push([path, old]); }
|
|
76
|
+
for (const [k, src] of Object.entries(r.files)) if (readFileSync(dirOf(k), 'utf8') !== src) throw new Error(`${k} does not hold what was written`);
|
|
77
|
+
written = true;
|
|
78
|
+
} catch (e) {
|
|
79
|
+
for (const [path, old] of done) writeFileSync(path, old);
|
|
80
|
+
console.error(`thunder write: could not write every file (${e.message}); the ones already written were put back.`);
|
|
81
|
+
return 1;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Proof: the tests, and the passport (which runs them itself, so they run once).
|
|
86
|
+
let runs = [], passport = null;
|
|
87
|
+
if (written && a.passport) {
|
|
88
|
+
passport = buildPassport({ parts: parts.map((p) => p.dir), base: 'HEAD', run: a.run, purpose: a.purpose ? { text: a.purpose, source: 'given with --purpose' } : null, evidence: [writeAcrossEvidence(r)], relativeTo: dirname(resolve(a.passport)) });
|
|
89
|
+
writeFileSync(a.passport, `${JSON.stringify(passport, null, 2)}\n`);
|
|
90
|
+
if (a.mdOut) writeFileSync(a.mdOut, renderPassportMarkdown(passport));
|
|
91
|
+
runs = passport.evidence.filter((e) => e.kind === 'test-run').map((e) => ({ command: e.basis.command, exitCode: e.basis.exitCode, part: e.claim.match(/ in ([^ ]+) exited/)?.[1] ?? null, tail: e.basis.outputTail }));
|
|
92
|
+
} else if (written) {
|
|
93
|
+
for (const spec of a.run) {
|
|
94
|
+
const m = String(spec).match(/^([A-Za-z0-9_.-]+):\s+(.+)$/);
|
|
95
|
+
const part = m && parts.find((p) => p.name === m[1]);
|
|
96
|
+
const command = part ? m[2] : spec;
|
|
97
|
+
const x = spawnSync(`(${command}) 2>&1`, { shell: true, cwd: part ? part.dir : process.cwd(), encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
98
|
+
runs.push({ command, part: part?.name ?? null, exitCode: x.status ?? 1, tail: String(x.stdout ?? '').trimEnd().split('\n').slice(-12).join('\n') });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const failed = runs.filter((x) => x.exitCode !== 0);
|
|
102
|
+
|
|
103
|
+
if (a.json) {
|
|
104
|
+
const { files: _f, ...rest } = r;
|
|
105
|
+
console.log(JSON.stringify({ ...rest, written, runs, ...(a.passport ? { passport: a.passport } : {}) }, null, 2));
|
|
106
|
+
return !r.ok || failed.length ? 1 : 0;
|
|
107
|
+
}
|
|
108
|
+
const say = (s = '') => console.log(paint(s, useColor()));
|
|
109
|
+
if (!r.ok) {
|
|
110
|
+
console.error(paint('✗ Not changed. No file was touched.', useColor(process.stderr)));
|
|
111
|
+
for (const p of r.problems) console.error(` ${p}`);
|
|
112
|
+
if (r.notIncluded?.length) { console.error('\nAlso similar, never changed by Thunder:'); for (const n of r.notIncluded) console.error(` ${n.part}/${n.file}:${n.line} ${n.why}`); }
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
say(`One rule, ${r.plan.length} implementation${r.plan.length === 1 ? '' : 's'}: ${r.rule.before} → ${r.rule.after}`);
|
|
116
|
+
say('');
|
|
117
|
+
for (const p of r.plan) {
|
|
118
|
+
say(`${p.part}/${p.file} (${p.language}, ${p.decision}, rule ${p.rule})`);
|
|
119
|
+
say(` why it is the same rule: ${p.why}`);
|
|
120
|
+
say(` was: ${p.before}`);
|
|
121
|
+
say(` now: ${p.after}`);
|
|
122
|
+
for (const c of p.change) say(` line ${c.line}, column ${c.column}: ${c.before} -> ${c.after}`);
|
|
123
|
+
}
|
|
124
|
+
say('\nChecked by reading each file again: the rule reads as intended, and every other rule and function in each file reads exactly as before.');
|
|
125
|
+
if (r.notIncluded.length) {
|
|
126
|
+
say('\nNot included (similar, but Thunder cannot tell it is the same rule; check by hand):');
|
|
127
|
+
for (const n of r.notIncluded) say(` ${n.part}/${n.file}:${n.line} ${n.why}`);
|
|
128
|
+
}
|
|
129
|
+
if (r.tests.length) {
|
|
130
|
+
say('\nTests that mention the old value (Thunder never edits tests; they may pin the old rule):');
|
|
131
|
+
for (const t of r.tests) say(` ${t.part}/${t.file}:${t.line} ${t.text}`);
|
|
132
|
+
}
|
|
133
|
+
if (!written) { say('\nPlan only; nothing was saved. Add --write to change every implementation (all or none).'); return 0; }
|
|
134
|
+
say(`\nSaved ${Object.keys(r.files).length} file${Object.keys(r.files).length === 1 ? '' : 's'}: ${Object.keys(r.files).join(', ')}.`);
|
|
135
|
+
if (runs.length) {
|
|
136
|
+
say('\nTests on the changed code:');
|
|
137
|
+
for (const x of runs) say(` ${x.exitCode === 0 ? '✓ passed' : `✗ failed (exit ${x.exitCode})`} ${x.part ? `${x.part}: ` : ''}${x.command}`);
|
|
138
|
+
for (const x of failed) { say(`\n ${x.part ? `${x.part}: ` : ''}${x.command} said:`); for (const l of String(x.tail).split('\n')) say(` ${l}`); }
|
|
139
|
+
if (failed.length) say('\nThe change is saved, and these tests fail on it. A test that pins the old rule fails until it is updated; any other failure needs a look.');
|
|
140
|
+
}
|
|
141
|
+
if (passport) { say(`\nPassport: ${a.passport}`); say(renderPassportSummary(passport)); }
|
|
142
|
+
return failed.length ? 1 : 0;
|
|
143
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Thunder write across languages: one change to a business rule, written into every service that implements it.
|
|
2
|
+
//
|
|
3
|
+
// The same rule is often written more than once: the web page says "free shipping from $50", the orders service
|
|
4
|
+
// charges by it, and billing checks it again. Change one and forget another, and the services disagree. This finds
|
|
5
|
+
// every implementation of a rule across the parts of an application (in any language Thunder reads), changes its
|
|
6
|
+
// number, comparison, or text value once, and writes that change into each implementation with Thunder write
|
|
7
|
+
// (write.mjs): only those characters change, and each file is read again to check that the rule now reads as
|
|
8
|
+
// intended and nothing else in the file reads differently. All or nothing: if any implementation cannot be written
|
|
9
|
+
// exactly, no file changes.
|
|
10
|
+
//
|
|
11
|
+
// Which rules count as the same: decisions whose rule has the same condition, comparing names as words
|
|
12
|
+
// (orderTotal, OrderTotal, and order_total are the same name), numbers by value, and comparisons and text exactly.
|
|
13
|
+
// A rule with the same shape where only the names or only the values differ is listed as "not included, check by
|
|
14
|
+
// hand", never changed. Test files are never edited; those that mention the rule's old values are listed.
|
|
15
|
+
//
|
|
16
|
+
// Deterministic and browser-safe: it takes file contents and returns new contents. It never runs anything.
|
|
17
|
+
import { readCode, sayCondition } from './read.mjs';
|
|
18
|
+
import { tokenize } from './expr.mjs';
|
|
19
|
+
import { writeRule } from './write.mjs';
|
|
20
|
+
import { isTestFile } from './trace.mjs';
|
|
21
|
+
|
|
22
|
+
export const WRITE_ACROSS_SCHEMA = 'thunder-write-across-v1';
|
|
23
|
+
|
|
24
|
+
const words = (name) => String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/[_\-.\s]+/g, ' ').trim().toLowerCase();
|
|
25
|
+
const editable = (t) => t.t === 'num' || t.t === 'str' || (t.t === 'op' && ['<', '<=', '>', '>=', '==', '!='].includes(t.v));
|
|
26
|
+
const keyOf = (t) => (t.t === 'id' ? `id:${words(t.v)}` : t.t === 'str' ? `str:${JSON.stringify(t.v)}` : `${t.t}:${t.v}`);
|
|
27
|
+
const shapeOf = (t) => (t.t === 'id' ? 'id' : editable(t) ? (t.t === 'op' ? 'cmp' : t.t) : `${t.t}:${t.v}`);
|
|
28
|
+
const join = (toks) => toks.map((t) => (t.t === 'str' ? JSON.stringify(t.v) : String(t.v))).join(' ');
|
|
29
|
+
const toks = (when) => { try { return tokenize(when); } catch { return null; } };
|
|
30
|
+
|
|
31
|
+
/** Every decision rule in the parts' source files (test files left out), read once. */
|
|
32
|
+
function rulesIn(files) {
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const f of files) {
|
|
35
|
+
if (isTestFile(f.path)) continue;
|
|
36
|
+
let reading;
|
|
37
|
+
try { reading = readCode(f.source, { file: f.path }); } catch { continue; }
|
|
38
|
+
for (const d of reading.items.filter((i) => i.kind === 'decision')) {
|
|
39
|
+
d.rules.forEach((r, i) => {
|
|
40
|
+
const t = toks(r.when);
|
|
41
|
+
if (t) out.push({ part: f.part, file: f.path, language: reading.language, decision: d.name, decisionLine: d.line, rule: i + 1, line: r.line, when: r.when, result: r.result, toks: t });
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const where = (x) => `${x.part ? `${x.part}/` : ''}${x.file ?? x.path}`;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Find a rule and every other implementation of it.
|
|
52
|
+
* files: [{ part, path, source }]
|
|
53
|
+
* decision: the decision's name (as `thunder read` shows it), or "part/file:name" when the name is used twice
|
|
54
|
+
* rule: its 1-based rule number
|
|
55
|
+
* Returns { ok, anchor, same: [...], notIncluded: [...], problems }.
|
|
56
|
+
*/
|
|
57
|
+
export function findSameRule(files, { decision, rule }) {
|
|
58
|
+
const all = rulesIn(files);
|
|
59
|
+
const m = String(decision ?? '').match(/^(.+):([^:]+)$/);
|
|
60
|
+
const name = m ? m[2] : decision;
|
|
61
|
+
let anchors = all.filter((x) => x.decision === name && x.rule === Number(rule));
|
|
62
|
+
if (m) anchors = anchors.filter((x) => where(x) === m[1] || x.file === m[1]);
|
|
63
|
+
if (!anchors.length) {
|
|
64
|
+
const has = all.some((x) => x.decision === name);
|
|
65
|
+
return { ok: false, problems: [has ? `${name} has no rule ${rule}. Find the rule number with: thunder read <folder>` : `No decision named ${name} was found in these parts. Thunder write changes decisions: functions that choose between fixed answers.`] };
|
|
66
|
+
}
|
|
67
|
+
if (anchors.length > 1) return { ok: false, problems: [`${anchors.length} decisions are called ${name}: ${anchors.map(where).join(', ')}. Name one as "part/file:${name}".`] };
|
|
68
|
+
const anchor = anchors[0];
|
|
69
|
+
const key = anchor.toks.map(keyOf).join(' ');
|
|
70
|
+
const shape = anchor.toks.map(shapeOf).join(' ');
|
|
71
|
+
const names = anchor.toks.filter((t) => t.t === 'id').map(keyOf).join(' ');
|
|
72
|
+
const values = anchor.toks.filter((t) => t.t !== 'id').map(keyOf).join(' ');
|
|
73
|
+
const same = [], notIncluded = [];
|
|
74
|
+
for (const x of all) {
|
|
75
|
+
if (x === anchor) continue;
|
|
76
|
+
const k = x.toks.map(keyOf).join(' ');
|
|
77
|
+
const said = sayCondition(x.when);
|
|
78
|
+
if (k === key) { same.push({ ...x, why: `the same condition: ${said} (names compared as words)` }); continue; }
|
|
79
|
+
if (x.toks.map(shapeOf).join(' ') !== shape) continue;
|
|
80
|
+
const xNames = x.toks.filter((t) => t.t === 'id').map(keyOf).join(' ');
|
|
81
|
+
const xValues = x.toks.filter((t) => t.t !== 'id').map(keyOf).join(' ');
|
|
82
|
+
if (xNames === names) notIncluded.push({ ...x, why: `the same names but a different limit (${said}); it may be another rule, or one that has already drifted` });
|
|
83
|
+
else if (xValues === values) notIncluded.push({ ...x, why: `the same limit but different names (${said}); Thunder cannot tell that these are the same values` });
|
|
84
|
+
}
|
|
85
|
+
const strip = ({ toks: _t, ...rest }) => rest;
|
|
86
|
+
return { ok: true, anchor: strip(anchor), same: [anchor, ...same].map(strip), notIncluded: notIncluded.map(strip), problems: [] };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Lines in test files that mention one of the rule's old values, in test files that call one of the rule's
|
|
91
|
+
* functions (by name, in any language's spelling). A test may pin the old rule; Thunder never edits tests.
|
|
92
|
+
*/
|
|
93
|
+
function testsMentioning(files, oldToks, newToks, functions) {
|
|
94
|
+
const changed = oldToks.filter((t, i) => editable(t) && t.t !== 'op' && keyOf(t) !== keyOf(newToks[i]));
|
|
95
|
+
if (!changed.length) return [];
|
|
96
|
+
const callsRule = (src) => (src.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? []).some((w) => functions.has(words(w)));
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const f of files.filter((x) => isTestFile(x.path) && callsRule(x.source))) {
|
|
99
|
+
f.source.split('\n').forEach((line, i) => {
|
|
100
|
+
const hit = changed.some((t) => (t.t === 'num' ? new RegExp(`(^|[^0-9.])${String(t.v).replace('.', '\\.')}(?![0-9])`).test(line) : line.includes(t.v)));
|
|
101
|
+
if (hit) out.push({ part: f.part, file: f.path, line: i + 1, text: line.trim().slice(0, 160) });
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Change one rule everywhere it is implemented.
|
|
109
|
+
* when: the rule's new condition in Thunder form, written with the names of the rule you chose
|
|
110
|
+
* ("subtotal >= 75"). Only numbers, comparisons, and text values may change.
|
|
111
|
+
* Returns { schema, ok, rule: { before, after }, plan, notIncluded, tests, files, problems }. `files` maps
|
|
112
|
+
* "part/path" to the new contents of each changed file; it is empty unless ok is true.
|
|
113
|
+
*/
|
|
114
|
+
export function writeRuleAcross(files, { decision, rule, when }) {
|
|
115
|
+
const base = { schema: WRITE_ACROSS_SCHEMA, ok: false, plan: [], notIncluded: [], tests: [], files: {}, problems: [] };
|
|
116
|
+
if (when == null) return { ...base, problems: ['Say the new condition with --when, for example "subtotal >= 75".'] };
|
|
117
|
+
const found = findSameRule(files, { decision, rule });
|
|
118
|
+
if (!found.ok) return { ...base, problems: found.problems };
|
|
119
|
+
const oldT = toks(found.anchor.when), newT = toks(when);
|
|
120
|
+
if (!newT) return { ...base, problems: [`The new condition "${when}" could not be read.`] };
|
|
121
|
+
if (oldT.length !== newT.length || oldT.some((t, i) => (editable(t) ? !(editable(newT[i]) && shapeOf(t) === shapeOf(newT[i])) : keyOf(t) !== keyOf(newT[i])))) {
|
|
122
|
+
return { ...base, problems: [`Thunder write can change a number, a comparison, or a text value in a rule. "${when}" also changes the rule's shape (names, and/or, or parentheses), so it is not one change Thunder can write into every implementation.`] };
|
|
123
|
+
}
|
|
124
|
+
const result = { ...base, plan: [], files: {}, rule: { before: sayCondition(found.anchor.when), after: sayCondition(join(newT)) }, notIncluded: found.notIncluded, tests: testsMentioning(files, oldT, newT, new Set(found.same.map((x) => words(x.decision)))) };
|
|
125
|
+
|
|
126
|
+
// Each implementation, with its own spelling of the names and the new values in the same places.
|
|
127
|
+
const byFile = new Map();
|
|
128
|
+
for (const x of found.same) { const k = where(x); if (!byFile.has(k)) byFile.set(k, []); byFile.get(k).push(x); }
|
|
129
|
+
const problems = [];
|
|
130
|
+
for (const [k, list] of byFile) {
|
|
131
|
+
const f = files.find((y) => where(y) === k);
|
|
132
|
+
let source = f.source;
|
|
133
|
+
for (const x of list.sort((a, b) => b.line - a.line)) {
|
|
134
|
+
const own = toks(x.when);
|
|
135
|
+
const next = join(own.map((t, i) => (editable(t) ? newT[i] : t)));
|
|
136
|
+
const r = writeRule({ source, language: x.language, file: x.file, decision: x.decision, line: x.decisionLine, rule: x.rule, when: next });
|
|
137
|
+
if (!r.ok) { problems.push(`${k}, ${x.decision} rule ${x.rule} (line ${x.line}): ${r.problems.join(' ')}`); continue; }
|
|
138
|
+
source = r.source;
|
|
139
|
+
result.plan.push({ part: x.part, file: x.file, language: x.language, decision: x.decision, rule: x.rule, line: x.line, why: x.why ?? 'the rule you chose', before: r.before, after: r.after, change: r.change });
|
|
140
|
+
}
|
|
141
|
+
result.files[k] = source;
|
|
142
|
+
}
|
|
143
|
+
result.plan.sort((a, b) => where(a).localeCompare(where(b)) || a.line - b.line);
|
|
144
|
+
if (problems.length) return { ...base, files: {}, plan: [], rule: result.rule, notIncluded: result.notIncluded, tests: result.tests, problems: ['Nothing was changed: every implementation must be written exactly, or none is.', ...problems] };
|
|
145
|
+
return { ...result, ok: true };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Passport evidence for a written change: one item per implementation, read again after the change. */
|
|
149
|
+
export function writeAcrossEvidence(result) {
|
|
150
|
+
if (!result?.ok) return [];
|
|
151
|
+
const items = result.plan.map((p) => ({
|
|
152
|
+
kind: 'rule-write', status: 'read',
|
|
153
|
+
claim: `${where(p)}: ${p.decision}, rule ${p.rule} now reads "${p.after}" (was "${p.before}").`,
|
|
154
|
+
basis: { schema: result.schema, line: p.line, change: p.change, check: 'read again after the change: this rule reads as intended, and every other rule and function in the file reads exactly as before' },
|
|
155
|
+
scope: 'How the code reads, not whether it runs. Code that computes the same thing in a different shape is not found or changed.',
|
|
156
|
+
inputs: [{ part: p.part, file: p.file }],
|
|
157
|
+
}));
|
|
158
|
+
if (result.notIncluded.length) {
|
|
159
|
+
items.push({
|
|
160
|
+
kind: 'rule-write', status: 'read',
|
|
161
|
+
claim: `${result.notIncluded.length} similar rule${result.notIncluded.length === 1 ? ' was' : 's were'} not changed and need${result.notIncluded.length === 1 ? 's' : ''} a person to check: ${result.notIncluded.map((n) => `${where(n)}:${n.line}`).join(', ')}.`,
|
|
162
|
+
basis: { schema: result.schema, notIncluded: result.notIncluded.map((n) => ({ at: `${where(n)}:${n.line}`, says: sayCondition(n.when), why: n.why })) },
|
|
163
|
+
scope: 'Listed, not changed: Thunder could not tell they are the same rule.',
|
|
164
|
+
inputs: result.notIncluded.map((n) => ({ part: n.part, file: n.file })),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return items;
|
|
168
|
+
}
|