@skillstech/thunderlang 1.3.0 → 1.4.1

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.
@@ -0,0 +1,178 @@
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
+ // The same condition in a decision whose name shares no word with the chosen one (couponAllowed next to
14
+ // shippingFee, both "subtotal >= 50") is a different rule that happens to use the same limit, so it is listed, not
15
+ // changed. A rule with the same shape where only the names or only the values differ is listed as "not included,
16
+ // check by hand", never changed. Test files are never edited; those that mention the rule's old values are listed.
17
+ //
18
+ // Deterministic and browser-safe: it takes file contents and returns new contents. It never runs anything.
19
+ import { readCode, sayCondition } from './read.mjs';
20
+ import { tokenize } from './expr.mjs';
21
+ import { writeRule } from './write.mjs';
22
+ import { isTestFile } from './trace.mjs';
23
+
24
+ export const WRITE_ACROSS_SCHEMA = 'thunder-write-across-v1';
25
+
26
+ 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();
27
+ const editable = (t) => t.t === 'num' || t.t === 'str' || (t.t === 'op' && ['<', '<=', '>', '>=', '==', '!='].includes(t.v));
28
+ const keyOf = (t) => (t.t === 'id' ? `id:${words(t.v)}` : t.t === 'str' ? `str:${JSON.stringify(t.v)}` : `${t.t}:${t.v}`);
29
+ const shapeOf = (t) => (t.t === 'id' ? 'id' : editable(t) ? (t.t === 'op' ? 'cmp' : t.t) : `${t.t}:${t.v}`);
30
+ const join = (toks) => toks.map((t) => (t.t === 'str' ? JSON.stringify(t.v) : String(t.v))).join(' ');
31
+ // Words that say nothing about which rule a function is (get_shipping_fee and ShippingFee share "shipping").
32
+ const FILLER = new Set(['get', 'is', 'has', 'can', 'should', 'calc', 'calculate', 'compute', 'check', 'find', 'the', 'a', 'an', 'of', 'for', 'to', 'by']);
33
+ const nameWords = (name) => new Set(words(name).split(' ').filter((w) => w && !FILLER.has(w)));
34
+ const sharesWord = (a, b) => { const A = nameWords(a); return [...nameWords(b)].some((w) => A.has(w)); };
35
+ const toks = (when) => { try { return tokenize(when); } catch { return null; } };
36
+
37
+ /** Every decision rule in the parts' source files (test files left out), read once. */
38
+ function rulesIn(files) {
39
+ const out = [];
40
+ for (const f of files) {
41
+ if (isTestFile(f.path)) continue;
42
+ let reading;
43
+ try { reading = readCode(f.source, { file: f.path }); } catch { continue; }
44
+ for (const d of reading.items.filter((i) => i.kind === 'decision')) {
45
+ d.rules.forEach((r, i) => {
46
+ const t = toks(r.when);
47
+ 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 });
48
+ });
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ const where = (x) => `${x.part ? `${x.part}/` : ''}${x.file ?? x.path}`;
55
+
56
+ /**
57
+ * Find a rule and every other implementation of it.
58
+ * files: [{ part, path, source }]
59
+ * decision: the decision's name (as `thunder read` shows it), or "part/file:name" when the name is used twice
60
+ * rule: its 1-based rule number
61
+ * Returns { ok, anchor, same: [...], notIncluded: [...], problems }.
62
+ */
63
+ export function findSameRule(files, { decision, rule }) {
64
+ const all = rulesIn(files);
65
+ const m = String(decision ?? '').match(/^(.+):([^:]+)$/);
66
+ const name = m ? m[2] : decision;
67
+ let anchors = all.filter((x) => x.decision === name && x.rule === Number(rule));
68
+ if (m) anchors = anchors.filter((x) => where(x) === m[1] || x.file === m[1]);
69
+ if (!anchors.length) {
70
+ const has = all.some((x) => x.decision === name);
71
+ 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.`] };
72
+ }
73
+ if (anchors.length > 1) return { ok: false, problems: [`${anchors.length} decisions are called ${name}: ${anchors.map(where).join(', ')}. Name one as "part/file:${name}".`] };
74
+ const anchor = anchors[0];
75
+ const key = anchor.toks.map(keyOf).join(' ');
76
+ const shape = anchor.toks.map(shapeOf).join(' ');
77
+ const names = anchor.toks.filter((t) => t.t === 'id').map(keyOf).join(' ');
78
+ const values = anchor.toks.filter((t) => t.t !== 'id').map(keyOf).join(' ');
79
+ const same = [], notIncluded = [];
80
+ for (const x of all) {
81
+ if (x === anchor) continue;
82
+ const k = x.toks.map(keyOf).join(' ');
83
+ const said = sayCondition(x.when);
84
+ if (k === key) {
85
+ if (sharesWord(x.decision, anchor.decision)) same.push({ ...x, why: `the same condition: ${said} (names compared as words)` });
86
+ else notIncluded.push({ ...x, why: `the same condition (${said}) in ${x.decision}, whose name shares no word with ${anchor.decision}; it may be a different rule that happens to use the same limit` });
87
+ continue;
88
+ }
89
+ if (x.toks.map(shapeOf).join(' ') !== shape) continue;
90
+ const xNames = x.toks.filter((t) => t.t === 'id').map(keyOf).join(' ');
91
+ const xValues = x.toks.filter((t) => t.t !== 'id').map(keyOf).join(' ');
92
+ 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` });
93
+ else if (xValues === values) notIncluded.push({ ...x, why: `the same limit but different names (${said}); Thunder cannot tell that these are the same values` });
94
+ }
95
+ const strip = ({ toks: _t, ...rest }) => rest;
96
+ return { ok: true, anchor: strip(anchor), same: [anchor, ...same].map(strip), notIncluded: notIncluded.map(strip), problems: [] };
97
+ }
98
+
99
+ /**
100
+ * Lines in test files that mention one of the rule's old values, in test files that call one of the rule's
101
+ * functions (by name, in any language's spelling). A test may pin the old rule; Thunder never edits tests.
102
+ */
103
+ function testsMentioning(files, oldToks, newToks, functions) {
104
+ const changed = oldToks.filter((t, i) => editable(t) && t.t !== 'op' && keyOf(t) !== keyOf(newToks[i]));
105
+ if (!changed.length) return [];
106
+ const callsRule = (src) => (src.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? []).some((w) => functions.has(words(w)));
107
+ const out = [];
108
+ for (const f of files.filter((x) => isTestFile(x.path) && callsRule(x.source))) {
109
+ f.source.split('\n').forEach((line, i) => {
110
+ const hit = changed.some((t) => (t.t === 'num' ? new RegExp(`(^|[^0-9.])${String(t.v).replace('.', '\\.')}(?![0-9])`).test(line) : line.includes(t.v)));
111
+ if (hit) out.push({ part: f.part, file: f.path, line: i + 1, text: line.trim().slice(0, 160) });
112
+ });
113
+ }
114
+ return out;
115
+ }
116
+
117
+ /**
118
+ * Change one rule everywhere it is implemented.
119
+ * when: the rule's new condition in Thunder form, written with the names of the rule you chose
120
+ * ("subtotal >= 75"). Only numbers, comparisons, and text values may change.
121
+ * Returns { schema, ok, rule: { before, after }, plan, notIncluded, tests, files, problems }. `files` maps
122
+ * "part/path" to the new contents of each changed file; it is empty unless ok is true.
123
+ */
124
+ export function writeRuleAcross(files, { decision, rule, when }) {
125
+ const base = { schema: WRITE_ACROSS_SCHEMA, ok: false, plan: [], notIncluded: [], tests: [], files: {}, problems: [] };
126
+ if (when == null) return { ...base, problems: ['Say the new condition with --when, for example "subtotal >= 75".'] };
127
+ const found = findSameRule(files, { decision, rule });
128
+ if (!found.ok) return { ...base, problems: found.problems };
129
+ const oldT = toks(found.anchor.when), newT = toks(when);
130
+ if (!newT) return { ...base, problems: [`The new condition "${when}" could not be read.`] };
131
+ if (oldT.length !== newT.length || oldT.some((t, i) => (editable(t) ? !(editable(newT[i]) && shapeOf(t) === shapeOf(newT[i])) : keyOf(t) !== keyOf(newT[i])))) {
132
+ 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.`] };
133
+ }
134
+ 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)))) };
135
+
136
+ // Each implementation, with its own spelling of the names and the new values in the same places.
137
+ const byFile = new Map();
138
+ for (const x of found.same) { const k = where(x); if (!byFile.has(k)) byFile.set(k, []); byFile.get(k).push(x); }
139
+ const problems = [];
140
+ for (const [k, list] of byFile) {
141
+ const f = files.find((y) => where(y) === k);
142
+ let source = f.source;
143
+ for (const x of list.sort((a, b) => b.line - a.line)) {
144
+ const own = toks(x.when);
145
+ const next = join(own.map((t, i) => (editable(t) ? newT[i] : t)));
146
+ const r = writeRule({ source, language: x.language, file: x.file, decision: x.decision, line: x.decisionLine, rule: x.rule, when: next });
147
+ if (!r.ok) { problems.push(`${k}, ${x.decision} rule ${x.rule} (line ${x.line}): ${r.problems.join(' ')}`); continue; }
148
+ source = r.source;
149
+ 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 });
150
+ }
151
+ result.files[k] = source;
152
+ }
153
+ result.plan.sort((a, b) => where(a).localeCompare(where(b)) || a.line - b.line);
154
+ 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] };
155
+ return { ...result, ok: true };
156
+ }
157
+
158
+ /** Passport evidence for a written change: one item per implementation, read again after the change. */
159
+ export function writeAcrossEvidence(result) {
160
+ if (!result?.ok) return [];
161
+ const items = result.plan.map((p) => ({
162
+ kind: 'rule-write', status: 'read',
163
+ claim: `${where(p)}: ${p.decision}, rule ${p.rule} now reads "${p.after}" (was "${p.before}").`,
164
+ 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' },
165
+ scope: 'How the code reads, not whether it runs. Code that computes the same thing in a different shape is not found or changed.',
166
+ inputs: [{ part: p.part, file: p.file }],
167
+ }));
168
+ if (result.notIncluded.length) {
169
+ items.push({
170
+ kind: 'rule-write', status: 'read',
171
+ 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(', ')}.`,
172
+ basis: { schema: result.schema, notIncluded: result.notIncluded.map((n) => ({ at: `${where(n)}:${n.line}`, says: sayCondition(n.when), why: n.why })) },
173
+ scope: 'Listed, not changed: Thunder could not tell they are the same rule.',
174
+ inputs: result.notIncluded.map((n) => ({ part: n.part, file: n.file })),
175
+ });
176
+ }
177
+ return items;
178
+ }