@skillstech/thunderlang 0.5.11 → 1.0.3

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 (66) hide show
  1. package/CHANGELOG.md +441 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
package/src/shell.mjs ADDED
@@ -0,0 +1,1212 @@
1
+ // Bash and POSIX shell in Thunder. A small, linear lexer and recursive-descent parser for the shell grammar (words,
2
+ // quotes, $(…), ${…}, heredocs, pipes, && and ||, if/elif/else, for, while/until, case, functions, groups), then each
3
+ // command in plain words: tests as sentences ("the file config exists"), exits as Stops with the message echoed
4
+ // right before them, `set -e` as a note, `trap … EXIT` as what runs at the end, and well-known tools (docker,
5
+ // kubectl, helm, az, aws, gcloud, git, npm, curl, files and folders) by what they do. Shell has no classes, so it has
6
+ // no Things. Deterministic, browser-safe; a command it does not know reads as "Runs <command>" and keeps its code.
7
+ import { sayCommand, gerund, words, cap, listWords, scriptPath, positional, opt } from './commands.mjs';
8
+
9
+ /** True when the first line is a shell shebang (#!/bin/bash, #!/usr/bin/env sh, zsh, ksh, dash). */
10
+ export const shellShebang = (src) => /^#!\s*\S*\/(?:env\s+(?:-\S+\s+)*)?(?:ba|z|k|da|a)?sh\b/.test(String(src));
11
+
12
+ function lineFinder(src) {
13
+ const starts = [0];
14
+ for (let i = src.indexOf('\n'); i >= 0; i = src.indexOf('\n', i + 1)) starts.push(i + 1);
15
+ return (idx) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= idx) lo = mid; else hi = mid - 1; } return lo + 1; };
16
+ }
17
+
18
+ // ── Lexer ─────────────────────────────────────────────────────────────────────────────────────────────
19
+
20
+ const META = new Set([' ', '\t', '\n', ';', '&', '|', '<', '>', '(', ')', '\r']);
21
+ const OPS = [';;&', ';;', ';&', '&&', '||', '|&', '&>>', '&>', '<<<', '<<-', '<<', '<>', '<&', '>>', '>&', '>|', ';', '&', '|', '<', '>', '(', ')'];
22
+ const REDIR = new Set(['&>>', '&>', '<<<', '<<-', '<<', '<>', '<&', '>>', '>&', '>|', '<', '>']);
23
+ const CMD_START = new Set(['if', 'then', 'elif', 'else', 'while', 'until', 'do', '!', 'time', '{', 'for']);
24
+
25
+ function skipSingle(s, i) { const j = s.indexOf("'", i + 1); return j < 0 ? s.length : j + 1; }
26
+ function skipBacktick(s, i) { for (let j = i + 1; j < s.length; j++) { if (s[j] === '\\') { j++; continue; } if (s[j] === '`') return j + 1; } return s.length; }
27
+ function skipAnsi(s, i) { for (let j = i + 2; j < s.length; j++) { if (s[j] === '\\') { j++; continue; } if (s[j] === "'") return j + 1; } return s.length; }
28
+ function skipDouble(s, i) {
29
+ for (let j = i + 1; j < s.length; j++) {
30
+ const c = s[j];
31
+ if (c === '\\') { j++; continue; }
32
+ if (c === '"') return j + 1;
33
+ if (c === '`') { j = skipBacktick(s, j) - 1; continue; }
34
+ if (c === '$' && s[j + 1] === '(') { j = skipBalanced(s, j + 1) - 1; continue; }
35
+ if (c === '$' && s[j + 1] === '{') { j = skipBrace(s, j + 1) - 1; continue; }
36
+ }
37
+ return s.length;
38
+ }
39
+ function skipBrace(s, i) {
40
+ let depth = 0;
41
+ for (let j = i; j < s.length; j++) {
42
+ const c = s[j];
43
+ if (c === '\\') { j++; continue; }
44
+ if (c === "'" && depth > 0 && false) continue;
45
+ if (c === '"') { j = skipDouble(s, j) - 1; continue; }
46
+ if (c === '$' && s[j + 1] === '(') { j = skipBalanced(s, j + 1) - 1; continue; }
47
+ if (c === '{') depth++;
48
+ else if (c === '}' && --depth === 0) return j + 1;
49
+ }
50
+ return s.length;
51
+ }
52
+ /** From the `(` at i to just past its matching `)`, skipping quotes, comments, nested substitutions, and heredocs. */
53
+ function skipBalanced(s, i) {
54
+ let depth = 0, pending = [];
55
+ for (let j = i; j < s.length; j++) {
56
+ const c = s[j];
57
+ if (c === '\\') { j++; continue; }
58
+ if (c === "'") { j = skipSingle(s, j) - 1; continue; }
59
+ if (c === '"') { j = skipDouble(s, j) - 1; continue; }
60
+ if (c === '`') { j = skipBacktick(s, j) - 1; continue; }
61
+ if (c === '#' && /[\s(;]/.test(s[j - 1] || ' ') && depth > 0) { const n = s.indexOf('\n', j); if (n < 0) return s.length; j = n - 1; continue; }
62
+ if (c === '<' && s[j + 1] === '<' && s[j + 2] !== '<') {
63
+ const m = s.slice(j + 2, j + 200).match(/^(-?)\s*(['"]?)([A-Za-z_][\w-]*)\2/);
64
+ if (m) { pending.push({ delim: m[3], strip: !!m[1] }); j += 1 + m[0].length; continue; }
65
+ }
66
+ if (c === '\n' && pending.length) { j = skipHeredocs(s, j + 1, pending) - 1; pending = []; continue; }
67
+ if (c === '(') depth++;
68
+ else if (c === ')' && --depth === 0) return j + 1;
69
+ }
70
+ return s.length;
71
+ }
72
+ /** Skip heredoc bodies starting at `at` (the line after the redirect); gives the offset after the last delimiter line. */
73
+ function skipHeredocs(s, at, list) {
74
+ let i = at;
75
+ for (const h of list) {
76
+ for (;;) {
77
+ if (i >= s.length) return s.length;
78
+ const eol = s.indexOf('\n', i);
79
+ const end = eol < 0 ? s.length : eol;
80
+ let l = s.slice(i, end).replace(/\r$/, '');
81
+ if (h.strip) l = l.replace(/^\t+/, '');
82
+ i = eol < 0 ? s.length : eol + 1;
83
+ if (l === h.delim || l.trimEnd() === h.delim) break;
84
+ }
85
+ }
86
+ return i;
87
+ }
88
+
89
+ function lex(src) {
90
+ const toks = [];
91
+ let i = 0, test = false;
92
+ const pending = [];
93
+ const prev = () => toks[toks.length - 1];
94
+ const atStart = () => { const t = prev(); return !t || t.t === 'nl' || (t.t === 'op' && !REDIR.has(t.v)) || (t.t === 'word' && CMD_START.has(t.v)); };
95
+ while (i < src.length) {
96
+ const c = src[i];
97
+ if (c === ' ' || c === '\t' || c === '\r') { i++; continue; }
98
+ if (c === '\\' && src[i + 1] === '\n') { i += 2; continue; }
99
+ if (c === '\n') {
100
+ toks.push({ t: 'nl', at: i, end: i + 1 });
101
+ i++;
102
+ if (pending.length) {
103
+ for (const h of pending) { const from = i; i = skipHeredocs(src, i, [h]); h.tok.end = Math.max(h.tok.end, i - 1); h.tok.body = src.slice(from, i); }
104
+ pending.length = 0;
105
+ }
106
+ continue;
107
+ }
108
+ if (c === '#') { const n = src.indexOf('\n', i); i = n < 0 ? src.length : n; continue; }
109
+ if (test) {
110
+ if (src.startsWith(']]', i) && (i + 2 >= src.length || META.has(src[i + 2]))) { toks.push({ t: 'word', v: ']]', at: i, end: i + 2 }); i += 2; test = false; continue; }
111
+ if (src.startsWith('&&', i) || src.startsWith('||', i)) { toks.push({ t: 'word', v: src.slice(i, i + 2), at: i, end: i + 2 }); i += 2; continue; }
112
+ } else {
113
+ if (src.startsWith('((', i) && atStart() || (src.startsWith('((', i) && prev()?.v === 'for')) {
114
+ const e = skipBalanced(src, i);
115
+ toks.push({ t: 'word', v: src.slice(i, e), arith: src.slice(i + 2, Math.max(i + 2, e - 2)), at: i, end: e });
116
+ i = e;
117
+ continue;
118
+ }
119
+ if ((c === '<' || c === '>') && src[i + 1] === '(') { const e = skipBalanced(src, i + 1); toks.push({ t: 'word', v: src.slice(i, e), at: i, end: e }); i = e; continue; }
120
+ const fd = src.slice(i, i + 3).match(/^\d+(?=[<>])/);
121
+ const op = OPS.find((o) => src.startsWith(o, fd ? i + fd[0].length : i));
122
+ if (op && (fd || !/^\d/.test(c))) {
123
+ const at = i;
124
+ i += (fd ? fd[0].length : 0) + op.length;
125
+ const tok = { t: 'op', v: op, at, end: i, ...(fd ? { fd: fd[0] } : {}) };
126
+ toks.push(tok);
127
+ if (op === '<<' || op === '<<-') {
128
+ while (src[i] === ' ' || src[i] === '\t') i++;
129
+ let e = i;
130
+ while (e < src.length && !META.has(src[e])) e++;
131
+ tok.target = src.slice(i, e);
132
+ tok.end = e;
133
+ i = e;
134
+ pending.push({ delim: tok.target.replace(/["'\\]/g, ''), strip: op === '<<-', tok });
135
+ }
136
+ continue;
137
+ }
138
+ }
139
+ // A word.
140
+ const start = i;
141
+ while (i < src.length) {
142
+ const ch = src[i];
143
+ if (META.has(ch)) {
144
+ if (test && (ch === '(' || ch === ')' || ch === '<' || ch === '>' || (ch === '|' && src[i + 1] !== '|'))) { i++; continue; }
145
+ if (ch === '(' && /(?:^|[^\\])(?:[A-Za-z_]\w*(?:\[[^\]]*\])?\+?=|[@!*+?])$/.test(src.slice(start, i))) { i = skipBalanced(src, i); continue; }
146
+ break;
147
+ }
148
+ if (ch === '\\') { i += 2; continue; }
149
+ if (ch === "'") { i = skipSingle(src, i); continue; }
150
+ if (ch === '"') { i = skipDouble(src, i); continue; }
151
+ if (ch === '`') { i = skipBacktick(src, i); continue; }
152
+ if (ch === '$') {
153
+ const n = src[i + 1];
154
+ if (n === '(') { i = skipBalanced(src, i + 1); continue; }
155
+ if (n === '{') { i = skipBrace(src, i + 1); continue; }
156
+ if (n === "'") { i = skipAnsi(src, i); continue; }
157
+ if (n === '"') { i = skipDouble(src, i + 1); continue; }
158
+ }
159
+ i++;
160
+ }
161
+ if (i === start) { i++; continue; }
162
+ const v = src.slice(start, i);
163
+ toks.push({ t: 'word', v, at: start, end: i });
164
+ if (v === '[[' && !test && atStartBefore(toks)) test = true;
165
+ }
166
+ return toks;
167
+ }
168
+ function atStartBefore(toks) {
169
+ const t = toks[toks.length - 2];
170
+ return !t || t.t === 'nl' || (t.t === 'op' && !REDIR.has(t.v)) || (t.t === 'word' && CMD_START.has(t.v));
171
+ }
172
+
173
+ // ── Parser ────────────────────────────────────────────────────────────────────────────────────────────
174
+
175
+ function parse(src) {
176
+ const toks = lex(src);
177
+ let p = 0, last = null;
178
+ const tok = () => toks[p];
179
+ const take = () => { const t = toks[p++]; if (t && t.t !== 'nl') last = t; return t; };
180
+ const isW = (v) => tok()?.t === 'word' && tok().v === v;
181
+ const isOp = (v) => tok()?.t === 'op' && tok().v === v;
182
+ const skipNl = () => { while (tok()?.t === 'nl') p++; };
183
+ const finish = (node, first) => Object.assign(node, { at: first.at, end: last ? last.end : first.end });
184
+
185
+ function list(stops) {
186
+ const items = [];
187
+ for (;;) {
188
+ while (tok() && (tok().t === 'nl' || (tok().t === 'op' && (tok().v === ';' || tok().v === '&')))) p++;
189
+ const t = tok();
190
+ if (!t || stops.has(t.v) && (t.t === 'word' || t.t === 'op')) break;
191
+ const before = p;
192
+ const node = andOr(stops);
193
+ if (node) { if (isOp('&')) node.background = true; items.push(node); }
194
+ if (p === before) take();
195
+ }
196
+ return items;
197
+ }
198
+ function andOr(stops) {
199
+ const first = tok();
200
+ const head = pipeline(stops);
201
+ if (!head) return null;
202
+ const rest = [];
203
+ while (isOp('&&') || isOp('||')) {
204
+ const op = take().v;
205
+ skipNl();
206
+ const n = pipeline(stops);
207
+ if (!n) break;
208
+ rest.push({ op, node: n });
209
+ }
210
+ return rest.length ? finish({ type: 'andor', first: head, rest }, first) : head;
211
+ }
212
+ function pipeline(stops) {
213
+ const first = tok();
214
+ let negate = false;
215
+ if (isW('!')) { take(); negate = true; }
216
+ const c0 = command(stops);
217
+ if (!c0) return null;
218
+ const cmds = [c0];
219
+ while (isOp('|') || isOp('|&')) { take(); skipNl(); const c = command(stops); if (!c) break; cmds.push(c); }
220
+ return cmds.length === 1 && !negate ? c0 : finish({ type: 'pipeline', cmds, negate }, first);
221
+ }
222
+ function redirsAfter(node) {
223
+ while (tok()?.t === 'op' && REDIR.has(tok().v)) node.redirs.push(redir());
224
+ if (last) node.end = Math.max(node.end, last.end);
225
+ return node;
226
+ }
227
+ function redir() {
228
+ const r = take();
229
+ if (r.target != null) return { op: r.v, fd: r.fd, target: r.target, body: r.body };
230
+ const t = tok();
231
+ if (t?.t === 'word') { take(); return { op: r.v, fd: r.fd, target: t.v }; }
232
+ return { op: r.v, fd: r.fd, target: '' };
233
+ }
234
+ function command(stops) {
235
+ const t = tok();
236
+ if (!t) return null;
237
+ if (t.t === 'op') {
238
+ if (t.v !== '(') return null;
239
+ take();
240
+ const body = list(new Set([')']));
241
+ if (isOp(')')) take();
242
+ return redirsAfter(finish({ type: 'subshell', body, redirs: [] }, t));
243
+ }
244
+ if (t.t !== 'word') return null;
245
+ if (t.arith != null) { take(); return redirsAfter(finish({ type: 'arith', expr: t.arith, redirs: [] }, t)); }
246
+ switch (t.v) {
247
+ case 'if': return redirsAfter(ifCmd());
248
+ case 'for': case 'select': return redirsAfter(forCmd());
249
+ case 'while': case 'until': return redirsAfter(whileCmd());
250
+ case 'case': return redirsAfter(caseCmd());
251
+ case '{': { take(); const body = list(new Set(['}'])); if (isW('}')) take(); return redirsAfter(finish({ type: 'group', body, redirs: [] }, t)); }
252
+ case 'function': return fnDef(true);
253
+ case '[[': {
254
+ take();
255
+ const ws = [];
256
+ while (tok() && !(tok().t === 'word' && tok().v === ']]') && tok().t !== 'nl') ws.push(take().v);
257
+ if (isW(']]')) take();
258
+ return redirsAfter(finish({ type: 'simple', words: ['[[', ...ws, ']]'], assigns: [], redirs: [] }, t));
259
+ }
260
+ default: break;
261
+ }
262
+ if (toks[p + 1]?.t === 'op' && toks[p + 1].v === '(' && toks[p + 2]?.t === 'op' && toks[p + 2].v === ')' && /^[\w:.@-]+$/.test(t.v)) return fnDef(false);
263
+ return simple();
264
+ }
265
+ function fnDef(keyword) {
266
+ const first = take();
267
+ const name = keyword ? take()?.v ?? '' : first.v;
268
+ if (isOp('(')) { take(); if (isOp(')')) take(); }
269
+ skipNl();
270
+ const body = command(new Set());
271
+ return finish({ type: 'function', name, body: body ? (body.type === 'group' ? body.body : [body]) : [], redirs: [] }, first);
272
+ }
273
+ function simple() {
274
+ const first = tok();
275
+ const node = { type: 'simple', words: [], assigns: [], redirs: [] };
276
+ while (tok()) {
277
+ const t = tok();
278
+ if (t.t === 'op' && REDIR.has(t.v)) { node.redirs.push(redir()); continue; }
279
+ if (t.t !== 'word') break;
280
+ take();
281
+ if (!node.words.length && /^[A-Za-z_]\w*(?:\[[^\]]*\])?\+?=/.test(t.v)) node.assigns.push(t.v);
282
+ else node.words.push(t.v);
283
+ }
284
+ return finish(node, first);
285
+ }
286
+ function ifCmd() {
287
+ const first = take();
288
+ const clauses = [];
289
+ let cond = list(new Set(['then']));
290
+ if (isW('then')) take();
291
+ let body = list(new Set(['elif', 'else', 'fi']));
292
+ clauses.push({ cond, body, at: first.at });
293
+ let otherwise = null;
294
+ while (isW('elif')) {
295
+ const at = take().at;
296
+ cond = list(new Set(['then']));
297
+ if (isW('then')) take();
298
+ body = list(new Set(['elif', 'else', 'fi']));
299
+ clauses.push({ cond, body, at });
300
+ }
301
+ let elseAt = null;
302
+ if (isW('else')) { elseAt = take().at; otherwise = list(new Set(['fi'])); }
303
+ if (isW('fi')) take();
304
+ return finish({ type: 'if', clauses, otherwise, elseAt, redirs: [] }, first);
305
+ }
306
+ function loopBody() {
307
+ while (tok() && (tok().t === 'nl' || isOp(';'))) p++;
308
+ if (isW('do')) { take(); const b = list(new Set(['done'])); if (isW('done')) take(); return b; }
309
+ if (isW('{')) { take(); const b = list(new Set(['}'])); if (isW('}')) take(); return b; }
310
+ return [];
311
+ }
312
+ function forCmd() {
313
+ const first = take();
314
+ if (tok()?.arith != null) { const expr = take().arith; return finish({ type: 'for', cstyle: expr, body: loopBody(), redirs: [] }, first); }
315
+ const name = tok()?.t === 'word' ? take().v : '';
316
+ skipNl();
317
+ let items = null;
318
+ if (isW('in')) { take(); items = []; while (tok()?.t === 'word') items.push(take().v); }
319
+ return finish({ type: 'for', select: first.v === 'select', name, items, body: loopBody(), redirs: [] }, first);
320
+ }
321
+ function whileCmd() {
322
+ const first = take();
323
+ const cond = list(new Set(['do']));
324
+ return finish({ type: 'while', until: first.v === 'until', cond, body: loopBody(), redirs: [] }, first);
325
+ }
326
+ function caseCmd() {
327
+ const first = take();
328
+ const word = tok()?.t === 'word' ? take().v : '';
329
+ skipNl();
330
+ if (isW('in')) take();
331
+ const arms = [];
332
+ for (;;) {
333
+ skipNl();
334
+ if (!tok() || isW('esac')) { if (tok()) take(); break; }
335
+ const at = tok().at;
336
+ if (isOp('(')) take();
337
+ const patterns = [];
338
+ while (tok() && !isOp(')')) { const t = take(); if (t.t === 'word') patterns.push(t.v); else if (t.t === 'nl') break; }
339
+ if (isOp(')')) take();
340
+ const before = p;
341
+ const body = list(new Set([';;', ';&', ';;&', 'esac']));
342
+ const endAt = last ? last.end : at;
343
+ if (isOp(';;') || isOp(';&') || isOp(';;&')) take();
344
+ arms.push({ patterns, body, at, end: endAt });
345
+ if (p === before && !patterns.length) take();
346
+ }
347
+ return finish({ type: 'case', word, arms, redirs: [] }, first);
348
+ }
349
+ return list(new Set());
350
+ }
351
+
352
+ // ── Words: a shell word in plain words ──────────────────────────────────────────────────────────────────
353
+ //
354
+ // Text with values inside (docs/spec.md, "Text with values inside"): the literal parts of a word are kept exactly as
355
+ // the code writes them, and each inserted value is a placeholder in guillemets: a plain variable by its name
356
+ // ("${NVM_DIR}/alias" -> "«NVM_DIR»/alias"), anything else by its code as written ("«$1»", "«${1-}»", "«$(cat)»").
357
+ // A word that is one value and nothing else is a value, and reads in words ("the first input"). A value Thunder has
358
+ // no exact words for is shown as code, in backticks, never as a guess.
359
+
360
+ const ORDINAL = ['', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth'];
361
+ const SPECIAL = { '@': 'all the inputs', '*': 'all the inputs', '#': 'how many inputs', '?': "the last command's exit code", '0': 'this script', $: "this script's process id", '!': 'the last background command', PWD: 'the current folder', HOME: 'the home folder', RANDOM: 'a random number', USER: 'the user name', BASH_SOURCE: 'this file', OLDPWD: 'the previous folder', PATH: 'the PATH (where commands are found)' };
362
+ function varWords(name) {
363
+ if (/^[1-9]$/.test(name)) return `the ${ORDINAL[name]} input`;
364
+ if (SPECIAL[name]) return SPECIAL[name];
365
+ return words(name.replace(/\[.*$/, '')) || name;
366
+ }
367
+ /** Code shown as code (the faithfulness gate's form): in backticks, shortened visibly when long. */
368
+ const asCode = (code, n = 100) => { const t = String(code).replace(/\s+/g, ' ').trim(); return `\`${t.length > n ? `${t.slice(0, n - 1)}…` : t}\``; };
369
+ const isCode = (said) => /^`[^`]*`$/.test(String(said));
370
+ const GLOBBY = /(?<!\\)[*?[]/;
371
+
372
+ /**
373
+ * `${…}` in words: ${x:-d} -> "x, or "d" when it is empty or not set", ${x#v} -> "x without "v" at the start",
374
+ * ${#x} -> "the length of x". Null when there are no exact words for it (the caller shows the code).
375
+ */
376
+ function braceWords(inner) {
377
+ let m;
378
+ if ((m = inner.match(/^#([A-Za-z_]\w*|[@*])(\[[@*]\])?$/))) return m[1] === '@' || m[1] === '*' ? 'how many inputs' : m[2] ? `how many items ${varWords(m[1])} has` : `the length of ${varWords(m[1])}`;
379
+ const sm = inner.match(/^(!?)([A-Za-z_]\w*|[0-9]|[@*#?$!])(\[[^\]]*\])?/);
380
+ if (!sm) return null;
381
+ const [head, bang, name, idx] = sm;
382
+ if (bang) return idx || inner.length > head.length || !/^[A-Za-z_]/.test(name) ? null : `the setting whose name is in ${varWords(name)}`;
383
+ let subj = varWords(name);
384
+ if (idx) {
385
+ const i = idx.slice(1, -1);
386
+ if (/^[@*]$/.test(i)) subj = `all the items in ${varWords(name)}`;
387
+ else { const iw = sayWord(i); if (isCode(iw)) return null; subj = `item ${iw.replace(/^"|"$/g, '')} of ${varWords(name)}`; }
388
+ }
389
+ const rest = inner.slice(head.length);
390
+ if (!rest) return subj;
391
+ if ((m = rest.match(/^(:?)([-=?+])([\s\S]*)$/))) {
392
+ const [, colon, op, w] = m;
393
+ const when = colon ? 'is empty or not set' : 'is not set';
394
+ const dw = w === '' ? '""' : sayWord(w);
395
+ const d = / when it /.test(dw) ? `(${dw})` : dw;
396
+ if (op === '-') return w === '' ? subj : `${subj}, or ${d} when it ${when}`;
397
+ if (op === '=') return `${subj} (first set to ${d} when it ${when})`;
398
+ if (op === '?') return `${subj} (the script stops when it ${when})`;
399
+ return `${d} when ${subj} ${colon ? 'is set and not empty' : 'is set'}, otherwise nothing`;
400
+ }
401
+ if ((m = rest.match(/^(##?|%%?)([\s\S]*)$/))) {
402
+ const [, op, p] = m;
403
+ if (/\$/.test(p)) return null;
404
+ const what = GLOBBY.test(p) ? `the ${op.length === 2 ? 'longest' : 'shortest'} match of "${p}"` : `"${p}"`;
405
+ return `${subj} without ${what} at the ${op[0] === '#' ? 'start' : 'end'}`;
406
+ }
407
+ if ((m = rest.match(/^\/([/#%]?)((?:\\.|[^/\\])*)(?:\/([\s\S]*))?$/))) {
408
+ const [, mode, p, r] = m;
409
+ if (!p || /\$/.test(p)) return null;
410
+ const pat = GLOBBY.test(p) ? `match of "${p}"` : `"${p}"`;
411
+ const which = mode === '/' ? `every ${pat}` : mode === '#' ? `${pat} at the start` : mode === '%' ? `${pat} at the end` : `the first ${pat}`;
412
+ if (r == null || r === '') return `${subj} with ${which} removed`;
413
+ const rw = sayWord(r);
414
+ return isCode(rw) ? null : `${subj} with ${which} replaced by ${rw}`;
415
+ }
416
+ if (rest === '^^') return `${subj} in capital letters`;
417
+ if (rest === ',,') return `${subj} in small letters`;
418
+ if (rest === '^') return `${subj} with its first letter a capital`;
419
+ if ((m = rest.match(/^:\s*(\d+)(?::\s*(\d+))?$/))) return m[2] ? `${m[2]} characters of ${subj}, from position ${m[1]} (counting from 0)` : `${subj} from position ${m[1]} on (counting from 0)`;
420
+ return null;
421
+ }
422
+
423
+ /**
424
+ * A word's parts: literal text and inserted values (variables, command output, arithmetic). Each literal part keeps
425
+ * `lit` (what the shell makes of it) and `raw` (as the code writes it); each value keeps `code` (as written), `name`
426
+ * (a plain variable's name, else null), and `v` (its words, or null when there are none).
427
+ */
428
+ function partsOf(raw) {
429
+ const out = [];
430
+ const lit = (s, r = s) => { if (!s && !r) return; const l = out[out.length - 1]; if (l && l.lit != null) { l.lit += s; l.raw += r; } else out.push({ lit: s, raw: r }); };
431
+ const walk = (s, quoted) => {
432
+ for (let i = 0; i < s.length; i++) {
433
+ const c = s[i];
434
+ if (c === '\\') { const n = s[i + 1] ?? ''; if (n === '\n') { i++; continue; } lit(quoted && !'$`"\\'.includes(n) ? c + n : n, c + n); i++; continue; }
435
+ if (c === "'" && !quoted) { const e = skipSingle(s, i); const t = s.slice(i + 1, e - 1); lit(t, t); i = e - 1; continue; }
436
+ if (c === '"' && !quoted) { const e = skipDouble(s, i); walk(s.slice(i + 1, e - 1), true); i = e - 1; continue; }
437
+ if (c === '`') { const e = skipBacktick(s, i); out.push({ cmd: s.slice(i + 1, e - 1), code: s.slice(i, e) }); i = e - 1; continue; }
438
+ if (c === '$') {
439
+ const n = s[i + 1];
440
+ if (n === '(' && s[i + 2] === '(') { const e = skipBalanced(s, i + 1); out.push({ arith: s.slice(i + 3, e - 2), code: s.slice(i, e) }); i = e - 1; continue; }
441
+ if (n === '(') { const e = skipBalanced(s, i + 1); out.push({ cmd: s.slice(i + 2, e - 1), code: s.slice(i, e) }); i = e - 1; continue; }
442
+ if (n === '{') { const e = skipBrace(s, i + 1); const inner = s.slice(i + 2, e - 1); out.push({ v: braceWords(inner), code: s.slice(i, e), name: /^[A-Za-z_]\w*$/.test(inner) ? inner : null }); i = e - 1; continue; }
443
+ if (n === "'" && !quoted) { const e = skipAnsi(s, i); const t = s.slice(i + 2, e - 1); lit(t, t); i = e - 1; continue; }
444
+ const m = s.slice(i + 1).match(/^(?:[A-Za-z_]\w*|[0-9@*#?$!-])/);
445
+ if (m) { out.push({ v: varWords(m[0]), code: `$${m[0]}`, name: /^[A-Za-z_]/.test(m[0]) ? m[0] : null }); i += m[0].length; continue; }
446
+ }
447
+ if (!quoted && (/[*?]/.test(c) || (c === '[' && s.indexOf(']', i + 2) > i))) out.push({ glob: true });
448
+ lit(c);
449
+ }
450
+ };
451
+ walk(String(raw), false);
452
+ return out;
453
+ }
454
+ const isGlob = (raw) => partsOf(raw).some((p) => p.glob);
455
+
456
+ /** Command output in words: "the output of building the Docker image web"; `$(< file)` is the file's contents. */
457
+ function outputWords(cmdText) {
458
+ const file = String(cmdText).trim().match(/^<\s*(\S+)$/);
459
+ if (file) return `the contents of ${sayWord(file[1])}`;
460
+ try {
461
+ const nodes = parse(cmdText);
462
+ const n = nodes[0];
463
+ if (!n) return 'the output of a command';
464
+ const say = sayNode(n);
465
+ return say && !isCode(say) ? `the output of ${gerund(say)}` : `the output of ${asCode(cmdText)}`;
466
+ } catch { return 'the output of a command'; }
467
+ }
468
+
469
+ /** One value's words: its words when Thunder has them, else its code. */
470
+ function valueWords(p) {
471
+ if (p.cmd != null) return outputWords(p.cmd);
472
+ if (p.arith != null) return arithWords(p.arith) ?? asCode(p.code);
473
+ return p.v ?? asCode(p.code);
474
+ }
475
+ /** One word in plain words: "prod" in quotes, $ENV_NAME as "env name", "$DIR/app.yaml" as "«DIR»/app.yaml". */
476
+ export function sayWord(raw) {
477
+ const parts = partsOf(raw).filter((p) => !p.glob);
478
+ if (!parts.length) return '""';
479
+ if (parts.length === 1) {
480
+ const p = parts[0];
481
+ if (p.lit != null) return /^-?\d+(\.\d+)?$/.test(p.raw) ? p.raw : `"${clip(p.raw, 80)}"`;
482
+ return valueWords(p);
483
+ }
484
+ return `"${textOf(parts)}"`;
485
+ }
486
+ /** Shortened visibly: at the first line break, or at n characters. */
487
+ const clip = (t, n) => { const nl = t.indexOf('\n'); const s = nl >= 0 ? `${t.slice(0, nl)}…` : t; return s.length > n ? `${s.slice(0, n - 1)}…` : s; };
488
+ /** A placeholder for one inserted value: its name when it is a plain variable, else its code as written. */
489
+ const slot = (p) => `«${p.name ?? p.code}»`;
490
+ /** Text with its literal parts exactly as written and each value as a placeholder: "Deploying «APP» to «$1»". */
491
+ function textOf(parts) {
492
+ return clip(parts.map((p) => (p.lit != null ? p.raw : p.code != null ? slot(p) : '')).join(''), 120);
493
+ }
494
+ /** Words (echo's arguments) as one message: { text } with placeholders, or { value } when it is one value only. */
495
+ function messageOf(raws) {
496
+ const parts = raws.flatMap((r, i) => [...(i ? [{ lit: ' ', raw: ' ' }] : []), ...partsOf(r).filter((p) => !p.glob)]);
497
+ if (parts.length === 1 && parts[0].lit == null) return { value: valueWords(parts[0]), text: slot(parts[0]) };
498
+ return { text: textOf(parts) };
499
+ }
500
+ const message = (raws) => messageOf(raws).text;
501
+
502
+ /**
503
+ * printf's format with each conversion paired with its argument: printf '%s/alias %5d\n' "$dir" "$n" ->
504
+ * "«dir»/alias «n as %5d»\n". Null when they cannot be paired (more or fewer arguments, a format built from values,
505
+ * an argument that is many values like "$@").
506
+ */
507
+ function printfText(fmt, args) {
508
+ const fp = partsOf(fmt ?? '').filter((p) => !p.glob);
509
+ if (fp.some((p) => p.lit == null)) return null;
510
+ const f = fp.map((p) => p.raw).join('');
511
+ const convs = [...f.matchAll(/%%|%([-+ #0]*\d*(?:\.\d+)?)([diouxXfFeEgGaAcsbq])/g)].filter((m) => m[0] !== '%%');
512
+ if (convs.length !== args.length) return null;
513
+ if (args.some((a) => /\$\{?[@]|\[[@*]\]\}/.test(a) || isGlob(a))) return null;
514
+ let k = 0;
515
+ const slots = args.map((a, i) => {
516
+ const ps = partsOf(a).filter((p) => !p.glob);
517
+ const m = convs[i];
518
+ const plain = !m[1] && /[sb]/.test(m[2]);
519
+ // A text argument put in as it is (%s) is its own text with placeholders; anything else is one placeholder.
520
+ if (plain && ps.length !== 1) return textOf(ps);
521
+ if (plain && ps[0].lit != null) return ps[0].raw;
522
+ const inner = ps.length === 1 && ps[0].lit == null ? (ps[0].name ?? ps[0].code) : a;
523
+ return `«${inner}${m[1] || !/[sdb]/.test(m[2]) ? ` as %${m[1]}${m[2]}` : ''}»`;
524
+ });
525
+ const text = f.replace(/%%|%([-+ #0]*\d*(?:\.\d+)?)([diouxXfFeEgGaAcsbq])/g, (m) => (m === '%%' ? m : slots[k++]));
526
+ return { text: clip(text, 120), value: convs.length === 1 && f === convs[0][0] && /^%[sb]$/.test(f) ? (() => { const ps = partsOf(args[0]).filter((p) => !p.glob); return ps.length === 1 && ps[0].lit == null ? valueWords(ps[0]) : null; })() : null };
527
+ }
528
+
529
+ const ARITH_OPS = { '==': 'is', '!=': 'is not', '>=': 'is at least', '<=': 'is at most', '>': 'is more than', '<': 'is less than', '&&': 'and', '||': 'or', '+': 'plus', '-': 'minus', '*': 'times', '**': 'to the power of', '/': 'divided by', '%': 'remainder after dividing by', '!': 'not' };
530
+ /**
531
+ * Arithmetic in words, or null when it has anything Thunder cannot say exactly (assignments, commas, ?:, ++, bit
532
+ * operators, an expansion without words): every character must be accounted for.
533
+ */
534
+ function arithWords(expr) {
535
+ const s = String(expr).replace(/"/g, '');
536
+ const out = [];
537
+ let i = 0;
538
+ while (i < s.length) {
539
+ const rest = s.slice(i);
540
+ let m;
541
+ if ((m = rest.match(/^\s+/))) { i += m[0].length; continue; }
542
+ if ((m = rest.match(/^\d+/))) { out.push(m[0]); i += m[0].length; continue; }
543
+ // Inside arithmetic only a plain value reads in words (`${x}`, `${#x}`, `${#x[@]}`); `${d:-0}` is shown as code.
544
+ if ((m = rest.match(/^\$\{(#?[A-Za-z_]\w*(?:\[[@*]\])?|#[@*])\}/))) { out.push(braceWords(m[1])); i += m[0].length; continue; }
545
+ if ((m = rest.match(/^\$?([A-Za-z_]\w*)(?!\s*\[)/))) { out.push(varWords(m[1])); i += m[0].length; continue; }
546
+ if ((m = rest.match(/^\$([0-9#?])/))) { out.push(varWords(m[1])); i += m[0].length; continue; }
547
+ if (/^(?:\+\+|--|[-+*/%]=|<<|>>|=(?!=)|[,?:^~[\]]|&(?!&)|\|(?!\|))/.test(rest)) return null;
548
+ if ((m = rest.match(/^(?:==|!=|>=|<=|&&|\|\||\*\*|[-+*/%<>!])/))) { out.push(ARITH_OPS[m[0]]); i += m[0].length; continue; }
549
+ if (rest[0] === '(' || rest[0] === ')') { out.push(rest[0]); i++; continue; }
550
+ return null;
551
+ }
552
+ return out.length ? out.join(' ').replace(/\( /g, '(').replace(/ \)/g, ')') : null;
553
+ }
554
+ /** An arithmetic statement (`(( … ))`) in words, or null. Commas run several statements in order. */
555
+ function arithStatement(expr) {
556
+ const e = String(expr).trim();
557
+ if (/,/.test(e)) {
558
+ const parts = [];
559
+ let depth = 0, from = 0;
560
+ for (let i = 0; i < e.length; i++) { if (e[i] === '(') depth++; else if (e[i] === ')') depth--; else if (e[i] === ',' && !depth) { parts.push(e.slice(from, i)); from = i + 1; } }
561
+ parts.push(e.slice(from));
562
+ const said = parts.map(arithStatement);
563
+ if (said.some((x) => !x)) return null;
564
+ return said.map((x, i) => (i ? `then ${x.charAt(0).toLowerCase()}${x.slice(1)}` : x)).join('; ');
565
+ }
566
+ let m, w;
567
+ if ((m = e.match(/^(\w+)\s*\+\+$|^\+\+\s*(\w+)$/))) return `Adds one to ${varWords(m[1] ?? m[2])}`;
568
+ if ((m = e.match(/^(\w+)\s*--$|^--\s*(\w+)$/))) return `Subtracts one from ${varWords(m[1] ?? m[2])}`;
569
+ if ((m = e.match(/^(\w+)\s*([-+*/])=\s*(.+)$/)) && (w = arithWords(m[3]))) return { '+': `Adds ${w} to ${varWords(m[1])}`, '-': `Subtracts ${w} from ${varWords(m[1])}`, '*': `Multiplies ${varWords(m[1])} by ${w}`, '/': `Divides ${varWords(m[1])} by ${w}` }[m[2]];
570
+ if ((m = e.match(/^(\w+)\s*=(?!=)\s*(.+)$/)) && (w = arithWords(m[2]))) return `Sets ${varWords(m[1])} to ${w}`;
571
+ return null;
572
+ }
573
+ /** An arithmetic statement's step words: the statement, the value it works out, or null (shown as code). */
574
+ const arithSays = (expr) => { const st = arithStatement(expr); if (st) return st; const w = arithWords(expr); return w ? `Works out ${w}` : null; };
575
+
576
+ // ── Tests and conditions ──────────────────────────────────────────────────────────────────────────────
577
+
578
+ const PLACE = /(?:^|\s)(?:file|dir|directory|folder|path)$/;
579
+ const fileLeaf = (noun, x, neg) => { const w = sayWord(x); const own = PLACE.test(w); return neg ? (own ? `${w} does not exist` : `there is no ${noun} ${w}`) : (own ? `${w} exists` : `the ${noun} ${w} exists`); };
580
+ const UNARY = {
581
+ '-f': (x, n) => fileLeaf('file', x, n), '-d': (x, n) => fileLeaf('folder', x, n),
582
+ '-e': (x, n) => `${sayWord(x)} ${n ? 'does not exist' : 'exists'}`, '-a': (x, n) => `${sayWord(x)} ${n ? 'does not exist' : 'exists'}`,
583
+ '-s': (x, n) => `${sayWord(x)} ${n ? 'is empty or missing' : 'has something in it'}`,
584
+ '-r': (x, n) => `${sayWord(x)} ${n ? 'cannot' : 'can'} be read`, '-w': (x, n) => `${sayWord(x)} ${n ? 'cannot' : 'can'} be written`,
585
+ '-x': (x, n) => `${sayWord(x)} ${n ? 'cannot' : 'can'} be run`, '-L': (x, n) => `${sayWord(x)} is ${n ? 'not ' : ''}a link`, '-h': (x, n) => `${sayWord(x)} is ${n ? 'not ' : ''}a link`,
586
+ '-z': (x, n) => `${sayWord(x)} is ${n ? 'set' : 'empty'}`, '-n': (x, n) => `${sayWord(x)} is ${n ? 'empty' : 'set'}`,
587
+ '-v': (x, n) => `${varWords(x.replace(/["']/g, ''))} is ${n ? 'not ' : ''}set`, '-t': (x, n) => `it is ${n ? 'not ' : ''}running in a terminal`,
588
+ };
589
+ const BINARY = {
590
+ '=': ['is', 'is not'], '==': ['is', 'is not'], '!=': ['is not', 'is'], '-eq': ['is', 'is not'], '-ne': ['is not', 'is'],
591
+ '-lt': ['is less than', 'is at least'], '-le': ['is at most', 'is more than'], '-gt': ['is more than', 'is at most'], '-ge': ['is at least', 'is less than'],
592
+ '=~': ['matches the pattern', 'does not match the pattern'], '<': ['comes before', 'does not come before'], '>': ['comes after', 'does not come after'],
593
+ '-nt': ['is newer than', 'is not newer than'], '-ot': ['is older than', 'is not older than'], '-ef': ['is the same file as', 'is not the same file as'],
594
+ };
595
+ /** A test's words ([ … ], [[ … ]], test …) as a sentence, or null when they are not a test it knows. */
596
+ function testWords(ws, neg, double) {
597
+ let i = 0;
598
+ const peek = () => ws[i];
599
+ const orExpr = (n) => {
600
+ const parts = [andExpr(n)];
601
+ while (peek() === '-o' || peek() === '||') { i++; parts.push(andExpr(n)); }
602
+ return parts.some((x) => x == null) ? null : parts.join(n ? ' and ' : ' or ');
603
+ };
604
+ const andExpr = (n) => {
605
+ const parts = [notExpr(n)];
606
+ while (peek() === '-a' && ws.length - i > 1 && ws[i + 2] !== undefined || peek() === '&&') { i++; parts.push(notExpr(n)); }
607
+ return parts.some((x) => x == null) ? null : parts.join(n ? ' or ' : ' and ');
608
+ };
609
+ const notExpr = (n) => { if (peek() === '!') { i++; return notExpr(!n); } return primary(n); };
610
+ const primary = (n) => {
611
+ const t = peek();
612
+ if (t === undefined) return null;
613
+ if (t === '(' || t === '\\(') { i++; const e = orExpr(n); if (peek() === ')' || peek() === '\\)') i++; return e; }
614
+ if (UNARY[t] && ws[i + 1] !== undefined && !BINARY[ws[i + 1]]) { i += 2; return UNARY[t](ws[i - 1], n); }
615
+ if (BINARY[ws[i + 1]] && ws[i + 2] !== undefined) {
616
+ const [a, op, b] = [ws[i], ws[i + 1], ws[i + 2]];
617
+ i += 3;
618
+ if ((op === '==' || op === '=' || op === '!=') && double && isGlob(b)) { const pos = op !== '!='; return `${sayWord(a)} ${pos !== n ? 'matches' : 'does not match'} ${b}`; }
619
+ // Compared with "" is a question about being empty.
620
+ if ((op === '=' || op === '==' || op === '!=') && /^(?:""|'')$/.test(b)) return `${sayWord(a)} is ${(op === '!=') !== n ? 'not empty' : 'empty'}`;
621
+ const pair = BINARY[op];
622
+ const right = op === '=~' ? `"${b.replace(/^["']|["']$/g, '')}"` : sayWord(b);
623
+ return `${sayWord(a)} ${pair[n ? 1 : 0]} ${right}`;
624
+ }
625
+ i++;
626
+ return `${sayWord(t)} is ${n ? 'empty' : 'set'}`;
627
+ };
628
+ const r = orExpr(neg);
629
+ return i >= ws.length ? r : null;
630
+ }
631
+
632
+ const PREDICATE_FN = /^(?:_*(?:is|has|can|should|was|are|does|needs?|uses?)_|.*_(?:exists|installed|available|enabled|running|ok|ready)$)/;
633
+ /** A list of commands used as a question (`if …; then`, `while …`): its last command's success, in words. */
634
+ function condWords(nodes, neg = false) {
635
+ const n = nodes[nodes.length - 1];
636
+ if (!n) return 'it is true';
637
+ return nodeCond(n, neg);
638
+ }
639
+ function nodeCond(n, neg) {
640
+ if (n.type === 'pipeline') {
641
+ if (n.cmds.length === 1) return nodeCond(n.cmds[0], neg !== n.negate);
642
+ const lastCmd = n.cmds[n.cmds.length - 1];
643
+ if (lastCmd.type === 'simple' && /^e?grep$/.test(lastCmd.words[0]) && lastCmd.words.some((w) => /^-[a-zA-Z]*q/.test(w))) {
644
+ const pat = positional(lastCmd.words.slice(1), ['-e'])[0];
645
+ const from = sayNode({ ...n, cmds: n.cmds.slice(0, -1), negate: false });
646
+ return `the output of ${from ? gerund(from) : 'the command'} ${neg !== n.negate ? 'does not contain' : 'contains'} ${sayWord(pat ?? '?')}`;
647
+ }
648
+ const s = sayNode({ ...n, negate: false });
649
+ return `${gerund(s ?? 'Runs the commands')} ${neg !== n.negate ? 'fails' : 'works'}`;
650
+ }
651
+ if (n.type === 'andor' && n.rest.every((r) => r.op === '&&')) return [n.first, ...n.rest.map((r) => r.node)].map((x) => nodeCond(x, neg)).join(neg ? ' or ' : ' and ');
652
+ if (n.type === 'andor' && n.rest.every((r) => r.op === '||')) return [n.first, ...n.rest.map((r) => r.node)].map((x) => nodeCond(x, neg)).join(neg ? ' and ' : ' or ');
653
+ if (n.type === 'arith') {
654
+ // (( x )) is true when x is not 0.
655
+ const lone = n.expr.trim().match(/^\$?([A-Za-z_]\w*)$/);
656
+ const w = lone ? `${varWords(lone[1])} is not 0` : arithWords(n.expr) ?? asCode(`((${n.expr}))`);
657
+ return neg ? `not: ${w}` : w;
658
+ }
659
+ if (n.type === 'group' || n.type === 'subshell') return condWords(n.body, neg);
660
+ if (n.type !== 'simple') return `${gerund(sayNode(n) ?? 'Runs the commands')} ${neg ? 'fails' : 'works'}`;
661
+ const [name0, ...args] = n.words;
662
+ const name = String(name0 ?? "").replace(/^\\(?=[\w.])/, "");
663
+ if (name === '[' || name === 'test' || name === '[[') {
664
+ const inner = name === 'test' ? args : args.slice(0, -1);
665
+ const r = testWords(inner, neg, name === '[[');
666
+ if (r) return r;
667
+ }
668
+ if ((name === 'command' && args[0] === '-v') || name === 'which' || name === 'type' || name === 'hash') {
669
+ const what = positional(args)[0];
670
+ return `${sayWord(what ?? '?')} is ${neg ? 'not ' : ''}installed`;
671
+ }
672
+ if (/^e?grep$/.test(name) && args.some((a) => /^-[a-zA-Z]*q/.test(a))) {
673
+ const pos = positional(args, ['-e', '-m']);
674
+ const pat = /** @type {string} */ (pos.shift());
675
+ return `${pos.length ? listWords(pos.map(sayWord)) : 'the input'} ${neg ? 'does not contain' : 'contains'} ${sayWord(pat ?? '?')}`;
676
+ }
677
+ if (name === 'true' || name === ':') return neg ? 'never' : 'always';
678
+ if (name === 'false') return neg ? 'always' : 'never';
679
+ if (KNOWN_FNS.has(name) && PREDICATE_FN.test(name)) return `${neg ? 'not: ' : ''}${words(name)}${args.length ? ` (${listWords(args.map(sayWord))})` : ''}`;
680
+ const s = sayNode(n);
681
+ return `${gerund(s ?? `Runs ${name}`)} ${neg ? 'fails' : 'works'}`;
682
+ }
683
+
684
+ // ── Commands in words ─────────────────────────────────────────────────────────────────────────────────
685
+
686
+ let KNOWN_FNS = new Set();
687
+ let DIES = new Map(); // functions whose last step stops the script: name -> exit code
688
+
689
+ const SET_FLAGS = { e: 'stops at the first command that fails', u: 'treats a missing setting as a mistake', x: 'shows each command as it runs', o: '' };
690
+ const SET_LONG = { errexit: 'e', nounset: 'u', xtrace: 'x', pipefail: 'pipefail' };
691
+ function setWords(args) {
692
+ if (args[0] === '--') return args.length > 1 ? `Replaces the inputs with ${listWords(args.slice(1).map(sayWord))}` : 'Clears the inputs';
693
+ const on = [], off = [];
694
+ for (let i = 0; i < args.length; i++) {
695
+ const a = args[i];
696
+ const m = a.match(/^([-+])([a-zA-Z]+)$/);
697
+ if (!m) continue;
698
+ for (const f of m[2]) {
699
+ if (f === 'o') { const l = SET_LONG[args[i + 1]] ?? null; i++; if (l) (m[1] === '-' ? on : off).push(l); continue; }
700
+ (m[1] === '-' ? on : off).push(f);
701
+ }
702
+ }
703
+ const phrase = { e: 'Stops at the first command that fails', u: 'Treats a missing setting as a mistake', x: 'Shows each command as it runs', pipefail: 'Counts a failure anywhere in a pipe as a failure' };
704
+ const offPhrase = { e: 'Carries on even when a command fails', u: 'Allows missing settings', x: 'Stops showing each command', pipefail: 'Counts only the last command of a pipe' };
705
+ const said = [...on.filter((f) => phrase[f]).map((f) => phrase[f]), ...off.filter((f) => offPhrase[f]).map((f) => offPhrase[f])];
706
+ if (!said.length) return `Changes shell options (${args.join(' ')})`;
707
+ return [said[0], ...said.slice(1).map((s) => s.charAt(0).toLowerCase() + s.slice(1))].join(', ').replace(/, ([^,]*)$/, said.length > 1 ? ', and $1' : ', $1');
708
+ }
709
+ const TRAP_WHEN = (sigs) => {
710
+ const s = sigs.map((x) => x.replace(/^SIG/, '').toUpperCase());
711
+ if (s.includes('EXIT') || s.includes('0')) return 'At the end, even if something fails';
712
+ if (s.includes('ERR')) return 'Whenever a command fails';
713
+ if (s.some((x) => ['INT', 'TERM', 'HUP', 'QUIT'].includes(x))) return 'If it is stopped (Ctrl+C or a stop signal)';
714
+ if (s.includes('RETURN')) return 'When the function finishes';
715
+ return `When it gets the signal ${s.join(' or ')}`;
716
+ };
717
+
718
+ /** One assignment word (`X=val`, `X+=val`, `arr=(a b)`) in words. */
719
+ function assignWords(a, { exported = false, readonly = false } = {}) {
720
+ const m = a.match(/^([A-Za-z_]\w*)(\[[^\]]*\])?(\+?)=([\s\S]*)$/);
721
+ if (!m) return null;
722
+ const [, name, index, plus, val] = m;
723
+ const who = `${varWords(name)}${index ? `'s ${sayWord(index.slice(1, -1))}` : ''}`;
724
+ const tail = exported ? ' and shares it with the programs it runs' : readonly ? ' (it cannot change after this)' : '';
725
+ if (name === 'PATH' && /\$\{?PATH\}?/.test(val)) { const added = val.split(':').filter((x) => !/\$\{?PATH\}?/.test(x)); return `Adds ${listWords(added.map(sayWord))} to the PATH (where commands are found)`; }
726
+ if (/^\(/.test(val)) {
727
+ const inner = val.slice(1, -1).trim();
728
+ if (!inner) return `Starts ${who} as an empty list`;
729
+ const items = inner.split(/\s+/).filter(Boolean);
730
+ return `${plus ? 'Adds' : 'Sets'} ${plus ? `${listWords(items.map(sayWord))} to ${who}` : `${who} to the list ${listWords(items.slice(0, 6).map(sayWord))}${items.length > 6 ? ', …' : ''}`}${tail}`;
731
+ }
732
+ if (val === '' || val === '""' || val === "''") return `Empties ${who}${tail}`;
733
+ const pos = val.match(/^"?\$\{?([1-9])(?:(:?)[-=]([^}]*))?\}?"?$/);
734
+ if (pos) return `Takes ${who} from the ${ORDINAL[pos[1]]} input${pos[3] ? ` (${sayWord(pos[3])} when it is ${pos[2] ? 'empty or ' : ''}not given)` : ''}${tail}`;
735
+ const parts = partsOf(val).filter((p) => !p.glob);
736
+ if (parts.length === 1 && parts[0].arith != null) return `Works out ${who}: ${arithWords(parts[0].arith) ?? asCode(parts[0].code)}${tail}`;
737
+ if (plus) return `Adds ${sayWord(val)} to ${who}${tail}`;
738
+ return `Sets ${who} to ${sayWord(val)}${tail}`;
739
+ }
740
+
741
+ const isDevNull = (t) => /^\/dev\/null$/.test(t) || t === '&1' || t === '&2';
742
+ /** What happens to a command's output: ", saving what it prints to log.txt". */
743
+ function redirWords(redirs) {
744
+ const bits = [];
745
+ for (const r of redirs) {
746
+ if (r.fd === '2' || r.op === '>&' || r.op === '<&' || r.op === '&>' || r.op === '&>>') { if (r.op === '&>' && !isDevNull(r.target)) bits.push(`, saving everything it prints to ${sayWord(r.target)}`); continue; }
747
+ if ((r.op === '>' || r.op === '>|') && !isDevNull(r.target)) bits.push(`, saving what it prints to ${sayWord(r.target)}`);
748
+ else if (r.op === '>>' && !isDevNull(r.target)) bits.push(`, adding what it prints to the end of ${sayWord(r.target)}`);
749
+ else if (r.op === '<') bits.push(`, reading from ${sayWord(r.target)}`);
750
+ else if (r.op === '<<' || r.op === '<<-') bits.push(', given the text written below it');
751
+ else if (r.op === '<<<') bits.push(`, given ${sayWord(r.target)}`);
752
+ }
753
+ return bits.join('');
754
+ }
755
+ const toStderr = (redirs) => redirs.some((r) => (r.op === '>&' && r.target === '2' && (!r.fd || r.fd === '1')) || (r.fd === '1' && r.op === '>&' && r.target === '2') || ((r.op === '>' || r.op === '>>') && r.target === '/dev/stderr'));
756
+
757
+ /** A simple command as { kind, says, ... }, or null when it does nothing a reader needs (`:`, `true`). */
758
+ function simpleSays(n, ctx = null) {
759
+ // `\command`, `\cd`: a leading backslash only skips aliases; the command is the same.
760
+ let ws = n.words.map((w, i) => (i === 0 ? w.replace(/^\\(?=[\w.])/, '') : w));
761
+ if (!ws.length) {
762
+ if (!n.assigns.length) { const r = n.redirs.find((x) => x.op === '>' || x.op === '>|'); return r ? { kind: 'call', says: `Empties the file ${sayWord(r.target)}` } : null; }
763
+ const said = n.assigns.map((a) => assignWords(a)).filter(Boolean);
764
+ return { kind: 'set', says: said.join('; then ') };
765
+ }
766
+ let suffix = '';
767
+ let admin = false;
768
+ for (;;) {
769
+ const w = ws[0];
770
+ if (w === 'sudo' || w === 'doas') { admin = true; ws = ws.slice(1).filter((x, i) => !(i === 0 && /^-/.test(x))); continue; }
771
+ if (w === 'command' && ws[1] !== '-v' || w === 'builtin' || w === 'time' || w === 'exec' || w === 'nohup' || w === 'noglob') { if (w === 'nohup') suffix += ', even after logging out'; ws = ws.slice(1); continue; }
772
+ if (w === 'env' && ws.length > 1) { ws = ws.slice(1).filter((x) => !/^[A-Za-z_]\w*=/.test(x) && !/^-/.test(x)); continue; }
773
+ break;
774
+ }
775
+ if (!ws.length) return null;
776
+ const [name, ...args] = ws;
777
+ if (n.background) suffix += ', in the background';
778
+ if (admin) suffix += ' (as an administrator)';
779
+ if (n.assigns.length) suffix += ` (with ${n.assigns.map((a) => { const m = a.match(/^(\w+)=(.*)$/); return m ? `${varWords(m[1])} set to ${sayWord(m[2])}` : a; }).join(', ')})`;
780
+ const out = (s, extra = {}) => ({ kind: 'call', says: s + redirWords(n.redirs) + suffix, ...extra });
781
+ switch (name) {
782
+ case ':': case 'true': return null;
783
+ case 'break': return { kind: 'call', says: 'Stops repeating' };
784
+ case 'continue': return { kind: 'call', says: 'Skips to the next one' };
785
+ case 'setopt': case 'unsetopt': return { kind: 'set', says: `Turns ${name === 'setopt' ? 'on' : 'off'} the zsh option${args.length > 1 ? 's' : ''} ${listWords(args.map(sayWord))}` };
786
+ case 'command': if (args[0] === '-v') return { kind: 'check', says: `Checks whether ${sayWord(positional(args)[0] ?? '?')} is installed` }; break;
787
+ case 'false': return { kind: 'fail', says: 'Fails (the command false)', error: 'failure' };
788
+ case 'echo': case 'printf': case 'print': {
789
+ let a = args;
790
+ if (name === 'echo') while (/^-[neE]+$/.test(a[0] ?? '')) a = a.slice(1);
791
+ let got;
792
+ if (name === 'printf') {
793
+ let pa = a[0] === '--' ? a.slice(1) : a;
794
+ const into = pa[0] === '-v' ? pa[1] : null;
795
+ if (into) pa = pa.slice(2);
796
+ const [fmt, ...rest] = pa;
797
+ got = printfText(fmt, rest);
798
+ // Arguments that cannot be paired with the format: the code, not a guess.
799
+ if (!got) return { kind: 'other', says: '' };
800
+ if (into) return { kind: 'set', says: `Sets ${varWords(into)} to ${got.value ?? `the text "${got.text}"`}` };
801
+ } else got = messageOf(a);
802
+ const { text: msg, value } = got;
803
+ const file = n.redirs.find((r) => (r.op === '>' || r.op === '>>' || r.op === '>|') && !r.fd && !isDevNull(r.target) && r.target !== '/dev/stderr');
804
+ const what = value ?? `"${msg}"`;
805
+ if (toStderr(n.redirs)) return { kind: 'call', says: value ? `Writes ${value} as an error message${suffix}` : `Writes an error message: "${msg}"${suffix}`, stderr: msg };
806
+ if (file) return { kind: 'call', says: `${file.op === '>>' ? 'Adds' : 'Writes'} ${what} ${file.op === '>>' ? 'to the end of' : 'to'} ${sayWord(file.target)}${suffix}` };
807
+ if (n.redirs.some((r) => isDevNull(r.target) && !r.fd)) return null;
808
+ return { kind: 'call', says: value ? `Writes out ${value}${suffix}` : msg && msg !== '\\n' ? `Writes a message: "${msg}"${suffix}` : 'Writes an empty line' };
809
+ }
810
+ case 'exit': {
811
+ // A bare exit ends with the last command's exit code: success only right after a command that worked.
812
+ if (args[0] == null && ctx !== '&&') return { kind: 'return', says: ctx === '||' ? "Stops the script here, with the failed command's exit code" : "Stops the script here, with the last command's exit code" };
813
+ const code = args[0] ?? '0';
814
+ if (code === '0') return { kind: 'return', says: 'Stops the script here, finished without errors' };
815
+ if (/^\d+$/.test(code)) return { kind: 'fail', says: `Fails with exit code ${code}`, error: `exit code ${code}`, exitCode: code };
816
+ return { kind: 'return', says: code === '$?' || code === '"$?"' ? "Stops the script with the last command's exit code" : `Stops the script with the exit code in ${sayWord(code)}` };
817
+ }
818
+ case 'return': {
819
+ if (args[0] == null && ctx !== '&&') return { kind: 'return', says: ctx === '||' ? "Returns the failed command's exit code" : "Returns the last command's exit code" };
820
+ const code = args[0] ?? '0';
821
+ if (code === '0') return { kind: 'return', says: 'Returns success' };
822
+ if (/^\d+$/.test(code)) return { kind: 'return', says: `Returns failure (code ${code})`, failCode: code };
823
+ return { kind: 'return', says: code === '$?' || code === '"$?"' ? "Returns the last command's exit code" : `Returns the code in ${sayWord(code)}` };
824
+ }
825
+ case 'set': return { kind: 'set', says: setWords(args) };
826
+ case 'shopt': return { kind: 'set', says: `${args.includes('-u') ? 'Turns off' : 'Turns on'} the shell option ${positional(args).map(sayWord).join(', ')}` };
827
+ case 'trap': {
828
+ const [handler, ...sigs] = args;
829
+ if (!sigs.length) return out('Lists the traps');
830
+ const when = TRAP_WHEN(sigs);
831
+ if (handler === '-' ) return { kind: 'set', says: `Stops handling ${sigs.join(', ')}` };
832
+ const body = partsOf(handler ?? '').map((p) => p.lit ?? '').join('');
833
+ if (!body.trim()) return { kind: 'set', says: `Ignores ${sigs.join(', ')}` };
834
+ const nodes = parse(body);
835
+ if (nodes.length === 1 && nodes[0].type === 'simple' && KNOWN_FNS.has(nodes[0].words[0])) return { kind: 'call', says: `${when}, runs ${words(nodes[0].words[0])}`, callee: nodes[0].words[0] };
836
+ return { kind: 'call', says: `${when}, it runs these steps`, trap: nodes };
837
+ }
838
+ case 'export': case 'local': case 'declare': case 'typeset': case 'readonly': {
839
+ const flags = args.filter((a) => /^[-+][a-zA-Z]+$/.test(a)).join('');
840
+ const items = args.filter((a) => !/^[-+][a-zA-Z]+$/.test(a));
841
+ const exported = name === 'export' || /x/.test(flags);
842
+ const ro = name === 'readonly' || /r/.test(flags);
843
+ const said = items.map((a) => (/=/.test(a) ? assignWords(a, { exported, readonly: ro }) : exported ? `Shares ${varWords(a)} with the programs it runs` : /A/.test(flags) ? `Starts ${varWords(a)} as an empty table` : /a/.test(flags) ? `Starts ${varWords(a)} as an empty list` : `Starts with no ${varWords(a)} yet`)).filter(Boolean);
844
+ if (!said.length) return null;
845
+ return { kind: 'set', says: said.join('; then ').replace(/; then (\w)/g, (m, c) => `; then ${c.toLowerCase()}`) };
846
+ }
847
+ case 'unset': return { kind: 'set', says: `Forgets ${listWords(positional(args).map((a) => (/^[A-Za-z_]\w*$/.test(a) ? varWords(a) : sayWord(a))))}` };
848
+ case 'source': case '.': return out(`Loads the commands and settings in ${sayWord(args[0] ?? '?')}`);
849
+ case 'shift': return { kind: 'set', says: args[0] && args[0] !== '1' ? `Moves past the next ${sayWord(args[0])} inputs` : 'Moves on to the next input' };
850
+ case 'read': {
851
+ const prompt = args.includes('-p') ? args[args.indexOf('-p') + 1] : null;
852
+ const names = positional(args, ['-p', '-t', '-n', '-d', '-u', '-a', '-N']).filter((x) => /^\w+$/.test(x));
853
+ const list = opt(args, ['-a']) ?? (args.some((x) => /^-[a-zA-Z]*a$/.test(x)) ? names.pop() : null);
854
+ const into = list ? `the list ${varWords(list)}` : names.length ? listWords(names.map(varWords)) : 'a line';
855
+ const given = n.redirs.find((r) => r.op === '<<<' || r.op === '<');
856
+ const from = given ? (given.op === '<' ? `the file ${sayWord(given.target)}` : sayWord(given.target)) : 'what is typed in';
857
+ if (prompt) return out(`Asks ${sayWord(prompt)} and keeps the answer as ${into}`);
858
+ return { kind: 'call', says: `Reads ${into} from ${from}${suffix}` };
859
+ }
860
+ case 'eval': return out(`Runs the text ${listWords(args.map(sayWord))} as a command`);
861
+ case 'getopts': return { kind: 'set', says: `Reads the next option into ${varWords(args[1] ?? 'opt')}` };
862
+ case 'alias': return { kind: 'set', says: `Makes the shortcut ${sayWord((args[0] ?? '').split('=')[0])}` };
863
+ case 'cat': case 'tee': {
864
+ const doc = n.redirs.find((r) => r.op === '<<' || r.op === '<<-');
865
+ if (!doc || positional(args).length && name === 'cat') break;
866
+ const lines = Math.max(0, (doc.body ?? '').split('\n').length - 2);
867
+ const file = name === 'tee' ? positional(args)[0] : n.redirs.find((r) => (r.op === '>' || r.op === '>>') && !r.fd && !isDevNull(r.target))?.target;
868
+ const appending = name === 'tee' ? args.includes('-a') : n.redirs.some((r) => r.op === '>>');
869
+ return { kind: 'call', says: file ? `${appending ? 'Adds' : 'Writes'} the text written below (${lines} line${lines === 1 ? '' : 's'}) ${appending ? 'to the end of' : 'to'} ${sayWord(file)}${suffix}` : `Writes out the text written below (${lines} line${lines === 1 ? '' : 's'})${suffix}` };
870
+ }
871
+ case 'cd': case 'pushd': case 'popd': break;
872
+ case 'wait': break;
873
+ case '[': case 'test': case '[[': {
874
+ const inner = name === 'test' ? args : args.slice(0, -1);
875
+ const t = testWords(inner, false, name === '[[');
876
+ return { kind: 'check', says: `Checks whether ${t ?? 'the test passes'}` };
877
+ }
878
+ default: break;
879
+ }
880
+ if (DIES.has(name)) {
881
+ const msg = message(args);
882
+ return { kind: 'fail', says: `Fails with exit code ${DIES.get(name)}${msg ? `: "${msg}"` : ''}`, error: `exit code ${DIES.get(name)}`, ...(msg ? { message: msg } : {}), callee: name };
883
+ }
884
+ if (KNOWN_FNS.has(name)) return out(`Runs ${words(name)}${args.length ? ` with ${listWords(args.slice(0, 4).map(sayWord))}${args.length > 4 ? ', …' : ''}` : ''}`, { callee: name });
885
+ const known = sayCommand(name, args, sayWord);
886
+ if (known) return out(known, { callee: name });
887
+ if (/^"?\$/.test(name)) return out(`Runs the command in ${sayWord(name)}`, { callee: name });
888
+ if (scriptPath(name)) return out(`Runs the script ${sayWord(name)}`, { callee: name });
889
+ return out(`Runs ${name}${args[0] && /^[a-z][\w-]*$/.test(args[0]) ? ` ${args[0]}` : ''}`, { callee: name });
890
+ }
891
+
892
+ /** Any node as one short sentence (used inside questions and "the output of …"). */
893
+ function sayNode(n) {
894
+ if (n.type === 'simple') { const s = simpleSays(n); return s && s.kind !== 'other' ? s.says : null; }
895
+ if (n.type === 'pipeline') {
896
+ const said = n.cmds.map((c) => sayNode(c)).filter(Boolean);
897
+ if (n.cmds.length === 2 && n.cmds[1].type === 'simple' && /^(?:ba|z)?sh$/.test(n.cmds[1].words[0]) && n.cmds[0].type === 'simple' && /^(curl|wget)$/.test(n.cmds[0].words[0])) {
898
+ const url = n.cmds[0].words.slice(1).find((a) => /:\/\/|\$/.test(a));
899
+ return `Downloads ${sayWord(url ?? '?')} and runs it as a script`;
900
+ }
901
+ return said.length ? [said[0], ...said.slice(1).map((s) => `then ${s.charAt(0).toLowerCase()}${s.slice(1)}`)].join(', ') : null;
902
+ }
903
+ if (n.type === 'arith') return arithSays(n.expr);
904
+ if (n.type === 'andor') return sayNode(n.first);
905
+ if (n.type === 'group' || n.type === 'subshell') return n.body[0] ? sayNode(n.body[0]) : null;
906
+ if (n.type === 'if') return 'Checks a condition';
907
+ if (n.type === 'for' || n.type === 'while') return 'Repeats some steps';
908
+ return null;
909
+ }
910
+
911
+ // ── Steps ─────────────────────────────────────────────────────────────────────────────────────────────
912
+
913
+ const CODE_MAX = 160;
914
+ function makeStepper(src) {
915
+ const lineAt = lineFinder(src);
916
+ const codeOf = (n) => { const t = src.slice(n.at, n.end).replace(/\s+/g, ' ').trim(); return t.length > CODE_MAX ? `${t.slice(0, CODE_MAX - 1)}…` : t; };
917
+ const headOf = (n) => { const t = src.slice(n.at, n.end).split('\n')[0].trim(); return t.length > CODE_MAX ? `${t.slice(0, CODE_MAX - 1)}…` : t; };
918
+ const span = (n) => ({ startLine: lineAt(n.at), endLine: lineAt(Math.max(n.at, n.end - 1)) });
919
+ const base = (n, code = codeOf(n)) => ({ code, line: lineAt(n.at), span: span(n) });
920
+
921
+ function steps(nodes) {
922
+ const out = [];
923
+ for (let k = 0; k < nodes.length; k++) {
924
+ const n = nodes[k];
925
+ const got = nodeSteps(n);
926
+ // An error message written right before an exit or a failing return is that Stop's message.
927
+ const next = nodes[k + 1];
928
+ if (got.length === 1 && got[0].stderr != null && next && next.type === 'simple') {
929
+ const ex = simpleSays(next);
930
+ if (ex && (ex.kind === 'fail' || ex.failCode) && !ex.message) {
931
+ const code = ex.exitCode ?? ex.failCode;
932
+ const what = ex.exitCode ? `exit code ${code}` : `return code ${code}`;
933
+ out.push({ kind: 'fail', says: `Fails with ${what}: "${got[0].stderr}"`, error: what, message: got[0].stderr, code: `${codeOf(n)}; ${codeOf(next)}`, line: lineAt(n.at), span: { startLine: lineAt(n.at), endLine: lineAt(next.end - 1) } });
934
+ k++;
935
+ continue;
936
+ }
937
+ }
938
+ for (const s of got) { delete s.stderr; delete s.exitCode; delete s.failCode; out.push(s); }
939
+ }
940
+ return out;
941
+ }
942
+
943
+ function branch(says, n, children, extra = {}) {
944
+ return { kind: 'branch', says, ...base(n, headOf(n)), ...(children.length ? { children } : {}), ...extra };
945
+ }
946
+
947
+ function nodeSteps(n, ctx = null) {
948
+ switch (n.type) {
949
+ case 'simple': {
950
+ const s = simpleSays(n, ctx);
951
+ if (!s) return [];
952
+ const st = { ...s, ...base(n) };
953
+ if (s.kind === 'other') st.says = codeOf(n);
954
+ if (s.trap) { delete st.trap; const kids = steps(s.trap).map((c) => ({ ...c, line: st.line, span: st.span })); if (kids.length) { st.children = kids; st.nested = true; } }
955
+ return [st];
956
+ }
957
+ case 'function': return [{ kind: 'set', says: `Defines a helper, ${words(n.name)}`, ...base(n, headOf(n)) }];
958
+ case 'arith': { const says = arithSays(n.expr); return [says ? { kind: 'set', says, ...base(n) } : { kind: 'other', says: codeOf(n), ...base(n) }]; }
959
+ case 'group': return steps(n.body);
960
+ case 'subshell': { const kids = steps(n.body); return [{ kind: 'call', says: 'Runs these steps in a separate shell (folder and setting changes stay inside it)', ...base(n, headOf(n)), ...(kids.length ? { children: kids } : {}) }]; }
961
+ case 'pipeline': return pipelineSteps(n);
962
+ case 'andor': return andOrSteps(n);
963
+ case 'if': {
964
+ let first = null, tail = null;
965
+ for (const c of n.clauses) {
966
+ const b = { kind: 'branch', says: `If ${condWords(c.cond)}`, code: src.slice(c.at, src.indexOf('\n', c.at) < 0 ? undefined : src.indexOf('\n', c.at)).trim().slice(0, CODE_MAX), line: lineAt(c.at), span: first ? { startLine: lineAt(c.at), endLine: lineAt(n.end - 1) } : span(n) };
967
+ const kids = steps(c.body);
968
+ if (kids.length) b.children = kids;
969
+ if (!first) first = b; else { b.elseIf = true; tail.otherwise = [b]; }
970
+ tail = b;
971
+ }
972
+ if (n.otherwise) { const kids = steps(n.otherwise); tail.otherwise = kids; tail.otherwiseLine = lineAt(n.elseAt); }
973
+ return [first];
974
+ }
975
+ case 'for': {
976
+ const kids = steps(n.body);
977
+ let says;
978
+ if (n.cstyle != null) {
979
+ const [init, cond] = n.cstyle.split(';').map((x) => x.trim());
980
+ const im = init.match(/^(\w+)\s*=\s*(.+)$/);
981
+ const from = im && arithWords(im[2]), wh = cond ? arithWords(cond) : '';
982
+ says = im && from && wh != null ? `Counts ${varWords(im[1])} from ${from}${wh ? ` while ${wh}` : ''}` : `Repeats: ${asCode(`for ((${n.cstyle}))`)}`;
983
+ } else {
984
+ const items = n.items;
985
+ let what;
986
+ if (!items || (items.length === 1 && /^"?\$[@*]"?$/.test(items[0]))) what = 'the inputs';
987
+ else if (items.length === 1) { const p = partsOf(items[0]); what = isGlob(items[0]) ? `the files matching ${items[0].replace(/^"|"$/g, '')}` : p.length === 1 && p[0].cmd != null ? outputWords(p[0].cmd) : sayWord(items[0]); }
988
+ else what = listWords(items.slice(0, 6).map(sayWord)) + (items.length > 6 ? ', …' : '');
989
+ says = n.select ? `Asks the person to pick ${varWords(n.name)} from ${what}` : `For each ${varWords(n.name)} in ${what}`;
990
+ }
991
+ return [{ kind: 'loop', says, ...base(n, headOf(n)), ...(kids.length ? { children: kids } : {}) }];
992
+ }
993
+ case 'while': {
994
+ const kids = steps(n.body);
995
+ const last = n.cond[n.cond.length - 1];
996
+ let says;
997
+ if (last?.type === 'simple' && last.words[0] === 'read') {
998
+ const names = positional(last.words.slice(1), ['-p', '-t', '-n', '-d', '-u', '-a']).filter((x) => /^\w+$/.test(x));
999
+ const from = n.redirs.find((r) => r.op === '<');
1000
+ says = `For each line${names.length > 1 ? ` (${listWords(names.map(varWords))})` : names[0] && names[0] !== 'line' ? ` (as ${varWords(names[0])})` : ''}${from ? ` in ${sayWord(from.target)}` : n.redirs.some((r) => r.op === '<<<') ? ` in ${sayWord(n.redirs.find((r) => r.op === '<<<').target)}` : ''}`;
1001
+ } else if (last?.type === 'simple' && last.words[0] === 'getopts') {
1002
+ const letters = (partsOf(last.words[1] ?? '')[0]?.lit ?? '').replace(/[:]/g, '').split('').filter(Boolean);
1003
+ says = `For each option given${letters.length ? ` (${letters.map((l) => `-${l}`).join(', ')})` : ''}`;
1004
+ } else if (last?.type === 'simple' && /^(true|:)$/.test(last.words[0])) says = n.until ? 'Never repeats' : 'Repeats until something stops it';
1005
+ else says = `Repeats ${n.until ? 'until' : 'while'} ${condWords(n.cond)}`;
1006
+ return [{ kind: 'loop', says, ...base(n, headOf(n)), ...(kids.length ? { children: kids } : {}) }];
1007
+ }
1008
+ case 'case': {
1009
+ const arms = n.arms.map((a) => {
1010
+ const pats = a.patterns.filter((p) => p !== '(');
1011
+ let says;
1012
+ if (pats.length === 1 && pats[0] === '*') says = 'Otherwise';
1013
+ else if (pats.every((p) => !isGlob(p))) { const ws = pats.map(sayWord); says = `When it is ${ws.length > 1 ? `${ws.slice(0, -1).join(', ')} or ${ws.at(-1)}` : ws[0]}`; }
1014
+ else says = `When it matches ${pats.map((p) => asCode(p)).join(' or ')}`;
1015
+ const kids = steps(a.body);
1016
+ return { kind: 'check', says, caseLabel: true, code: src.slice(a.at, src.indexOf(')', a.at) + 1).trim().slice(0, 90), line: lineAt(a.at), span: { startLine: lineAt(a.at), endLine: lineAt(Math.max(a.at, a.end - 1)) }, ...(kids.length ? { children: kids } : {}) };
1017
+ });
1018
+ return [{ kind: 'branch', says: `Chooses by ${sayWord(n.word)}`, ...base(n, headOf(n)), ...(arms.length ? { children: arms } : {}) }];
1019
+ }
1020
+ default: return [];
1021
+ }
1022
+ }
1023
+
1024
+ function pipelineSteps(n) {
1025
+ const lastCmd = n.cmds[n.cmds.length - 1];
1026
+ if (lastCmd.type === 'while' && n.cmds.length > 1) {
1027
+ const [loop] = nodeSteps(lastCmd);
1028
+ const from = sayNode({ ...n, cmds: n.cmds.slice(0, -1), negate: false });
1029
+ loop.says = loop.says.replace(/^For each line.*$/, (m) => `${m} from ${from ? gerund(from) : 'the command'}`);
1030
+ return [{ ...loop, ...base(n, headOf(n)) }];
1031
+ }
1032
+ const s = sayNode(n);
1033
+ if (n.negate) return [{ kind: 'check', says: `Checks that ${gerund(s ?? 'Runs the commands')} fails`, ...base(n) }];
1034
+ return s ? [{ kind: 'call', says: s, ...base(n) }] : [{ kind: 'other', says: codeOf(n), ...base(n) }];
1035
+ }
1036
+
1037
+ /** The last command of an && / || list: a bare return or exit there ends with that list's result. */
1038
+ function lastSteps(n, op) { return n.type === 'simple' ? nodeSteps(n, op) : steps([n]); }
1039
+
1040
+ function andOrSteps(n) {
1041
+ const chain = [n.first, ...n.rest.map((r) => r.node)];
1042
+ const ops = n.rest.map((r) => r.op);
1043
+ const isTest = (x) => x.type === 'arith' || (x.type === 'simple' && /^(\[\[?|test)$/.test(x.words[0] ?? ''));
1044
+ // `test && a || b` is the shell's if/else, but only when `a` cannot fail (b runs when a fails, too).
1045
+ const cannotFail = (x) => x.type === 'simple' && (!x.words.length || /^(?:echo|printf|:|true|return|exit|break|continue|unset|local|export)$/.test(x.words[0]));
1046
+ if (ops.length === 2 && ops[0] === '&&' && ops[1] === '||' && isTest(chain[0]) && cannotFail(chain[1])) {
1047
+ const kids = steps([chain[1]]), other = steps([chain[2]]);
1048
+ return [branch(`If ${nodeCond(chain[0], false)}`, n, kids, { otherwise: other })];
1049
+ }
1050
+ // Mixed: the shell groups from the left, so `a && b || c` runs c when a or b failed. One change of operator at
1051
+ // the end is said as a condition on the whole group; anything more mixed is shown as code.
1052
+ if (new Set(ops).size > 1) {
1053
+ const head = ops.slice(0, -1);
1054
+ if (new Set(head).size > 1) return [{ kind: 'other', says: codeOf(n), ...base(n) }];
1055
+ const groupOp = head[0], lastOp = ops[ops.length - 1];
1056
+ const group = chain.slice(0, -1);
1057
+ // The group works when all of an && group work, or any of an || group; it fails otherwise.
1058
+ const wantFail = lastOp === '||';
1059
+ const joinWord = (groupOp === '&&') !== wantFail ? ' and ' : ' or ';
1060
+ const cond = group.map((x) => nodeCond(x, wantFail)).join(joinWord);
1061
+ const kids = lastSteps(chain[chain.length - 1], lastOp);
1062
+ return [{ kind: 'branch', says: `If ${cond}`, ...base(n), ...(kids.length ? { children: kids } : {}) }];
1063
+ }
1064
+ // a && b && c: each runs only if the one before worked; a || b: b runs only if a failed.
1065
+ const build = (i) => {
1066
+ if (i === chain.length - 1) return lastSteps(chain[i], ops[i - 1]);
1067
+ const op = ops[i];
1068
+ const head = chain[i];
1069
+ const cond = nodeCond(head, op === '||');
1070
+ const kids = build(i + 1);
1071
+ const b = { kind: 'branch', says: `If ${cond}`, ...base(n, i === 0 ? codeOf(n) : codeOf(head)), ...(kids.length ? { children: kids } : {}) };
1072
+ if (isTest(head) || head.type === 'pipeline' && head.negate) return [b];
1073
+ // The command itself is a step too, when it does something besides answering yes or no.
1074
+ const own = steps([head]);
1075
+ const question = /\b(?:works|fails)$/.test(cond) && own.length === 1 && own[0].kind === 'call';
1076
+ if (question || own.length === 0) return [b];
1077
+ if (head.type === 'simple' && ((head.words[0] === 'command' && head.words[1] === '-v') || /^(which|type|hash)$/.test(head.words[0]) || (/^e?grep$/.test(head.words[0]) && head.words.some((w) => /^-[a-zA-Z]*q/.test(w))))) return [b];
1078
+ return [...own, { ...b, says: `If that ${op === '&&' ? 'worked' : 'failed'}` }];
1079
+ };
1080
+ return build(0);
1081
+ }
1082
+ return { steps, lineAt, codeOf, headOf };
1083
+ }
1084
+
1085
+ // ── Reading a file ────────────────────────────────────────────────────────────────────────────────────
1086
+
1087
+ /** The comment lines right above line `line` (1-based), as the author's note; null when there are none. */
1088
+ function docAbove(lines, line) {
1089
+ const run = [];
1090
+ for (let k = line - 2; k >= 0; k--) {
1091
+ const t = lines[k].trim();
1092
+ if (!t.startsWith('#') || t.startsWith('#!')) break;
1093
+ run.unshift(t.replace(/^#+\s?/, '').trim());
1094
+ }
1095
+ return cleanDoc(run);
1096
+ }
1097
+ function cleanDoc(run) {
1098
+ const para = [];
1099
+ for (const t of run) {
1100
+ if (/^[-=#*~_ ]*$/.test(t)) { if (para.length) break; continue; }
1101
+ if (/^(usage|example|examples|arguments|args|options|returns?|outputs?|globals|params?)\s*:/i.test(t)) break;
1102
+ para.push(t);
1103
+ }
1104
+ const s = para.join(' ').replace(/\s+/g, ' ').trim();
1105
+ return s ? (s.length > 300 ? `${s.slice(0, 299)}…` : s) : null;
1106
+ }
1107
+ /** The comment block at the top of the file, after the shebang: what the script is for. */
1108
+ function headerDoc(lines) {
1109
+ const run = [];
1110
+ let k = 0;
1111
+ if (/^#!/.test(lines[0] ?? '')) k = 1;
1112
+ while (k < lines.length && !lines[k].trim()) k++;
1113
+ for (; k < lines.length && /^\s*#/.test(lines[k]); k++) {
1114
+ const t = lines[k].trim();
1115
+ if (/^#\s*(shellcheck|-\*-|vim:)/.test(t)) continue;
1116
+ run.push(t.replace(/^#+\s?/, '').trim());
1117
+ }
1118
+ return cleanDoc(run);
1119
+ }
1120
+
1121
+ /** The text with every single-quoted part (outside double quotes) blanked: what the shell itself expands. */
1122
+ function withoutSingleQuoted(t, dq = false) {
1123
+ let out = '';
1124
+ for (let i = 0; i < t.length; i++) {
1125
+ const c = t[i];
1126
+ if (c === '\\') { out += t.slice(i, i + 2); i++; continue; }
1127
+ if (c === '"') { dq = !dq; out += c; continue; }
1128
+ if (c === "'" && !dq) { const e = t.indexOf("'", i + 1); if (e < 0) break; out += ' '; i = e; continue; }
1129
+ // Inside $( … ) quoting starts over.
1130
+ if (c === '$' && t[i + 1] === '(') { const e = skipBalanced(t, i + 1); out += `$(${withoutSingleQuoted(t.slice(i + 2, e - 1))})`; i = e - 1; continue; }
1131
+ out += c;
1132
+ }
1133
+ return out;
1134
+ }
1135
+ /** Inputs a function (or script) takes, from `local name="$1"` and the positional inputs it uses. */
1136
+ function inputsOf(nodes, src) {
1137
+ const named = [];
1138
+ let max = 0;
1139
+ const visit = (list) => {
1140
+ for (const n of list || []) {
1141
+ if (n.type === 'function') continue;
1142
+ if (n.type === 'simple') {
1143
+ const items = /^(local|declare|typeset|readonly|export)$/.test(n.words[0] ?? '') ? n.words.slice(1) : n.assigns;
1144
+ for (const a of items) { const m = a.match(/^([A-Za-z_]\w*)="?\$\{?([1-9])(?:[:?=-][^}$]*)?\}?"?$/); if (m && !named[m[2]]) named[m[2]] = m[1]; }
1145
+ }
1146
+ for (const k of ['body', 'otherwise', 'cond', 'cmds']) if (Array.isArray(n[k])) visit(n[k]);
1147
+ if (n.first) visit([n.first, ...n.rest.map((r) => r.node)]);
1148
+ if (n.clauses) for (const c of n.clauses) { visit(c.cond); visit(c.body); }
1149
+ if (n.arms) for (const a of n.arms) visit(a.body);
1150
+ // `$2` inside single quotes is another program's (awk '{print $2}'), not this function's input.
1151
+ const text = withoutSingleQuoted(src.slice(n.at, n.end));
1152
+ for (const m of text.matchAll(/\$\{?([1-9])\b/g)) if (n.type !== 'function') max = Math.max(max, Number(m[1]));
1153
+ }
1154
+ };
1155
+ visit(nodes);
1156
+ const out = [];
1157
+ for (let i = 1; i <= Math.max(max, named.length - 1); i++) out.push({ name: named[i] ?? `input_${i}`, type: null });
1158
+ return out;
1159
+ }
1160
+
1161
+ /**
1162
+ * Read a shell script: each function, and the script's own top-level code as one item named after the file, in the
1163
+ * shape read.mjs turns into reading items.
1164
+ */
1165
+ export function shellReading(src, file = '') {
1166
+ const nodes = parse(src);
1167
+ const lines = src.split('\n');
1168
+ const fns = [];
1169
+ const all = [];
1170
+ const collect = (list) => {
1171
+ for (const n of list || []) {
1172
+ if (n.type === 'function') { all.push(n); collect(n.body); continue; }
1173
+ for (const k of ['body', 'otherwise', 'cond', 'cmds']) if (Array.isArray(n[k])) collect(n[k]);
1174
+ if (n.first) collect([n.first, ...n.rest.map((r) => r.node)]);
1175
+ if (n.clauses) for (const c of n.clauses) collect(c.body);
1176
+ if (n.arms) for (const a of n.arms) collect(a.body);
1177
+ }
1178
+ };
1179
+ collect(nodes);
1180
+ KNOWN_FNS = new Set(all.map((f) => f.name));
1181
+ DIES = new Map();
1182
+ // Helpers like die() { echo "$*" >&2; exit 1; }: a call to one is a Stop.
1183
+ for (const f of all) {
1184
+ const last = f.body[f.body.length - 1];
1185
+ if (last?.type === 'simple' && last.words[0] === 'exit' && /^[1-9]\d*$/.test(last.words[1] ?? '')) DIES.set(f.name, last.words[1]);
1186
+ }
1187
+ const { steps, lineAt } = makeStepper(src);
1188
+ const errors = new Map();
1189
+ const noteErrors = (list) => { for (const s of list || []) { if (s.kind === 'fail' && s.message && !errors.has(s.message)) errors.set(s.message, s.line); noteErrors(s.children); noteErrors(s.otherwise); } };
1190
+ for (const f of all) {
1191
+ const line = lineAt(f.at);
1192
+ const st = steps(f.body);
1193
+ // `name() { :; }` (a stub, or a test's stand-in) does nothing, and says so.
1194
+ if (!st.length) st.push({ kind: 'return', says: 'Does nothing', code: src.slice(f.at, f.end).replace(/\s+/g, ' ').trim().slice(0, 160), line, span: { startLine: line, endLine: lineAt(f.end - 1) } });
1195
+ noteErrors(st);
1196
+ const first = f.body[0], lastN = f.body[f.body.length - 1];
1197
+ fns.push({ name: f.name, line, params: inputsOf(f.body, src), doc: docAbove(lines, line), steps: st, body: first ? [lineAt(first.at), lineAt(lastN.end - 1)] : null });
1198
+ }
1199
+ const top = nodes.filter((n) => n.type !== 'function');
1200
+ if (top.length) {
1201
+ const st = steps(top);
1202
+ noteErrors(st);
1203
+ const name = file ? String(file).split(/[\\/]/).pop() : 'script';
1204
+ fns.push({ name, line: lineAt(top[0].at), params: inputsOf(top, src), doc: headerDoc(lines), steps: st, body: [lineAt(top[0].at), lineAt(top[top.length - 1].end - 1)], topLevel: true, headline: `Runs ${name}, from top to bottom.` });
1205
+ }
1206
+ fns.sort((a, b) => a.line - b.line);
1207
+ KNOWN_FNS = new Set(); DIES = new Map();
1208
+ return { fns, errors: [...errors].map(([name, line]) => ({ name, line })), tests: [] };
1209
+ }
1210
+
1211
+ export const SHELL_TRIVIA = /^\s*(?:fi|done|esac|then|do|else|;;|\{|\}|\)|\(|[;&|]+)\s*(?:#.*)?$/;
1212
+ export { cap };