@skillstech/thunderlang 0.5.11 → 0.5.12

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 +437 -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
@@ -0,0 +1,1361 @@
1
+ // PowerShell in Thunder. A linear tokenizer (strings with $var and $(…), here-strings, <# #> comments, types and
2
+ // attributes, -operators and -Parameters) and a statement reader for functions with param() blocks, if/elseif/else,
3
+ // foreach, ForEach-Object, for, while, do/until, switch (cases), try/catch/finally, trap, throw, return; cmdlets read
4
+ // by Verb-Noun ("Get-AzResourceGroup" -> "Gets the Azure resource groups"), well-known native tools through the
5
+ // shared phrasebook, comparison operators in words, classes (properties with defaults, methods) and enums as Things
6
+ // and Choices, comment-based help (.SYNOPSIS) as the author's note, and Pode routes as actions. Deterministic,
7
+ // browser-safe; what it cannot say keeps its code.
8
+ import { sayCommand, gerund, words, cap, listWords } from './commands.mjs';
9
+ import { accountsFor, asCodeWords } from './faithful.mjs';
10
+
11
+ function lineFinder(src) {
12
+ const starts = [0];
13
+ for (let i = src.indexOf('\n'); i >= 0; i = src.indexOf('\n', i + 1)) starts.push(i + 1);
14
+ 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; };
15
+ }
16
+
17
+ // ── Tokens ────────────────────────────────────────────────────────────────────────────────────────────
18
+
19
+ const OPENERS = { '{': '}', '(': ')', '$(': ')', '@(': ')', '@{': '}', '[': ']' };
20
+ const WORD_OPS = /^-[ci]?(?:eq|ne|gt|ge|lt|le|like|notlike|match|notmatch|contains|notcontains|in|notin|replace|split|join|and|or|xor|not|is|isnot|as|band|bor|bxor|bnot|f|shl|shr)$/i;
21
+ const PUNCT = ['::', '++', '--', '+=', '-=', '*=', '/=', '%=', '2>&1', '*>', '2>>', '2>', '>>', '..', '&&', '||', '{', '}', '(', ')', ';', ',', '|', '=', '.', '+', '-', '*', '/', '%', '!', '&', '>', '<', ']', '?'];
22
+
23
+ function skipString(s, i) {
24
+ const q = s[i];
25
+ for (let j = i + 1; j < s.length; j++) {
26
+ const c = s[j];
27
+ if (q === "'") { if (c === "'") { if (s[j + 1] === "'") { j++; continue; } return j + 1; } continue; }
28
+ if (c === '`') { j++; continue; }
29
+ if (c === '"') { if (s[j + 1] === '"') { j++; continue; } return j + 1; }
30
+ if (c === '$' && s[j + 1] === '(') { j = skipParen(s, j + 1) - 1; continue; }
31
+ }
32
+ return s.length;
33
+ }
34
+ function skipParen(s, i) {
35
+ let d = 0;
36
+ for (let j = i; j < s.length; j++) {
37
+ const c = s[j];
38
+ if (c === "'" || c === '"') { j = skipString(s, j) - 1; continue; }
39
+ if (c === '(') d++;
40
+ else if (c === ')' && --d === 0) return j + 1;
41
+ }
42
+ return s.length;
43
+ }
44
+
45
+ function tokenize(src) {
46
+ const toks = [];
47
+ let i = 0;
48
+ const n = src.length;
49
+ const push = (t, text, at, end, extra) => toks.push({ t, text, at, end, ...extra });
50
+ while (i < n) {
51
+ const c = src[i];
52
+ if (c === ' ' || c === '\t' || c === '\r' || c === '\f' || c === '') { i++; continue; }
53
+ if (c === '`' && (src[i + 1] === '\n' || src[i + 1] === '\r')) { i += src[i + 1] === '\r' ? 3 : 2; continue; }
54
+ if (c === '\n') { push('nl', '\n', i, i + 1); i++; continue; }
55
+ if (c === '<' && src[i + 1] === '#') { const e = src.indexOf('#>', i + 2); const end = e < 0 ? n : e + 2; push('comment', src.slice(i, end), i, end, { block: true }); i = end; continue; }
56
+ if (c === '#') { let e = src.indexOf('\n', i); if (e < 0) e = n; push('comment', src.slice(i, e), i, e); i = e; continue; }
57
+ if (c === '@' && (src[i + 1] === '"' || src[i + 1] === "'") && /^\s*\r?\n/.test(src.slice(i + 2, i + 40))) {
58
+ const q = src[i + 1];
59
+ const re = new RegExp(`\\n[ \\t]*${q}@`, 'g');
60
+ re.lastIndex = i + 2;
61
+ const m = re.exec(src);
62
+ const end = m ? m.index + m[0].length : n;
63
+ push('str', src.slice(i, end), i, end, { quote: q, body: src.slice(src.indexOf('\n', i) + 1, m ? m.index : n), here: true });
64
+ i = end;
65
+ continue;
66
+ }
67
+ if (c === "'" || c === '"') { const e = skipString(src, i); push('str', src.slice(i, e), i, e, { quote: c, body: src.slice(i + 1, e - 1) }); i = e; continue; }
68
+ if (c === '$' && src[i + 1] === '(') { push('punc', '$(', i, i + 2); i += 2; continue; }
69
+ if (c === '@' && (src[i + 1] === '(' || src[i + 1] === '{')) { push('punc', `@${src[i + 1]}`, i, i + 2); i += 2; continue; }
70
+ if (c === '$') {
71
+ if (src[i + 1] === '{') { const e = src.indexOf('}', i); const end = e < 0 ? n : e + 1; push('var', src.slice(i, end), i, end, { name: src.slice(i + 2, end - 1) }); i = end; continue; }
72
+ const m = src.slice(i + 1, i + 200).match(/^(?:[A-Za-z_][\w]*:)?[A-Za-z_\d][\w]*|^[_?^$]/);
73
+ if (m) { push('var', `$${m[0]}`, i, i + 1 + m[0].length, { name: m[0] }); i += 1 + m[0].length; continue; }
74
+ }
75
+ if (c === '@' && /[A-Za-z_]/.test(src[i + 1] || '')) { const m = src.slice(i + 1).match(/^\w+/); push('var', `@${m[0]}`, i, i + 1 + m[0].length, { name: m[0], splat: true }); i += 1 + m[0].length; continue; }
76
+ if (c === '[') {
77
+ const prev = toks[toks.length - 1];
78
+ const glued = prev && prev.end === i && (prev.t === 'var' || prev.text === ')' || prev.text === ']' || prev.t === 'str' || prev.t === 'word');
79
+ if (!glued) {
80
+ let d = 0, j = i;
81
+ for (; j < n; j++) {
82
+ const ch = src[j];
83
+ if (ch === "'" || ch === '"') { j = skipString(src, j) - 1; continue; }
84
+ if (ch === '[' || ch === '(') d++;
85
+ else if ((ch === ']' || ch === ')') && --d === 0 && ch === ']') break;
86
+ if (ch === '\n' && d <= 1 && !/\(/.test(src.slice(i, j))) break;
87
+ }
88
+ const text = src.slice(i, j + 1);
89
+ if (src[j] === ']' && /^\[\s*[A-Za-z_][\w.`]*(?:\[[^\]]*\])?\s*(?:\([\s\S]*\))?\s*\]$/.test(text)) {
90
+ push(/\(/.test(text) ? 'attr' : 'type', text, i, j + 1, { name: /\(/.test(text) ? text.match(/^\[\s*([\w.`]+)/)[1] : text.slice(1, -1).trim() });
91
+ i = j + 1;
92
+ continue;
93
+ }
94
+ }
95
+ push('punc', '[', i, i + 1);
96
+ i++;
97
+ continue;
98
+ }
99
+ if (c === '-' && /[A-Za-z]/.test(src[i + 1] || '')) {
100
+ const m = src.slice(i).match(/^-[A-Za-z][\w-]*:?/);
101
+ const text = m[0];
102
+ push(WORD_OPS.test(text) ? 'op' : 'param', text, i, i + text.length);
103
+ i += text.length;
104
+ continue;
105
+ }
106
+ // Redirections: 2>$null, 2>&1, *>>log.txt.
107
+ if (/[1-6*]/.test(c) && src[i + 1] === '>' && /\s/.test(src[i - 1] ?? ' ')) {
108
+ const m = src.slice(i).match(/^[1-6*]>(?:&[12]|>)?/);
109
+ push('punc', m[0], i, i + m[0].length);
110
+ i += m[0].length;
111
+ continue;
112
+ }
113
+ if (/\d/.test(c) || (c === '.' && /\d/.test(src[i + 1] || ''))) {
114
+ const m = src.slice(i).match(/^(?:0x[\da-fA-F]+|\d*\.?\d+(?:[eE][+-]?\d+)?)(?:KB|MB|GB|TB|PB|[lLdD])?(?![\w.-])/i);
115
+ if (m) { push('num', m[0], i, i + m[0].length); i += m[0].length; continue; }
116
+ }
117
+ const prevT = toks[toks.length - 1];
118
+ if (prevT && prevT.end === i && prevT.t === 'punc' && (prevT.text === '.' || prevT.text === '::') && /[A-Za-z_]/.test(c)) {
119
+ const m = src.slice(i).match(/^[A-Za-z_]\w*/);
120
+ push('word', m[0], i, i + m[0].length);
121
+ i += m[0].length;
122
+ continue;
123
+ }
124
+ const path = (c === '*' && /\s/.test(src[i - 1] || ' ') && /[\w.*\\\/]/.test(src[i + 1] || '')) || (c === '.' && /[\\/]/.test(src[i + 1] || '')) || src.startsWith('..\\', i) || src.startsWith('../', i) || (c === '-' && src[i + 1] === '-' && /[A-Za-z]/.test(src[i + 2] || ''));
125
+ const p = path ? null : PUNCT.find((x) => src.startsWith(x, i));
126
+ if (p) { push('punc', p, i, i + p.length); i += p.length; continue; }
127
+ // A bareword: a command name, a path, a native argument.
128
+ const dashed = c === '-';
129
+ let j = i;
130
+ while (j < n && !/[\s{}();,|"'`]/.test(src[j])) {
131
+ if (src[j] === '=' && !dashed) break;
132
+ if (src[j] === '[' && j > i && !/[\\/:*]/.test(src.slice(i, j))) break;
133
+ if (src[j] === ']') break;
134
+ j++;
135
+ }
136
+ if (j === i) j = i + 1;
137
+ push('word', src.slice(i, j), i, j);
138
+ i = j;
139
+ }
140
+ // Bracket matching, so every statement and block can be cut out in one pass.
141
+ toks.forEach((t, k) => { t.i = k; Object.defineProperty(t, 'all', { value: toks, enumerable: false }); });
142
+ const stack = [];
143
+ for (let k = 0; k < toks.length; k++) {
144
+ const t = toks[k];
145
+ if (t.t === 'punc' && OPENERS[t.text]) { stack.push(k); continue; }
146
+ if (t.t === 'punc' && (t.text === '}' || t.text === ')' || t.text === ']')) {
147
+ for (let s = stack.length - 1; s >= 0; s--) { if (OPENERS[toks[stack[s]].text] === t.text) { toks[stack[s]].match = k; stack.length = s; break; } }
148
+ }
149
+ }
150
+ return toks;
151
+ }
152
+
153
+ // ── Values and conditions in words ───────────────────────────────────────────────────────────────────
154
+
155
+ const SPECIAL_VARS = { _: 'it', psitem: 'it', true: 'yes', false: 'no', null: 'nothing', psscriptroot: "this script's folder", pscommandpath: 'this script', args: 'the inputs', lastexitcode: "the last program's exit code", pwd: 'the current folder', home: 'the home folder', error: 'the errors so far', this: 'it' };
156
+ // Inside a catch block, `$_` is the error that was caught.
157
+ let IN_CATCH = 0;
158
+ function varWords(name) {
159
+ const n = String(name);
160
+ const env = n.match(/^env:(.+)$/i);
161
+ if (env) return `the ${words(env[1])} setting`;
162
+ const scoped = n.replace(/^(?:script|global|local|private|using):/i, '');
163
+ if (IN_CATCH && /^(_|psitem)$/i.test(scoped)) return 'the error';
164
+ return SPECIAL_VARS[scoped.toLowerCase()] ?? words(scoped);
165
+ }
166
+ /** Tokens back to their code: the token texts, with a space wherever the source had one. */
167
+ const toksCode = (list) => at0(list).map((t, k, a) => (k && t.at > a[k - 1].end ? ' ' : '') + t.text).join('');
168
+ /** One inserted variable as a placeholder: a plain name as the code spells it; `$_`, `$?`, `$$`, `$^` as code. */
169
+ const insertName = (name) => (/^[_?$^]$/.test(name) ? `«$${name}»` : `«${name}»`);
170
+ /** A value inserted into text (a -f argument) as a placeholder: a plain variable by its name, anything else as code. */
171
+ function insertCode(list) {
172
+ const v = at0(list);
173
+ if (v.length === 1 && v[0].t === 'var' && !v[0].splat) return insertName(v[0].name);
174
+ return `«${toksCode(v)}»`;
175
+ }
176
+ /**
177
+ * Quoted text exactly as the code writes it (escapes included), with each inserted value as a placeholder:
178
+ * "Deploying $name to $($cfg.Env)" -> "Deploying «name» to «$($cfg.Env)»". Single-quoted text is literal.
179
+ * PowerShell expands only `$name` in "…$name.Prop…", so the rest stays text: "«name».Prop".
180
+ */
181
+ function stringText(tok) {
182
+ const oneLine = (x) => (tok.here ? x.replace(/[ \t]*\r?\n[ \t]*/g, ' ').trim() : x);
183
+ if (tok.quote === "'") return oneLine(tok.body);
184
+ let out = '';
185
+ const b = tok.body;
186
+ for (let i = 0; i < b.length; i++) {
187
+ const c = b[i];
188
+ if (c === '`') { out += c + (b[i + 1] ?? ''); i++; continue; }
189
+ if (c === '$' && b[i + 1] === '(') { const e = skipParen(b, i + 1); out += `«${b.slice(i, e)}»`; i = e - 1; continue; }
190
+ if (c === '$') {
191
+ const m = b.slice(i + 1).match(/^\{([^}]+)\}|^(?:[A-Za-z_]\w*:)?[A-Za-z_]\w*|^[?^$]/);
192
+ if (m) { out += insertName(m[1] ?? m[0]); i += m[0].length; continue; }
193
+ }
194
+ out += c;
195
+ }
196
+ return oneLine(out);
197
+ }
198
+ /** A double-quoted text that is one inserted value and nothing else ("$name", "$($x.Count)") is that value, in words. */
199
+ function singleInsert(tok) {
200
+ if (tok.quote !== '"' || tok.here) return null;
201
+ const b = tok.body;
202
+ if (b.startsWith('$(') && skipParen(b, 1) === b.length) return sayValue(tokenize(b.slice(2, -1)));
203
+ const m = b.match(/^\$(?:\{([^}]+)\}|((?:[A-Za-z_]\w*:)?[A-Za-z_]\w*|[?^$]))$/);
204
+ return m ? varWords(m[1] ?? m[2]) : null;
205
+ }
206
+ /** A message: quoted text as it is; any other value in words, never inside quotes it does not have. */
207
+ const messageOf = (v) => (v == null || v === '' ? '' : v);
208
+ const quoteText = (t) => `"${t.length > 100 ? `${t.slice(0, 99)}…` : t}"`;
209
+
210
+ const at0 = (toks) => toks.filter((t) => t.t !== 'nl' && t.t !== 'comment');
211
+ /** Tokens grouped at the top level: each item is one token, or a bracket with everything inside it. */
212
+ function groups(list) {
213
+ const out = [];
214
+ let cur = null, depth = 0;
215
+ for (const t of list) {
216
+ if (depth === 0) { cur = [t]; out.push(cur); } else cur.push(t);
217
+ if (t.t === 'punc' && OPENERS[t.text]) depth++;
218
+ else if (t.t === 'punc' && (t.text === ')' || t.text === '}' || t.text === ']')) depth = Math.max(0, depth - 1);
219
+ }
220
+ return out;
221
+ }
222
+ /** A member chain `$x.Name.Length` or `$x.Items.Count` in words. */
223
+ function chainWords(base, members) {
224
+ const ms = members.filter(Boolean);
225
+ if (!ms.length) return base;
226
+ const last = ms[ms.length - 1];
227
+ const owner = ms.length > 1 ? possessive(base, ms[ms.length - 2]) : base;
228
+ if (/^count$/i.test(last) && owner === 'it') return 'its count';
229
+ if (/^count$/i.test(last) || (/^length$/i.test(last) && owner !== 'it')) return `how many ${owner}`;
230
+ return possessive(owner, last);
231
+ }
232
+ const owns = (x) => (/\w\ws$/.test(x) ? `${x}'` : `${x}'s`);
233
+ const possessive = (owner, member) => (owner === 'it' ? words(member) : `${owns(/^the /.test(owner) ? owner : `the ${owner}`)} ${words(member)}`);
234
+
235
+ /** A value (a group of tokens) in words, or null when it is something Thunder will not guess at. */
236
+ function sayValue(toks, plain = false) {
237
+ toks = at0(toks);
238
+ if (!toks.length) return null;
239
+ while (toks[0].t === 'type' && toks.length > 1 && toks[1].text !== '::') toks = toks.slice(1);
240
+ const g = groups(toks);
241
+ const first = g[0];
242
+ // An assignment inside a value (`($p = Join-Path …)`) is not a value Thunder can name.
243
+ if (g.some((x) => x.length === 1 && x[0].t === 'punc' && /^(=|\+=|-=)$/.test(x[0].text))) return null;
244
+ if (g.length === 1 && first.length === 1) {
245
+ const t = first[0];
246
+ if (t.t === 'str') return singleInsert(t) ?? quoteText(stringText(t));
247
+ if (t.t === 'num') return t.text;
248
+ if (t.t === 'var') return varWords(t.name);
249
+ if (t.t === 'word') return /^[\w.:\\/*?-]+$/.test(t.text) ? quoteText(t.text) : null;
250
+ }
251
+ if (g.length === 1 && first.length > 1) {
252
+ const open = first[0].text;
253
+ const inner = first.slice(1, -1);
254
+ if (open === '@(') return inner.length ? `the list ${listWords(splitCommas(inner).map((x) => sayValue(x) ?? 'a value').slice(0, 6))}` : 'an empty list';
255
+ if (open === '{') return 'a set of steps to run later (a script block)';
256
+ if (open === '@{') { const keys = at0(inner).filter((t, k, a) => (t.t === 'word' || t.t === 'str') && a[k + 1]?.text === '=').map((t) => words(t.t === 'str' ? t.body : t.text)); return keys.length ? `a table of ${listWords(keys.slice(0, 6))}` : 'an empty table'; }
257
+ if ((open === '(' || open === '$(') && first[0].match != null) {
258
+ const all = first[0].all;
259
+ const st = splitStatements(all, first[0].i + 1, first[0].match);
260
+ if (st.length === 1) { const s = pipelineWords(all.slice(st[0][0], st[0][1])); if (s?.command) return `the result of ${gerund(s.says)}`; if (s) return /^[A-Z][a-z]/.test(s.says) ? s.says.charAt(0).toLowerCase() + s.says.slice(1) : s.says; }
261
+ return null;
262
+ }
263
+ }
264
+ // (Get-Item $p).FullName: a fact about what the command gives back.
265
+ if (g.length === 3 && first[0].text === '(' && g[1][0].text === '.' && g[2][0].t === 'word') {
266
+ const inner = sayValue(first, true);
267
+ if (inner) return `the ${words(g[2][0].text)} of ${inner}`;
268
+ }
269
+ // $x.Member, $x.Member.Count, $x.Method(...), [Type]::Member
270
+ if (first.length === 1 && (first[0].t === 'var' || first[0].t === 'type')) {
271
+ const members = [];
272
+ let k = 1, call = null;
273
+ let index = null;
274
+ while (k < g.length) {
275
+ // $matches['ver'], $args[0]: an item of the list or table.
276
+ if (g[k][0].text === '[' && g[k].length > 2) {
277
+ if (index != null) return null;
278
+ const key = at0(g[k].slice(1, -1));
279
+ index = key.length === 1 && key[0].t === 'str' ? { key: key[0].body } : key.length === 1 && key[0].t === 'num' && /^\d+$/.test(key[0].text) ? { n: Number(key[0].text) } : key.length === 2 && key[0].text === '-' && key[1].text === '1' ? { last: true } : key.length === 1 && key[0].t === 'var' ? { by: varWords(key[0].name) } : null;
280
+ if (!index) return null;
281
+ k++; continue;
282
+ }
283
+ if (g[k][0].text !== '.' && g[k][0].text !== '::') break;
284
+ const m = g[k + 1]?.[0];
285
+ if (!m || m.t !== 'word') break;
286
+ if (g[k + 2]?.[0].text === '(') { call = m.text; k += 3; break; }
287
+ if (index != null) { if (index.key == null) return null; members.push(index.key); index = null; }
288
+ members.push(m.text);
289
+ k += 2;
290
+ }
291
+ const owner = first[0].t === 'var' ? varWords(first[0].name) : `the ${first[0].name.split('.').pop()}`;
292
+ if (index != null && (k !== g.length || call)) return null;
293
+ if (index != null) {
294
+ const of = chainWords(owner, members);
295
+ if (index.key != null) return possessive(of, index.key);
296
+ if (index.last) return `the last item of ${of}`;
297
+ if (index.by) return `the entry for ${index.by} in ${of}`;
298
+ const ORD = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth'];
299
+ if (of === 'the inputs' && index.n < 10) return `the ${ORD[index.n]} input`;
300
+ // The index as the code writes it (counting from 0), so the number matches the code.
301
+ return `the item at index ${index.n} of ${of}`;
302
+ }
303
+ if (k === g.length && first[0].t === 'type' && !call && members.length) return `the ${words(members[members.length - 1])} (${first[0].name.split('.').pop()})`;
304
+ if (k === g.length && first[0].t === 'var' && !call) return chainWords(varWords(first[0].name), members);
305
+ if (k === g.length && call) {
306
+ if (/^new$/i.test(call) && first[0].t === 'type') return `a new ${first[0].name.replace(/\[.*$/, '').split('.').pop()}`;
307
+ return `the result of ${words(call)}${first[0].t === 'var' ? ` on ${chainWords(varWords(first[0].name), members)}` : ''}`;
308
+ }
309
+ }
310
+ // Arithmetic and text joined with + - * /.
311
+ const AR = { '+': 'plus', '-': 'minus', '*': 'times', '/': 'divided by', '%': 'remainder after dividing by' };
312
+ const opAt = g.findIndex((x) => x.length === 1 && AR[x[0].text]);
313
+ if (opAt > 0) { const a = sayValue(g.slice(0, opAt).flat()), b = sayValue(g.slice(opAt + 1).flat()); if (a && b) return `${a} ${AR[g[opAt][0].text]} ${b}`; }
314
+ if (g.some((x) => x.length === 1 && x[0].t === 'op' && /^-[ci]?f$/i.test(x[0].text)) && first[0].t === 'str') {
315
+ // A format string: each {n} is the n-th value after -f, as a placeholder; alignment and format are kept.
316
+ const args = splitCommas(g.slice(g.findIndex((x) => /^-[ci]?f$/i.test(x[0].text)) + 1).flat()).map(insertCode);
317
+ let missing = false;
318
+ const text = stringText(first[0]).replace(/\{\{|\}\}|\{(\d+)(,\s*-?\d+)?(:[^}]*)?\}/g, (m, d, al, fm) => { if (d == null) return m; if (args[d] == null) { missing = true; return m; } return al || fm ? `${args[d].slice(0, -1)} as ${m}»` : args[d]; });
319
+ return missing ? null : quoteText(text);
320
+ }
321
+ // Text operators: a -join ', ', a -split ',', a -replace 'x', 'y'.
322
+ const tOp = g.findLastIndex((x, k) => k > 0 && x.length === 1 && x[0].t === 'op' && /^(join|replace|split)$/.test(opName(x[0])));
323
+ if (tOp > 0) {
324
+ const a = sayValue(g.slice(0, tOp).flat(), plain);
325
+ const rest = splitCommas(g.slice(tOp + 1).flat()).map((x) => sayValue(x, true) ?? '…');
326
+ const o = opName(g[tOp][0]);
327
+ if (a) return o === 'join' ? `${a} joined with ${rest[0] ?? 'nothing'}` : o === 'split' ? `${a} split at ${rest[0] ?? 'spaces'}` : `${a} with ${rest[0] ?? '…'} replaced by ${rest[1] ?? 'nothing'}`;
328
+ }
329
+ // Several values separated by commas are a list.
330
+ if (g.some((x) => x.length === 1 && x[0].text === ',')) { const items = splitCommas(toks).map((x) => sayValue(x, true)); if (items.every(Boolean)) return `the list ${listWords(items.slice(0, 6))}${items.length > 6 ? ', …' : ''}`; }
331
+ if (!plain && g.some((x) => x.length === 1 && x[0].t === 'op')) { const c = condWords(toks, false); if (c) return `whether ${c}`; }
332
+ const cmd = toks[0].t === 'word' || toks[0].text === '&' ? pipelineWords(toks) : null;
333
+ if (cmd?.command) return `the result of ${gerund(cmd.says)}`;
334
+ return null;
335
+ }
336
+ function splitCommas(toks) {
337
+ const out = [[]];
338
+ for (const g of groups(toks)) { if (g.length === 1 && g[0].text === ',') out.push([]); else out[out.length - 1].push(...g); }
339
+ return out.filter((x) => at0(x).length);
340
+ }
341
+
342
+ const CMP = { eq: ['is', 'is not'], ne: ['is not', 'is'], gt: ['is more than', 'is at most'], ge: ['is at least', 'is less than'], lt: ['is less than', 'is at least'], le: ['is at most', 'is more than'], like: ['matches', 'does not match'], notlike: ['does not match', 'matches'], match: ['matches the pattern', 'does not match the pattern'], notmatch: ['does not match the pattern', 'matches the pattern'], contains: ['includes', 'does not include'], notcontains: ['does not include', 'includes'], in: ['is one of', 'is not one of'], notin: ['is not one of', 'is one of'], is: ['is a', 'is not a'], isnot: ['is not a', 'is a'], as: ['can be turned into a', 'cannot be turned into a'] };
343
+ const BASE_OPS = new Set(['eq', 'ne', 'gt', 'ge', 'lt', 'le', 'like', 'notlike', 'match', 'notmatch', 'contains', 'notcontains', 'in', 'notin', 'is', 'isnot', 'as', 'and', 'or', 'xor', 'not', 'replace', 'split', 'join', 'f', 'band', 'bor', 'bxor', 'bnot', 'shl', 'shr']);
344
+ const opName = (t) => { const x = t.text.toLowerCase().slice(1); return BASE_OPS.has(x) ? x : x.replace(/^[ci]/, ''); };
345
+
346
+ // The faithfulness gate (faithful.mjs) counts `!`, `!=`, `&&`, `||` and comparisons; PowerShell spells them as
347
+ // -not, -ne, -and, -or, -gt, … So the condition is first written with those symbols, then checked against the words.
348
+ const GATE_OPS = { eq: '==', ne: '!=', gt: '>', ge: '>=', lt: '<', le: '<=', and: '&&', or: '||', xor: '||', not: '!', like: '~', match: '~', contains: '~', notlike: '!~', notmatch: '!~', notcontains: '!~', in: 'in', notin: 'not in', is: 'is', isnot: 'is not', as: 'as' };
349
+ export function psCondCode(toks) {
350
+ const code = at0(toks).map((t, k, a) => {
351
+ const sp = k && t.at > a[k - 1].end ? ' ' : '';
352
+ if (t.t === 'op') return ` ${GATE_OPS[opName(t)] ?? opName(t)} `;
353
+ if (t.t === 'var') return sp + (/^null$/i.test(t.name) ? 'null' : t.name.replace(/^\w+:/, ''));
354
+ if (t.t === 'str') return `${sp}Q`;
355
+ if (t.t === 'param') return `${sp}P`;
356
+ return sp + t.text;
357
+ }).join('');
358
+ // `$null -ne $x` is `$x -ne $null`: "x is set" (faithful.mjs reads `!= null` as "is set", not as a negation).
359
+ return code.replace(/\bnull\s*(==|!=)\s*([\w.]+)/g, '$2 $1 null');
360
+ }
361
+ /** The words for a condition, or null when they do not account for every negation, and/or, and comparison. */
362
+ // While the gate reads a condition, each value inside it is marked (\u0001…\u0002), so a list's "and" or a
363
+ // possessive's apostrophe inside a value is not taken for logic or a quote.
364
+ let MARK = 0;
365
+ const atom = (v) => (MARK && v ? `\u0001${v}\u0002` : v);
366
+ function gated(toks, said) {
367
+ if (!said || said === 'always' || said === 'never') return said;
368
+ MARK++;
369
+ let marked;
370
+ try { marked = condWords(toks, false); } finally { MARK--; }
371
+ if (!marked) return null;
372
+ let checked = marked;
373
+ for (let n = 0; n < 4 && /\u0001/.test(checked); n++) checked = checked.replace(/\u0001([^\u0001\u0002]*)\u0002/g, (m, v) => v.replace(/\b(?:and|or)\b/g, '&').replace(/'/g, ''));
374
+ checked = checked.replace(/[\u0001\u0002]/g, '');
375
+ return accountsFor(psCondCode(toks), checked) ? said : null;
376
+ }
377
+
378
+ /** A condition in words: `$Count -gt 0 -and -not $Force` -> "count is more than 0 and force is not set". */
379
+ function condWords(toks, neg) {
380
+ const g = groups(at0(toks));
381
+ if (!g.length) return null;
382
+ const split = (names) => { const parts = [[]]; for (const x of g) { if (x.length === 1 && x[0].t === 'op' && names.includes(opName(x[0]))) parts.push([]); else parts[parts.length - 1].push(x); } return parts; };
383
+ for (const [names, join, flip] of [[['or', 'xor'], ' or ', ' and '], [['and'], ' and ', ' or ']]) {
384
+ const parts = split(names);
385
+ if (parts.length > 1) { const said = parts.map((p) => condWords(p.flat(), neg)); return said.some((x) => !x) ? null : said.join(neg ? flip : join); }
386
+ }
387
+ if ((g[0].length === 1 && ((g[0][0].t === 'op' && opName(g[0][0]) === 'not') || g[0][0].text === '!'))) return condWords(g.slice(1).flat(), !neg);
388
+ if (g.length === 1 && g[0].length > 1 && g[0][0].text === '(') {
389
+ const inner = g[0].slice(1, -1);
390
+ const ig = groups(at0(inner));
391
+ if (ig[0]?.length === 1 && ig[0][0].t === 'word' && /-/.test(ig[0][0].text)) return commandCond(at0(inner), neg);
392
+ // `-not (a -or b)` stays one negation of the whole: "not (a or b)".
393
+ if (neg && ig.some((x) => x.length === 1 && x[0].t === 'op' && /^(and|or|xor)$/.test(opName(x[0])))) { const c = condWords(inner, false); return c ? `not (${c})` : null; }
394
+ return condWords(inner, neg);
395
+ }
396
+ if (g[0].length === 1 && g[0][0].t === 'word' && /^[A-Za-z]+-[A-Za-z]/.test(g[0][0].text)) return commandCond(at0(toks), neg);
397
+ const at = g.findIndex((x) => x.length === 1 && x[0].t === 'op' && CMP[opName(x[0])]);
398
+ if (at > 0) {
399
+ const op = opName(g[at][0]);
400
+ const left = g.slice(0, at).flat(), right = g.slice(at + 1).flat();
401
+ const isNull = (x) => x.length === 1 && x[0].t === 'var' && /^null$/i.test(x[0].name);
402
+ if (isNull(left) || isNull(right)) {
403
+ const other = sayValue(isNull(left) ? right : left);
404
+ if (!other || !['eq', 'ne'].includes(op)) return null;
405
+ return `${atom(other)} is ${(op === 'eq') !== neg ? 'empty' : 'set'}`;
406
+ }
407
+ const a = sayValue(left), b = right.length === 1 && right[0].t === 'type' ? right[0].name.split('.').pop() : sayValue(right);
408
+ if (!a || !b) return null;
409
+ return `${atom(a)} ${CMP[op][neg ? 1 : 0]} ${atom(b)}`;
410
+ }
411
+ const v = sayValue(at0(toks), true);
412
+ if (!v) return null;
413
+ if (v === 'yes' || v === 'no') return (v === 'yes') !== neg ? 'always' : 'never';
414
+ return `${atom(v)} is ${neg ? 'not ' : ''}set`;
415
+ }
416
+ /** A command used as a question: Test-Path -> "the file exists", anything else -> "it finds something". */
417
+ function commandCond(toks, neg) {
418
+ const name = toks[0].text;
419
+ const args = argsOf(toks.slice(1));
420
+ if (/^test-path$/i.test(name)) { const p = args.named.path ?? args.named.literalpath ?? args.pos[0]; const v = p ? sayValue(p) : 'the path'; return v ? `${atom(v)} ${neg ? 'does not exist' : 'exists'}` : null; }
421
+ if (/^get-command$/i.test(name)) { const p = args.named.name ?? args.pos[0]; const v = p ? sayValue(p) : 'the command'; return v ? `${atom(v)} is ${neg ? 'not ' : ''}installed` : null; }
422
+ const s = commandWords(toks);
423
+ if (s && /^test-/i.test(name)) return `${atom(gerund(s))} says ${neg ? 'no' : 'yes'}`;
424
+ return s ? `${atom(gerund(s))} ${neg ? 'does not find anything' : 'finds something'}` : null;
425
+ }
426
+
427
+ /** A condition as an expression the Thunder decision reader understands (`score >= 90 && member`), or null. */
428
+ export function condJs(toks) {
429
+ const out = [];
430
+ for (const t of at0(toks)) {
431
+ if (t.t === 'op') {
432
+ const o = opName(t);
433
+ const m = { eq: '==', ne: '!=', gt: '>', ge: '>=', lt: '<', le: '<=', and: '&&', or: '||', not: '!' }[o];
434
+ if (!m) return null;
435
+ out.push(m);
436
+ } else if (t.t === 'var') {
437
+ if (/^true$/i.test(t.name)) out.push('true'); else if (/^false$/i.test(t.name)) out.push('false'); else if (/^null$/i.test(t.name)) return null;
438
+ else out.push(t.name.replace(/^(?:script|global|local):/i, '').replace(/^this$/i, 'this'));
439
+ } else if (t.t === 'str') { if (t.quote === '"' && /\$/.test(t.body)) return null; out.push(JSON.stringify(t.body.replace(/''/g, "'"))); }
440
+ else if (t.t === 'num') { if (!/^-?\d+(\.\d+)?$/.test(t.text)) return null; out.push(t.text); }
441
+ else if (t.t === 'punc' && ['(', ')', '.', '!'].includes(t.text)) out.push(t.text);
442
+ else if (t.t === 'word' && out[out.length - 1] === '.') out.push(t.text);
443
+ else return null;
444
+ }
445
+ return out.join(' ').replace(/ \. /g, '.');
446
+ }
447
+
448
+ // ── Commands ──────────────────────────────────────────────────────────────────────────────────────────
449
+
450
+ const REDIRECT = /^(?:[1-6*]?>>?|[1-6*]>&[12])$/;
451
+ /**
452
+ * A command's arguments as PowerShell splits them: at spaces, so `$s.Path.Expand()` or `$x[0]` is one argument.
453
+ * Redirections (`> $null`, `2>&1`) are not arguments and are left out.
454
+ */
455
+ function argGroups(toks) {
456
+ const out = [];
457
+ let skipNext = false;
458
+ for (const g of groups(at0(toks))) {
459
+ if (skipNext) { skipNext = false; continue; }
460
+ if (g.length === 1 && g[0].t === 'punc' && REDIRECT.test(g[0].text)) {
461
+ // `2>$null` reads as the number 2 and `>`: the 2 is part of the redirection.
462
+ const prev = out[out.length - 1];
463
+ if (prev?.length === 1 && prev[0].t === 'num' && /^\d$/.test(prev[0].text) && prev[0].end === g[0].at) out.pop();
464
+ skipNext = !/&/.test(g[0].text);
465
+ continue;
466
+ }
467
+ const prev = out[out.length - 1];
468
+ const last = prev?.[prev.length - 1];
469
+ if (prev && g[0].at === last.end && g[0].text !== ',' && last.text !== ',' && prev[0].t !== 'param' && g[0].t !== 'param') prev.push(...g);
470
+ else out.push([...g]);
471
+ }
472
+ return out;
473
+ }
474
+
475
+ /** A command's arguments: { named: { name: tokens }, pos: [tokens], switches: Set, block: tokens|null }. */
476
+ function argsOf(toks) {
477
+ const named = {}, pos = [], switches = new Set(), spelled = {};
478
+ const g = argGroups(toks);
479
+ for (let k = 0; k < g.length; k++) {
480
+ const x = g[k];
481
+ if (x.length === 1 && x[0].t === 'param') {
482
+ const name = x[0].text.slice(1).replace(/:$/, '').toLowerCase();
483
+ spelled[name] = x[0].text.slice(1).replace(/:$/, '');
484
+ const next = g[k + 1];
485
+ if (x[0].text.endsWith(':') && next) { named[name] = next; k++; continue; }
486
+ if (next && !(next.length === 1 && (next[0].t === 'param' || next[0].text === ','))) {
487
+ if (SWITCH.has(name)) { switches.add(name); continue; }
488
+ // Values joined by commas belong together: -Name a, b.
489
+ let val = [...next];
490
+ k++;
491
+ while (g[k + 1]?.[0].text === ',' && g[k + 2]) { val = [...val, ...g[k + 1], ...g[k + 2]]; k += 2; }
492
+ named[name] = val;
493
+ } else switches.add(name);
494
+ continue;
495
+ }
496
+ pos.push(x);
497
+ }
498
+ return { named, pos, switches, spelled };
499
+ }
500
+ const SWITCH = new Set(['leaf', 'parent', 'verbose', 'debug', 'force', 'recurse', 'whatif', 'confirm', 'passthru', 'asjob', 'noprofile', 'nonewline', 'raw', 'descending', 'unique', 'wait', 'erroraction', 'append', 'notypeinformation']);
501
+ SWITCH.delete('erroraction');
502
+
503
+ const VERB = { get: 'Gets', set: 'Sets', new: 'Makes', remove: 'Removes', add: 'Adds', clear: 'Clears', copy: 'Copies', move: 'Moves', rename: 'Renames', start: 'Starts', stop: 'Stops', restart: 'Restarts', invoke: 'Runs', test: 'Checks', write: 'Writes', read: 'Reads', import: 'Loads', export: 'Saves', install: 'Installs', uninstall: 'Uninstalls', update: 'Updates', wait: 'Waits for', join: 'Joins', split: 'Splits', enable: 'Turns on', disable: 'Turns off', register: 'Registers', unregister: 'Unregisters', publish: 'Publishes', send: 'Sends', receive: 'Receives', connect: 'Connects to', disconnect: 'Disconnects from', resolve: 'Works out', push: 'Saves and moves to', pop: 'Goes back to', enter: 'Enters', exit: 'Leaves', find: 'Finds', search: 'Searches for', show: 'Shows', hide: 'Hides', format: 'Formats', compare: 'Compares', confirm: 'Confirms', use: 'Uses', grant: 'Grants', revoke: 'Revokes', protect: 'Protects', unprotect: 'Unprotects', lock: 'Locks', unlock: 'Unlocks', mount: 'Mounts', dismount: 'Unmounts', deploy: 'Deploys', build: 'Builds', merge: 'Merges', initialize: 'Sets up', reset: 'Resets', edit: 'Edits', expand: 'Unpacks', compress: 'Packs', save: 'Saves', sync: 'Syncs', restore: 'Restores', backup: 'Backs up', submit: 'Submits', request: 'Requests', close: 'Closes', open: 'Opens', convert: 'Turns', convertto: 'Turns', convertfrom: 'Reads', measure: 'Measures', select: 'Picks', sort: 'Sorts', group: 'Groups', out: 'Sends', assert: 'Checks', approve: 'Approves', block: 'Blocks', unblock: 'Unblocks', suspend: 'Pauses', resume: 'Resumes', repair: 'Repairs', debug: 'Debugs', trace: 'Traces', limit: 'Limits', optimize: 'Optimizes', redo: 'Redoes', undo: 'Undoes', complete: 'Finishes', checkpoint: 'Checkpoints', watch: 'Watches', step: 'Steps', skip: 'Skips', switch: 'Switches', ping: 'Pings', mock: 'Fakes' };
504
+ const NOUN_PREFIX = [[/^AzureRm/, 'Azure '], [/^AzureAD/, 'Azure AD '], [/^Az(?=[A-Z])/, 'Azure '], [/^Mg(?=[A-Z])/, 'Microsoft Graph '], [/^AD(?=[A-Z])/, 'Active Directory '], [/^Exo(?=[A-Z])/, 'Exchange Online '], [/^Pnp(?=[A-Z])/i, 'SharePoint '], [/^Pode(?=[A-Z])/, 'Pode ']];
505
+ function nounWords(noun) {
506
+ let pre = '', n = noun;
507
+ for (const [re, w] of NOUN_PREFIX) if (re.test(n)) { pre = w; n = n.replace(re, ''); break; }
508
+ const parts = n.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+/g) || [n];
509
+ return pre + parts.map((p) => (/^[A-Z]{2,}$/.test(p) ? p : p.toLowerCase())).join(' ');
510
+ }
511
+ const pluralNoun = (n) => (/(?:s|sh|ch|x)$/.test(n) ? `${n}es` : /[^aeiou]y$/.test(n) ? `${n.slice(0, -1)}ies` : `${n}s`);
512
+
513
+ const ALIASES = { ls: 'Get-ChildItem', dir: 'Get-ChildItem', gci: 'Get-ChildItem', cd: 'Set-Location', sl: 'Set-Location', chdir: 'Set-Location', rm: 'Remove-Item', del: 'Remove-Item', ri: 'Remove-Item', rmdir: 'Remove-Item', erase: 'Remove-Item', cp: 'Copy-Item', copy: 'Copy-Item', cpi: 'Copy-Item', mv: 'Move-Item', move: 'Move-Item', mi: 'Move-Item', cat: 'Get-Content', gc: 'Get-Content', type: 'Get-Content', echo: 'Write-Output', write: 'Write-Output', '%': 'ForEach-Object', foreach: 'ForEach-Object', '?': 'Where-Object', where: 'Where-Object', select: 'Select-Object', sort: 'Sort-Object', iex: 'Invoke-Expression', irm: 'Invoke-RestMethod', iwr: 'Invoke-WebRequest', md: 'New-Item', mkdir: 'New-Item', pwd: 'Get-Location', cls: 'Clear-Host', ni: 'New-Item', sc: 'Set-Content', ac: 'Add-Content', ipmo: 'Import-Module', gm: 'Get-Member', measure: 'Measure-Object', group: 'Group-Object', tee: 'Tee-Object', sleep: 'Start-Sleep', start: 'Start-Process', saps: 'Start-Process', kill: 'Stop-Process', ps: 'Get-Process', gps: 'Get-Process', gsv: 'Get-Service', ft: 'Format-Table', fl: 'Format-List' };
514
+
515
+ let STOP_ON_ERROR = false;
516
+ let KNOWN_FNS = new Set();
517
+
518
+ /** One argument in words, or its code when it cannot be said. */
519
+ const argWords = (x) => sayValue(x) ?? asCodeWords(toksCode(x), 60);
520
+ /** A message argument (-Message or the first one given). */
521
+ const msgArg = (a, key) => (a.named[key] ? argWords(a.named[key]) : a.pos[0] ? argWords(a.pos[0]) : '(empty)');
522
+ /** " with a, b, and c set to d": every argument a command is given, none dropped. */
523
+ function withArgs(a) {
524
+ const parts = [...a.pos.map(argWords), ...Object.entries(a.named).map(([k, v]) => `${words(a.spelled[k] ?? k)} set to ${argWords(v)}`), ...[...a.switches].map((k) => `the ${words(a.spelled[k] ?? k)} switch`)];
525
+ return parts.length ? ` with ${listWords(parts)}` : '';
526
+ }
527
+
528
+ /** One command (name and argument tokens) in words, or null. */
529
+ function commandWords(toks, ctx = {}) {
530
+ toks = at0(toks);
531
+ if (!toks.length) return null;
532
+ let head = toks[0];
533
+ let rest = toks.slice(1);
534
+ if ((head.text === '&' || head.text === '.') && rest.length) {
535
+ const ag = argGroups(rest);
536
+ const target = ag[0];
537
+ if (target.length === 1 && target[0].t === 'word' && !/[\\/]/.test(target[0].text)) { head = target[0]; rest = rest.slice(1); }
538
+ else {
539
+ const said = target.length === 1 && target[0].t === 'word' ? quoteText(target[0].text) : sayValue(target);
540
+ if (!said) return null;
541
+ const more = ag.slice(1).map((x) => argWords(x));
542
+ return `${head.text === '.' ? 'Loads the commands in' : 'Runs'} ${said}${more.length ? ` with ${listWords(more)}` : ''}`;
543
+ }
544
+ }
545
+ if (head.t !== 'word') return null;
546
+ const raw = head.text;
547
+ const name = ALIASES[raw.toLowerCase()] && !(raw.toLowerCase() === 'mkdir' && false) ? ALIASES[raw.toLowerCase()] : raw;
548
+ const a = argsOf(rest);
549
+ const val = (k, ...more) => { for (const n of [k, ...more]) if (a.named[n]) return sayValue(a.named[n]); return null; };
550
+ const p0 = a.pos[0] ? sayValue(a.pos[0]) : null;
551
+ const target = val('path', 'literalpath', 'name', 'filepath', 'uri', 'id', 'identity', 'resourcegroupname') ?? p0;
552
+ const lower = name.toLowerCase();
553
+ if (/^(mkdir|md)$/i.test(raw)) return `Makes the folder ${target ?? '?'}`;
554
+ switch (lower) {
555
+ case 'write-host': case 'write-output': case 'write-information': {
556
+ const m = a.named.object ?? a.named.messagedata;
557
+ const parts = m ? [m] : a.pos;
558
+ const msg = parts.length === 1 ? argWords(parts[0]) : parts.length ? `${parts.map(argWords).join(', ')} (joined by spaces)` : '';
559
+ if (lower === 'write-output') return msg ? (/^"/.test(msg) ? `Writes out the text ${msg}` : `Writes out ${msg}`) : 'Writes out an empty line';
560
+ return msg ? `${lower === 'write-host' ? 'Shows' : 'Writes'} a message: ${msg}` : `${lower === 'write-host' ? 'Shows' : 'Writes'} an empty line`;
561
+ }
562
+ // A message is quoted text only when the code has quoted text; `$_` is the error, not the word "it".
563
+ case 'write-verbose': return `Writes a detailed message: ${msgArg(a, 'message')}`;
564
+ case 'write-debug': return `Writes a debugging message: ${msgArg(a, 'message')}`;
565
+ case 'write-warning': return `Warns: ${msgArg(a, 'message')}`;
566
+ case 'write-progress': return `Shows progress: ${val('activity') ?? p0 ?? '…'}`;
567
+ case 'new-item': {
568
+ const type = String(val('itemtype', 'type') ?? '').replace(/"/g, '').toLowerCase();
569
+ const what = /directory|folder/.test(type) || /^(mkdir|md)$/i.test(raw) ? 'a folder' : /file/.test(type) ? 'a file' : /symbolic/.test(type) ? 'a link' : 'an item';
570
+ return `Makes ${what} ${target ?? '?'}${val('value') ? ` containing ${val('value')}` : ''}`;
571
+ }
572
+ case 'remove-item': return `Removes ${target ?? 'them'}${a.switches.has('recurse') ? ' and everything in it' : ''}`;
573
+ case 'set-content': return `Writes ${val('value') ?? (a.pos[1] ? sayValue(a.pos[1]) : 'it')} to ${val('path', 'literalpath') ?? p0 ?? '?'}`;
574
+ case 'add-content': return `Adds ${val('value') ?? (a.pos[1] ? sayValue(a.pos[1]) : 'it')} to the end of ${val('path', 'literalpath') ?? p0 ?? '?'}`;
575
+ case 'get-content': return `Reads ${target ?? 'the file'}`;
576
+ case 'out-file': return `Saves it to ${val('filepath', 'path') ?? p0 ?? '?'}`;
577
+ case 'copy-item': return `Copies ${target ?? '?'} to ${val('destination') ?? (a.pos[1] ? sayValue(a.pos[1]) : '?')}${a.switches.has('recurse') ? ', with everything inside' : ''}`;
578
+ case 'move-item': return `Moves ${target ?? '?'} to ${val('destination') ?? (a.pos[1] ? sayValue(a.pos[1]) : '?')}`;
579
+ case 'rename-item': return `Renames ${target ?? '?'} to ${val('newname') ?? (a.pos[1] ? sayValue(a.pos[1]) : '?')}`;
580
+ case 'get-childitem': return `Gets the files and folders in ${target ?? 'the current folder'}${val('filter', 'include') ? ` matching ${val('filter', 'include')}` : ''}${a.switches.has('recurse') ? ', looking inside every folder' : ''}`;
581
+ case 'set-location': return `Goes into the folder ${target ?? '?'}`;
582
+ case 'push-location': return `Goes into the folder ${target ?? '?'}, remembering where it was`;
583
+ case 'pop-location': return 'Goes back to the folder it was in before';
584
+ case 'get-location': return 'Gets the current folder';
585
+ case 'test-path': return `Checks whether ${target ?? 'the path'} exists`;
586
+ case 'join-path': return `Joins ${target ?? '?'} and ${val('childpath') ?? (a.pos[1] ? sayValue(a.pos[1]) : '?')} into one path`;
587
+ case 'split-path': return a.switches.has('leaf') ? `Takes the last part of the path ${target ?? '?'}` : a.switches.has('parent') || !a.switches.size ? `Takes the folder of the path ${target ?? '?'}` : `Takes part of the path ${target ?? '?'}`;
588
+ case 'invoke-restmethod': case 'invoke-webrequest': {
589
+ const method = String(val('method') ?? 'GET').replace(/"/g, '').toUpperCase();
590
+ const url = val('uri') ?? p0 ?? '?';
591
+ return `Sends a ${method} request to ${url}${a.named.body ? ` with ${sayValue(a.named.body) ?? 'a body'}` : ''}${val('outfile') ? ` and saves the answer to ${val('outfile')}` : ''}`;
592
+ }
593
+ case 'start-sleep': { const s = val('seconds', 's') ?? p0; const ms = val('milliseconds', 'm'); return ms ? `Waits ${ms} milliseconds` : `Waits ${s ?? '?'} second${s === '1' ? '' : 's'}`; }
594
+ case 'start-process': return `Starts the program ${val('filepath') ?? p0 ?? '?'}${a.switches.has('wait') ? ' and waits for it to finish' : ''}`;
595
+ case 'import-module': return `Loads the module ${val('name') ?? p0 ?? '?'}`;
596
+ case 'export-modulemember': return `Makes ${val('function') ?? p0 ?? 'these functions'} available to users of the module`;
597
+ case 'read-host': return `Asks the person: ${val('prompt') ?? p0 ?? '…'}`;
598
+ case 'get-date': return 'Gets the date and time';
599
+ case 'set-strictmode': return 'Treats mistakes such as missing settings as errors';
600
+ case 'convertto-json': return 'Turns it into JSON';
601
+ case 'convertfrom-json': return 'Reads the JSON';
602
+ case 'invoke-expression': return `Runs the text ${p0 ?? val('command') ?? '?'} as a command`;
603
+ case 'invoke-command': return a.named.computername ? `Runs these steps on ${val('computername')}` : 'Runs these steps';
604
+ case 'get-command': return `Looks up the command ${target ?? '?'}`;
605
+ case 'new-object': { const props = a.named.property ? sayValue(a.named.property) : null; return `Makes a new ${String(val('typename') ?? p0 ?? 'object').replace(/"/g, '').split('.').pop()}${props ? ` from ${props}` : ''}`; }
606
+ case 'expand-archive': return `Unpacks ${target ?? '?'}${val('destinationpath') ? ` into ${val('destinationpath')}` : ''}`;
607
+ case 'compress-archive': return `Packs ${target ?? '?'} into ${val('destinationpath') ?? '?'}`;
608
+ case 'add-type': return 'Loads .NET code';
609
+ case 'clear-host': return 'Clears the screen';
610
+ case 'export-csv': return `Saves them to the CSV file ${target ?? '?'}`;
611
+ case 'import-csv': return `Reads the CSV file ${target ?? '?'}`;
612
+ default: break;
613
+ }
614
+ if (KNOWN_FNS.has(lower)) return `Runs ${words(name)}${withArgs(a)}`;
615
+ const vn = name.match(/^([A-Za-z]+)-([A-Za-z]\w*)$/);
616
+ if (vn && (VERB[vn[1].toLowerCase()])) {
617
+ const verb = vn[1].toLowerCase();
618
+ const noun = nounWords(vn[2]);
619
+ const OBJ = ['name', 'resourcegroupname', 'identity', 'id', 'path', 'displayname', 'vmname', 'servicename', 'username'];
620
+ const objKey = OBJ.find((k) => a.named[k]);
621
+ const named = objKey ? sayValue(a.named[objKey]) : null;
622
+ const object = named ?? (a.pos[0] ? sayValue(a.pos[0]) : null);
623
+ // Every other value it is given is kept: `Write-Prompt $text -Color $c` is not just "the prompt text".
624
+ const extra = { named: Object.fromEntries(Object.entries(a.named).filter(([k]) => k !== objKey && k !== 'erroraction')), pos: objKey ? a.pos : a.pos.slice(1), switches: new Set(), spelled: a.spelled };
625
+ const more = withArgs(extra);
626
+ const many = verb === 'get' && !object;
627
+ const dup = object && !/^"/.test(object) && noun.toLowerCase().endsWith(object.toLowerCase());
628
+ return `${VERB[verb]} the ${many ? pluralNoun(noun) : noun}${object ? (dup ? ` named by ${object}` : ` ${object}`) : ''}${more}`;
629
+ }
630
+ const raws = argGroups(rest).map(toksCode);
631
+ const known = sayCommand(raw.replace(/\.exe$/i, ''), raws, (w) => sayValue(tokenize(w)) ?? quoteText(w));
632
+ if (known) return known;
633
+ if (/[\\/]|\.ps1$/i.test(raw)) return `Runs the script ${quoteText(raw)}${withArgs(a)}`;
634
+ return `Runs ${raw}${withArgs(a)}`;
635
+ }
636
+
637
+ /**
638
+ * A pipeline (`A | B | C`) or an expression statement in words. Gives { says, command, loop?, block? } or null.
639
+ * `loop` is set when it ends in ForEach-Object with a script block (its steps are the loop's body).
640
+ */
641
+ function pipelineWords(toks) {
642
+ toks = at0(toks);
643
+ const parts = [[]];
644
+ for (const g of groups(toks)) { if (g.length === 1 && g[0].text === '|') parts.push([]); else parts[parts.length - 1].push(...g); }
645
+ const said = [];
646
+ let command = false, loop = null, headValue = null;
647
+ for (let k = 0; k < parts.length; k++) {
648
+ const p = parts[k];
649
+ if (!p.length) continue;
650
+ const head = p[0];
651
+ if (head.t === 'word' && /^(if|switch|foreach|for|while|do|try|function|class|return|throw)$/i.test(head.text)) return null;
652
+ const name = head.t === 'word' ? (ALIASES[head.text.toLowerCase()] ?? head.text) : head.t === 'punc' && (head.text === '%' || head.text === '?') && k > 0 ? ALIASES[head.text] : '';
653
+ const lower = name.toLowerCase();
654
+ const blockG = groups(p.slice(1)).find((x) => x[0].text === '{');
655
+ const block = blockG?.[0];
656
+ if (lower === 'where-object') {
657
+ const ct = blockG ? blockG.slice(1, -1) : p.slice(1);
658
+ const c = gated(ct, condWords(ct, false));
659
+ said.push(`keeps only those where ${c ?? asCodeWords(toksCode(ct))}`);
660
+ command = true;
661
+ continue;
662
+ }
663
+ if (lower === 'foreach-object' && block) {
664
+ // Only one block's steps can be shown as the loop body.
665
+ if (loop) return null;
666
+ // In the middle of a pipeline, the steps run on each item before the later commands see them.
667
+ const last = parts.slice(k + 1).every((q) => !q.length || /^out-null$/i.test(q[0].text));
668
+ loop = { from: block.i + 1, to: block.match, ...(last ? {} : { middle: true }) };
669
+ if (!last) said.push('runs the steps below on each one');
670
+ command = true;
671
+ continue;
672
+ }
673
+ if (lower === 'foreach-object') {
674
+ // `ForEach-Object Name`: each item's Name.
675
+ const a = argsOf(p.slice(1));
676
+ const m = at0(a.named.membername ?? a.pos[0] ?? []);
677
+ if (m.length !== 1 || m[0].t !== 'word' || a.pos.length > 1) return null;
678
+ said.push(`takes each one's ${words(m[0].text)}`);
679
+ command = true;
680
+ continue;
681
+ }
682
+ if (lower === 'out-null') continue;
683
+ if (lower === 'select-object') { const a = argsOf(p.slice(1)); const first = a.named.first ? sayValue(a.named.first) : null; const props = a.named.property ?? a.pos[0]; const xp = a.named.expandproperty ? at0(a.named.expandproperty) : null; said.push(xp?.length === 1 ? `takes each one's ${words(xp[0].text)}` : first ? `takes the first ${first}` : a.named.last ? `takes the last ${sayValue(a.named.last)}` : a.switches.has('unique') ? 'keeps one of each' : props ? `picks ${listWords(splitCommas(props).map((x) => words(at0(x)[0]?.text ?? '')))}` : 'picks some of them'); command = true; continue; }
684
+ if (lower === 'sort-object') { const a = argsOf(p.slice(1)); const by = a.named.property ?? a.pos[0]; said.push(`sorts them${by ? ` by ${listWords(splitCommas(by).map((x) => words(at0(x)[0]?.text ?? '')))}` : ''}${a.switches.has('descending') ? ', highest first' : ''}`); command = true; continue; }
685
+ if (lower === 'measure-object') { said.push('counts them'); command = true; continue; }
686
+ if (lower === 'group-object') { const a = argsOf(p.slice(1)); const by = a.named.property ?? a.pos[0]; said.push(`groups them${by ? ` by ${words(at0(by)[0]?.text ?? '')}` : ''}`); command = true; continue; }
687
+ if (lower === 'format-table' || lower === 'format-list') { said.push(`shows them as a ${lower === 'format-table' ? 'table' : 'list'}`); command = true; continue; }
688
+ if (lower === 'tee-object') { said.push('keeps a copy as it goes'); command = true; continue; }
689
+ if (head.t === 'word' || head.text === '&' || (head.text === '.' && p.length > 1 && p[1].t !== 'word')) {
690
+ const s = commandWords(p);
691
+ if (s && k === 1 && headValue && said.length === 1) {
692
+ // `$module | Import-Module`: the value is what the command works on.
693
+ said[0] = / \?(?=$|[\s,])/.test(s) ? s.replace(/ \?(?=$|[\s,])/, ` ${headValue}`) : `Passes ${headValue} into ${gerund(s)}`;
694
+ headValue = null; command = true; continue;
695
+ }
696
+ if (s) { said.push(k === 0 ? s : s.charAt(0).toLowerCase() + s.slice(1)); command = true; continue; }
697
+ if (k > 0) return null;
698
+ }
699
+ const v = sayValue(p);
700
+ if (!v) return null;
701
+ if (k === 0) headValue = v;
702
+ said.push(k === 0 ? v : `then ${v}`);
703
+ }
704
+ if (!said.length && !loop) return null;
705
+ const rest = said.slice(1).map((x) => x.replace(/^then /, ''));
706
+ const text = said.length ? cap(said[0]) + (rest.length ? `, ${rest.length > 1 ? `${rest.slice(0, -1).join(', ')}, then ${rest[rest.length - 1]}` : `then ${rest[0]}`}` : '') : '';
707
+ return { says: text, command, ...(loop ? { loop } : {}), ...(headValue && said.length === 1 ? { value: headValue } : {}) };
708
+ }
709
+
710
+ // ── Statements ────────────────────────────────────────────────────────────────────────────────────────
711
+
712
+ const BLOCK_KW = /^(if|elseif|else|foreach|for|while|do|switch|try|catch|finally|trap|function|filter|workflow|class|enum|begin|process|end|dynamicparam|until)$/i;
713
+ const CONTINUES = /^(=|\+=|-=|\*=|\/=|\||,|\+|-|\*|\/|::|\(|\{|\[)$/;
714
+
715
+ /** Statement ranges [from, to) in toks[from..to), with else/catch/while/{ on later lines joined to their statement. */
716
+ function splitStatements(toks, from, to) {
717
+ const out = [];
718
+ let i = from;
719
+ while (i < to) {
720
+ while (i < to && (toks[i].t === 'nl' || toks[i].t === 'comment' || toks[i].text === ';')) i++;
721
+ if (i >= to) break;
722
+ const s = i;
723
+ const kw = toks[s].t === 'word' ? toks[s].text.toLowerCase() : '';
724
+ while (i < to) {
725
+ const t = toks[i];
726
+ if (t.match != null && t.match < to) { i = t.match + 1; continue; }
727
+ if (t.text === ';' && t.t === 'punc') break;
728
+ if (t.t === 'nl') {
729
+ let prev = i - 1;
730
+ while (prev > s && toks[prev].t === 'comment') prev--;
731
+ const p = toks[prev];
732
+ if (p && (p.t === 'punc' && CONTINUES.test(p.text) || p.t === 'op')) { i++; continue; }
733
+ let k = i;
734
+ while (k < to && (toks[k].t === 'nl' || toks[k].t === 'comment')) k++;
735
+ const nx = toks[k];
736
+ if (nx && ((nx.t === 'punc' && nx.text === '|') || (nx.t === 'punc' && nx.text === '.' && toks[k + 1]?.t === 'word' && toks[k + 1].end === toks[k].end + toks[k + 1].text.length) || (nx.t === 'word' && /^(else|elseif)$/i.test(nx.text) && /^(if|elseif|else)$/.test(kw)) || (nx.t === 'word' && /^(catch|finally)$/i.test(nx.text) && kw === 'try') || (nx.t === 'word' && /^(while|until)$/i.test(nx.text) && kw === 'do') || (nx.t === 'punc' && nx.text === '{' && BLOCK_KW.test(kw) && !lastIsBlock(toks, s, i)))) { i = k; continue; }
737
+ break;
738
+ }
739
+ i++;
740
+ }
741
+ out.push([s, i]);
742
+ }
743
+ return out;
744
+ }
745
+ function lastIsBlock(toks, s, i) { let k = i - 1; while (k > s && (toks[k].t === 'nl' || toks[k].t === 'comment')) k--; return toks[k]?.text === '}' && !/^(else|try|finally|do)$/i.test(toks[k - 1]?.text ?? ''); }
746
+
747
+ /** Parameters from a param(...) block or a function's own (...) list. */
748
+ function paramsOf(toks) {
749
+ const out = [];
750
+ for (const part of splitCommas(toks)) {
751
+ const v = part.find((t) => t.t === 'var');
752
+ if (!v) continue;
753
+ const type = [...part.slice(0, part.indexOf(v))].reverse().find((t) => t.t === 'type');
754
+ const t = type ? type.name.toLowerCase() : null;
755
+ const eq = part.indexOf(part.find((t2, i) => t2.text === '=' && i > part.indexOf(v)));
756
+ const def = eq > 0 ? part.slice(eq + 1) : null;
757
+ out.push({ name: v.name, type: t ? (/^(int|int32|int64|long|double|decimal|float|single|byte)$/.test(t) ? 'number' : /^(string|char)$/.test(t) ? 'string' : /^(bool|boolean|switch)$/.test(t) ? 'boolean' : type.name) : null, ...(def ? { default: at0(def).map((x) => x.text).join(' ') } : {}), mandatory: part.some((x) => x.t === 'attr' && /Mandatory/i.test(x.text)) });
758
+ }
759
+ return out;
760
+ }
761
+
762
+ /** Comment-based help: .SYNOPSIS (or .DESCRIPTION), else the plain comment lines. */
763
+ function helpText(text) {
764
+ const t = String(text).replace(/^<#|#>$/g, '');
765
+ const m = t.match(/\.SYNOPSIS\s*\n([\s\S]*?)(?:\n\s*\.[A-Z]+\b|$)/i) || t.match(/\.DESCRIPTION\s*\n([\s\S]*?)(?:\n\s*\.[A-Z]+\b|$)/i);
766
+ const body = (m ? m[1] : /^\s*\.[A-Z]/m.test(t) ? '' : t).split('\n').map((l) => l.replace(/^\s*#\s?/, '').trim());
767
+ const para = [];
768
+ for (const l of body) { if (!l) { if (para.length) break; continue; } para.push(l); }
769
+ const s = para.join(' ').replace(/\s+/g, ' ').trim();
770
+ return s ? (s.length > 300 ? `${s.slice(0, 299)}…` : s) : null;
771
+ }
772
+ function docBefore(toks, idx) {
773
+ let k = idx - 1;
774
+ while (k >= 0 && (toks[k].t === 'nl' || toks[k].t === 'attr')) k--;
775
+ if (k < 0 || toks[k].t !== 'comment') return null;
776
+ if (toks[k].block) return helpText(toks[k].text);
777
+ const run = [];
778
+ while (k >= 0 && toks[k].t === 'comment' && !toks[k].block) { run.unshift(toks[k].text); k--; if (toks[k]?.t === 'nl') k--; }
779
+ return helpText(run.join('\n'));
780
+ }
781
+
782
+ function makeReader(src) {
783
+ const toks = tokenize(src);
784
+ const lineAt = lineFinder(src);
785
+ const fns = [], things = [], errors = new Map(), tests = [];
786
+ const code = (s, e) => { const t = src.slice(toks[s].at, toks[e - 1].end).replace(/\s+/g, ' ').trim(); return t.length > 160 ? `${t.slice(0, 159)}…` : t; };
787
+ const head = (s, e) => { const t = src.slice(toks[s].at, toks[e - 1].end).split('\n')[0].trim(); return t.length > 160 ? `${t.slice(0, 159)}…` : t; };
788
+ const spanOf = (s, e) => ({ startLine: lineAt(toks[s].at), endLine: lineAt(toks[e - 1].end - 1) });
789
+ const base = (s, e, c = code(s, e)) => ({ code: c, line: lineAt(toks[s].at), span: spanOf(s, e) });
790
+ const nextTok = (i, to) => { while (i < to && (toks[i].t === 'nl' || toks[i].t === 'comment')) i++; return i; };
791
+ const blockAt = (i, to) => { const k = nextTok(i, to); return toks[k]?.text === '{' && toks[k].match != null ? [k + 1, toks[k].match] : null; };
792
+
793
+ function stepsIn(from, to, ctx = {}) {
794
+ const out = [];
795
+ for (const [s, e] of splitStatements(toks, from, to)) {
796
+ try { out.push(...statement(s, e, ctx)); } catch (err) { if (process.env.PS_DEBUG) console.error(err); out.push({ kind: 'other', says: code(s, e), ...base(s, e) }); }
797
+ }
798
+ return out;
799
+ }
800
+
801
+ function statement(s, e, ctx) {
802
+ const t = toks[s];
803
+ const kw = t.t === 'word' ? t.text.toLowerCase() : '';
804
+ const parenAt = (i) => { const k = nextTok(i, e); return toks[k]?.text === '(' ? k : -1; };
805
+ switch (kw) {
806
+ case 'if': {
807
+ let i = s, first = null, tail = null;
808
+ while (i < e) {
809
+ const w = toks[i].text.toLowerCase();
810
+ if (w === 'if' || w === 'elseif') {
811
+ const p = parenAt(i + 1);
812
+ if (p < 0) break;
813
+ const blk = blockAt(toks[p].match + 1, e);
814
+ if (!blk) break;
815
+ const cond = toks.slice(p + 1, toks[p].match);
816
+ const b = { kind: 'branch', says: `If ${gated(cond, condWords(cond, false)) ?? asCodeWords(code(p + 1, toks[p].match))}`, cond: condJs(cond), code: head(i, blk[1] + 1), line: lineAt(toks[i].at), span: first ? spanOf(i, e) : spanOf(s, e) };
817
+ const kids = stepsIn(blk[0], blk[1], ctx);
818
+ if (kids.length) b.children = kids;
819
+ if (!first) first = b; else { b.elseIf = true; tail.otherwise = [b]; }
820
+ tail = b;
821
+ i = nextTok(blk[1] + 1, e);
822
+ continue;
823
+ }
824
+ if (w === 'else' && tail) {
825
+ const blk = blockAt(i + 1, e);
826
+ if (!blk) break;
827
+ tail.otherwise = stepsIn(blk[0], blk[1], ctx);
828
+ tail.otherwiseLine = lineAt(toks[i].at);
829
+ i = blk[1] + 1;
830
+ continue;
831
+ }
832
+ break;
833
+ }
834
+ return first ? [first] : [{ kind: 'other', says: code(s, e), ...base(s, e) }];
835
+ }
836
+ case 'foreach': {
837
+ const p = parenAt(s + 1);
838
+ if (p < 0) break;
839
+ const inner = at0(toks.slice(p + 1, toks[p].match));
840
+ const inAt = inner.findIndex((x) => /^in$/i.test(x.text));
841
+ const blk = blockAt(toks[p].match + 1, e);
842
+ const kids = blk ? stepsIn(blk[0], blk[1], ctx) : [];
843
+ const what = inAt > 0 ? sayValue(inner.slice(inAt + 1)) ?? `\`${inner.slice(inAt + 1).map((x) => x.text).join(' ')}\`` : 'them';
844
+ return [{ kind: 'loop', says: `For each ${inner[0]?.t === 'var' ? varWords(inner[0].name) : 'item'} in ${what}`, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
845
+ }
846
+ case 'for': {
847
+ const p = parenAt(s + 1);
848
+ if (p < 0) break;
849
+ const parts = []; let cur = [];
850
+ for (const x of toks.slice(p + 1, toks[p].match)) { if (x.text === ';') { parts.push(cur); cur = []; } else cur.push(x); }
851
+ parts.push(cur);
852
+ const blk = blockAt(toks[p].match + 1, e);
853
+ const kids = blk ? stepsIn(blk[0], blk[1], ctx) : [];
854
+ const init = at0(parts[0] || []);
855
+ const cond = parts[1] ? gated(parts[1], condWords(parts[1], false)) ?? (at0(parts[1]).length ? asCodeWords(toksCode(parts[1])) : null) : null;
856
+ const says = init[0]?.t === 'var' && init[1]?.text === '=' ? `Counts ${varWords(init[0].name)} from ${sayValue(init.slice(2)) ?? '…'}${cond ? ` while ${cond}` : ''}` : `Repeats${cond ? ` while ${cond}` : ''}`;
857
+ return [{ kind: 'loop', says, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
858
+ }
859
+ case 'while': {
860
+ const p = parenAt(s + 1);
861
+ if (p < 0) break;
862
+ const blk = blockAt(toks[p].match + 1, e);
863
+ const kids = blk ? stepsIn(blk[0], blk[1], ctx) : [];
864
+ const c = toks.slice(p + 1, toks[p].match);
865
+ const cw = gated(c, condWords(c, false));
866
+ return [{ kind: 'loop', says: cw === 'always' ? 'Repeats until something stops it' : `Repeats while ${cw ?? asCodeWords(code(p + 1, toks[p].match))}`, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
867
+ }
868
+ case 'do': {
869
+ const blk = blockAt(s + 1, e);
870
+ if (!blk) break;
871
+ const k = nextTok(blk[1] + 1, e);
872
+ const until = /^until$/i.test(toks[k]?.text ?? '');
873
+ const p = parenAt(k + 1);
874
+ const ct = p >= 0 ? toks.slice(p + 1, toks[p].match) : null;
875
+ const cw = ct ? gated(ct, condWords(ct, false)) ?? asCodeWords(toksCode(ct)) : null;
876
+ const kids = stepsIn(blk[0], blk[1], ctx);
877
+ return [{ kind: 'loop', says: `Runs once, then repeats ${until ? 'until' : 'while'} ${cw ?? 'a condition holds'}`, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
878
+ }
879
+ case 'switch': {
880
+ let i = s + 1;
881
+ const flags = [];
882
+ while (i < e && (toks[i].t === 'param' || toks[i].t === 'nl')) { if (toks[i].t === 'param') flags.push(toks[i].text.toLowerCase()); i++; }
883
+ const p = parenAt(i);
884
+ const subjectToks = p >= 0 ? toks.slice(p + 1, toks[p].match) : [];
885
+ const blk = blockAt(p >= 0 ? toks[p].match + 1 : i, e);
886
+ if (!blk) break;
887
+ const arms = [];
888
+ let k = blk[0];
889
+ while (k < blk[1]) {
890
+ k = nextTok(k, blk[1]);
891
+ while (k < blk[1] && toks[k].text === ';') k = nextTok(k + 1, blk[1]);
892
+ if (k >= blk[1]) break;
893
+ const patStart = k;
894
+ const pat = toks[k];
895
+ k = pat.match != null ? pat.match + 1 : k + 1;
896
+ const body = blockAt(k, blk[1]);
897
+ if (!body) break;
898
+ const kids = stepsIn(body[0], body[1], ctx);
899
+ const label = /^default$/i.test(pat.text) ? 'Otherwise'
900
+ : pat.text === '{' ? `When ${gated(toks.slice(patStart + 1, pat.match), condWords(toks.slice(patStart + 1, pat.match), false)) ?? asCodeWords(code(patStart + 1, pat.match))}`
901
+ : flags.includes('-regex') ? `When it matches the pattern ${sayValue([pat])}`
902
+ : flags.includes('-wildcard') ? `When it matches ${sayValue([pat])}`
903
+ : `When it is ${sayValue(toks.slice(patStart, k)) ?? pat.text}`;
904
+ arms.push({ kind: 'check', says: label, caseLabel: true, code: head(patStart, body[1] + 1).slice(0, 90), line: lineAt(pat.at), span: spanOf(patStart, body[1] + 1), ...(kids.length ? { children: kids } : {}), _pat: pat });
905
+ k = body[1] + 1;
906
+ }
907
+ for (const a of arms) delete a._pat;
908
+ return [{ kind: 'branch', says: `Chooses by ${sayValue(subjectToks) ?? 'value'}`, ...base(s, e, head(s, e)), ...(arms.length ? { children: arms } : {}) }];
909
+ }
910
+ case 'try': {
911
+ const blk = blockAt(s + 1, e);
912
+ if (!blk) break;
913
+ const step = { kind: 'try', says: 'Tries these steps and handles any error', ...base(s, e, head(s, e)) };
914
+ const kids = stepsIn(blk[0], blk[1], ctx);
915
+ if (kids.length) step.children = kids;
916
+ let i = nextTok(blk[1] + 1, e);
917
+ while (i < e) {
918
+ const w = toks[i].text.toLowerCase();
919
+ if (w === 'catch') {
920
+ const types = [];
921
+ let j = i + 1;
922
+ while (j < e && (toks[j].t === 'type' || toks[j].text === ',' || toks[j].t === 'nl')) { if (toks[j].t === 'type') types.push(toks[j].name.split('.').pop()); j++; }
923
+ const b = blockAt(j, e);
924
+ if (!b) break;
925
+ IN_CATCH++;
926
+ let hs;
927
+ try { hs = stepsIn(b[0], b[1], ctx); } finally { IN_CATCH--; }
928
+ (step.handlers ||= []).push({ says: types.length ? `If ${types.join(' or ')} goes wrong` : 'If anything goes wrong', line: lineAt(toks[i].at), steps: hs });
929
+ i = nextTok(b[1] + 1, e);
930
+ continue;
931
+ }
932
+ if (w === 'finally') {
933
+ const b = blockAt(i + 1, e);
934
+ if (!b) break;
935
+ step.always = { line: lineAt(toks[i].at), steps: stepsIn(b[0], b[1], ctx) };
936
+ i = nextTok(b[1] + 1, e);
937
+ continue;
938
+ }
939
+ break;
940
+ }
941
+ return [step];
942
+ }
943
+ case 'trap': {
944
+ const k = toks[s + 1]?.t === 'type' ? s + 2 : s + 1;
945
+ const blk = blockAt(k, e);
946
+ const kids = blk ? stepsIn(blk[0], blk[1], ctx) : [];
947
+ return [{ kind: 'call', says: 'Whenever an error happens, it runs these steps', ...base(s, e, head(s, e)), ...(kids.length ? { children: kids, nested: true } : {}) }];
948
+ }
949
+ case 'throw': {
950
+ const rest = at0(toks.slice(s + 1, e));
951
+ let name = 'an error', msg = null;
952
+ if (rest[0]?.t === 'str') msg = stringText(rest[0]);
953
+ else if (rest[0]?.t === 'type') { name = rest[0].name.split('.').pop(); const str = rest.find((x) => x.t === 'str'); if (str) msg = stringText(str); }
954
+ else if (/^new-object$/i.test(rest[0]?.text ?? '')) { name = String(rest[1]?.text ?? 'error').split('.').pop(); const str = rest.find((x) => x.t === 'str'); if (str) msg = stringText(str); }
955
+ else if (rest[0]?.t === 'punc' && rest[0].text === '(') { const str = rest.find((x) => x.t === 'str'); const ty = rest.find((x) => x.t === 'type' || /exception$/i.test(x.text)); if (ty) name = (ty.name ?? ty.text).split('.').pop(); if (str) msg = stringText(str); }
956
+ else if (rest[0]?.t === 'var') { if (!rest.length || /^_$/.test(rest[0].name)) return [{ kind: 'fail', says: 'Fails again with the same error', error: 'the same error', ...base(s, e) }]; msg = null; name = varWords(rest[0].name); }
957
+ else if (!rest.length) return [{ kind: 'fail', says: 'Fails again with the same error', error: 'the same error', ...base(s, e) }];
958
+ if (msg) errors.set(msg, errors.get(msg) ?? lineAt(t.at)); else if (name !== 'an error') errors.set(name, errors.get(name) ?? lineAt(t.at));
959
+ return [{ kind: 'fail', says: `Fails with ${name}${msg ? `: "${msg}"` : ''}`, error: name, ...(msg ? { message: msg } : {}), ...base(s, e) }];
960
+ }
961
+ case 'return': {
962
+ const rest = toks.slice(s + 1, e);
963
+ if (!at0(rest).length) return [{ kind: 'return', says: 'Stops here', ...base(s, e) }];
964
+ // `return $(if (…) { a } else { b })`: the choice itself, each side giving back its value.
965
+ const r0 = at0(rest);
966
+ if (r0.length && (r0[0].text === '$(' || r0[0].text === '(') && r0[0].match === r0[r0.length - 1].i) {
967
+ const k = nextTok(r0[0].i + 1, r0[0].match);
968
+ if (/^(if|switch)$/i.test(toks[k]?.text ?? '')) return statement(k, r0[0].match, ctx);
969
+ }
970
+ const v = sayValue(rest);
971
+ return [{ kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', ...(v ? {} : { restates: true }), ...base(s, e), _value: rest }];
972
+ }
973
+ case 'exit': {
974
+ const n = at0(toks.slice(s + 1, e))[0];
975
+ if (!n || n.text === '0') return [{ kind: 'return', says: 'Stops the script here, finished without errors', ...base(s, e) }];
976
+ if (n.t === 'num') return [{ kind: 'fail', says: `Fails with exit code ${n.text}`, error: `exit code ${n.text}`, ...base(s, e) }];
977
+ return [{ kind: 'return', says: `Stops the script with the exit code in ${sayValue([n]) ?? 'a value'}`, ...base(s, e) }];
978
+ }
979
+ case 'break': return [];
980
+ case 'continue': return [{ kind: 'call', says: 'Skips to the next one', ...base(s, e) }];
981
+ case 'function': case 'filter': case 'workflow': {
982
+ defineFunction(s, e);
983
+ return [{ kind: 'set', says: `Defines a helper, ${words(toks[nextTok(s + 1, e)]?.text ?? 'function')}`, ...base(s, e, head(s, e)) }];
984
+ }
985
+ case 'class': case 'enum': defineType(s, e, kw); return [];
986
+ case 'param': case 'using': return [];
987
+ case 'begin': case 'process': case 'end': {
988
+ const blk = blockAt(s + 1, e);
989
+ if (!blk) break;
990
+ const kids = stepsIn(blk[0], blk[1], ctx);
991
+ if (kw === 'process' && kids.length) return [{ kind: 'loop', says: 'For each item given to it', ...base(s, e, head(s, e)), children: kids }];
992
+ return kids;
993
+ }
994
+ default: break;
995
+ }
996
+ if (t.t === 'attr' || t.t === 'comment') { const k = nextTok(s + 1, e); return k < e ? statement(k, e, ctx) : []; }
997
+ // Pode routes: Add-PodeRoute -Method Get -Path '/orders' -ScriptBlock { … }.
998
+ if (/^add-poderoute$/i.test(t.text)) { podeRoute(s, e); return []; }
999
+ if (/^(describe|context|it)$/i.test(t.text) && toks[nextTok(s + 1, e)]?.t === 'str') {
1000
+ const name = stringText(toks[nextTok(s + 1, e)]);
1001
+ const blk = toks.slice(s, e).find((x) => x.text === '{' && x.match != null);
1002
+ if (/^it$/i.test(t.text)) tests.push({ name, line: lineAt(t.at) });
1003
+ else if (blk) stepsIn(blk.i + 1, blk.match, ctx);
1004
+ return [];
1005
+ }
1006
+ return pipelineStatement(s, e, ctx);
1007
+ }
1008
+
1009
+ function pipelineStatement(s, e, ctx) {
1010
+ const list = at0(toks.slice(s, e));
1011
+ // Assignment: $x = …, $x.Y = …, [int]$x = …, $x += …
1012
+ const g = groups(list);
1013
+ const eqAt = g.findIndex((x) => x.length === 1 && x[0].t === 'punc' && /^(=|\+=|-=|\*=|\/=)$/.test(x[0].text));
1014
+ if (eqAt > 0 && g.slice(0, eqAt).every((x) => x[0].t === 'var' || x[0].t === 'type' || x[0].text === '.' || x[0].t === 'word' || x[0].text === '[')) {
1015
+ const lhs = g.slice(0, eqAt).flat().filter((x) => x.t !== 'type');
1016
+ const v = lhs[0];
1017
+ const members = lhs.filter((x, i) => i > 0 && x.t === 'word').map((x) => x.text);
1018
+ const isThis = v?.t === 'var' && /^this$/i.test(v.name);
1019
+ // `$args[0] = …` changes one item, not the whole list.
1020
+ const indexed = lhs.some((x) => x.text === '[');
1021
+ const target = indexed ? sayValue(lhs) : v?.t === 'var' ? (isThis ? (members.length ? words(members[members.length - 1]) : 'it') : chainWords(varWords(v.name), members)) : 'a value';
1022
+ if (!target) return [{ kind: 'other', says: code(s, e), ...base(s, e) }];
1023
+ const op = g[eqAt][0].text;
1024
+ let rhs = g.slice(eqAt + 1).flat();
1025
+ // `$null = …` runs it and throws the answer away.
1026
+ if (v?.t === 'var' && /^null$/i.test(v.name) && op === '=') {
1027
+ const pw0 = rhs[0]?.t === 'word' || rhs[0]?.text === '&' ? pipelineWords(rhs) : null;
1028
+ const said = pw0?.command ? pw0.says : sayValue(rhs) ? `Works out ${sayValue(rhs)}` : null;
1029
+ return [{ kind: 'call', says: said ? `${said}, ignoring the answer` : code(s, e), ...(said ? {} : { restates: true }), ...base(s, e) }];
1030
+ }
1031
+ // `$a = $b = $false`: every name gets the same value.
1032
+ const more = [];
1033
+ for (let rg = groups(rhs), at = rg.findIndex((x) => x.length === 1 && x[0].text === '='); at > 0 && rg[0][0].t === 'var'; rg = groups(rhs), at = rg.findIndex((x) => x.length === 1 && x[0].text === '=')) {
1034
+ more.push(varWords(rg[0][0].name));
1035
+ rhs = rg.slice(at + 1).flat();
1036
+ }
1037
+ if (more.length) { const val = sayValue(rhs); return [{ kind: 'set', says: `Sets ${listWords([target, ...more])} to ${val ?? 'a computed value'}`, ...(val ? {} : { restates: true }), ...base(s, e) }]; }
1038
+ if (/^\$?ErrorActionPreference$/i.test(v?.name ?? '') && /stop/i.test(rhs.map((x) => x.text).join(''))) return [{ kind: 'set', says: 'Stops at the first error', ...base(s, e) }];
1039
+ if (op === '+=' || op === '-=') { const val = sayValue(rhs); return [{ kind: 'set', says: `${op === '+=' ? 'Adds' : 'Subtracts'} ${val ?? 'a value'} ${op === '+=' ? 'to' : 'from'} ${target}`, ...base(s, e) }]; }
1040
+ if (isThis && rhs.length === 1 && rhs[0].t === 'var' && rhs[0].name.toLowerCase() === String(members[members.length - 1]).toLowerCase()) return [{ kind: 'set', says: `Keeps the ${target} it is given`, ...base(s, e) }];
1041
+ const piped = groups(rhs).some((x) => x.length === 1 && x[0].text === '|');
1042
+ const pw = rhs[0]?.t === 'word' || rhs[0]?.text === '&' || piped ? pipelineWords(rhs) : null;
1043
+ if (pw?.loop) {
1044
+ // `$x = $list | ForEach-Object { … }`: the steps run for each one, and their results become x.
1045
+ const kids = stepsIn(pw.loop.from, pw.loop.to, ctx);
1046
+ const says = pw.loop.middle ? `${pw.says}, keeping the result as ${target}` : `For each ${pw.value ? `one in ${pw.value}` : `result of ${gerund(pw.says)}`}, runs the steps below; the results become ${target}`;
1047
+ return [{ kind: 'loop', says, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
1048
+ }
1049
+ if (pw?.command || (piped && pw)) return [{ kind: 'set', says: `${pw.says}, keeping the result as ${target}`, ...(rhs[0].t === 'word' ? { callee: rhs[0].text } : {}), ...base(s, e) }];
1050
+ const ifV = rhs[0]?.t === 'word' && /^(if|switch|foreach|try)$/i.test(rhs[0].text);
1051
+ if (ifV) { const inner = statement(rhs[0].i, e, ctx); return inner.map((x) => ({ ...x, says: `${x.says} (the answer becomes ${target})` })); }
1052
+ const val = sayValue(rhs);
1053
+ if (val === 'an empty list' || val === 'an empty table') return [{ kind: 'set', says: `Starts ${target} as ${val}`, ...base(s, e) }];
1054
+ return [{ kind: 'set', says: val ? `Sets ${target} to ${val}` : `Works out ${target}`, ...(val ? {} : { restates: true }), ...base(s, e) }];
1055
+ }
1056
+ if (g.length === 2 && g[0][0].t === 'var' && (g[1][0].text === '++' || g[1][0].text === '--')) return [{ kind: 'set', says: `${g[1][0].text === '++' ? 'Adds one to' : 'Subtracts one from'} ${varWords(g[0][0].name)}`, ...base(s, e) }];
1057
+ const head0 = list[0];
1058
+ const lower = head0?.t === 'word' ? head0.text.toLowerCase() : '';
1059
+ if (/^write-error$/.test(lower)) {
1060
+ const a = argsOf(list.slice(1));
1061
+ const msg = a.named.message ? sayValue(a.named.message) : a.pos[0] ? sayValue(a.pos[0]) : null;
1062
+ const text = msg ? msg.replace(/^"|"$/g, '') : null;
1063
+ const stops = STOP_ON_ERROR || /stop/i.test(a.named.erroraction?.map((x) => x.text).join('') ?? '');
1064
+ if (text) errors.set(text, errors.get(text) ?? lineAt(head0.at));
1065
+ return [stops ? { kind: 'fail', says: `Fails with an error${text ? `: "${text}"` : ''}`, error: 'an error', ...(text ? { message: text } : {}), ...base(s, e) } : { kind: 'call', says: `Reports an error${text ? `: "${text}"` : ''} and carries on`, ...base(s, e) }];
1066
+ }
1067
+ // A command given a script block (`Invoke-Command { … }`, `Measure-Command { … }`): the block's steps are read.
1068
+ const lg = groups(list);
1069
+ const lastBlock = lg[lg.length - 1];
1070
+ if (head0?.t === 'word' && lg.length > 1 && !lg.some((x) => x.length === 1 && x[0].text === '|') && lastBlock[0].text === '{' && lastBlock[0].match != null && !/^(foreach-object|where-object|foreach|where)$/i.test(head0.text)) {
1071
+ const said = commandWords(list.slice(0, list.length - lastBlock.length)) ?? `Runs ${head0.text}`;
1072
+ const kids = stepsIn(lastBlock[0].i + 1, lastBlock[0].match, ctx);
1073
+ return [{ kind: 'call', says: /these steps/.test(said) ? said : `${said}, with these steps`, callee: head0.text, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
1074
+ }
1075
+ const pw = pipelineWords(list);
1076
+ if (pw?.loop) {
1077
+ const kids = pw.loop.to != null ? stepsIn(pw.loop.from, pw.loop.to, ctx) : [];
1078
+ const says = pw.loop.middle ? pw.says : pw.value ? `For each one in ${pw.value}` : pw.says ? `For each result of ${gerund(pw.says)}` : 'For each one';
1079
+ return [{ kind: 'loop', says, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
1080
+ }
1081
+ if (pw) {
1082
+ if (!pw.command) {
1083
+ // `$list.Add(x)`, `$sb.Append(x)`: a method that changes something reads as what it does, not as an answer.
1084
+ const mg = groups(list);
1085
+ const lastG = mg[mg.length - 1];
1086
+ if (mg.length >= 4 && lastG[0].text === '(' && mg[mg.length - 3][0].text === '.' && mg[mg.length - 2][0].t === 'word' && (mg[0][0].t === 'var' || mg[0][0].t === 'type')) {
1087
+ const method = mg[mg.length - 2][0].text;
1088
+ const owner = sayValue(mg.slice(0, -3).flat()) ?? 'it';
1089
+ const arg = splitCommas(lastG.slice(1, -1)).map((x) => sayValue(x) ?? 'a value');
1090
+ const said = /^(add|push|enqueue|append|appendline|insert)$/i.test(method) ? `Adds ${listWords(arg) || 'a line'} to ${owner}`
1091
+ : /^(remove|removeat|pop|dequeue)$/i.test(method) ? `Removes ${listWords(arg) || 'one'} from ${owner}`
1092
+ : /^clear$/i.test(method) ? `Empties ${owner}` : /^(dispose|close)$/i.test(method) ? `Closes ${owner}` : `Calls ${words(method)} on ${owner}`;
1093
+ return [{ kind: 'call', says: said, callee: method, ...base(s, e) }];
1094
+ }
1095
+ // A bare value is output: in a function it is part of what it gives back.
1096
+ const said = /^"/.test(pw.says) || /^[A-Z][a-z]*[A-Z]/.test(pw.says) ? pw.says : pw.says.charAt(0).toLowerCase() + pw.says.slice(1);
1097
+ return [{ kind: 'return', says: `Returns ${said}`, implicit: true, ...base(s, e), _value: toks.slice(s, e) }];
1098
+ }
1099
+ const callee = head0?.t === 'word' ? head0.text : undefined;
1100
+ // New-Object on its own line is output: the function gives the new object back.
1101
+ if (/^new-object$/i.test(lower) && groups(list).every((x) => x[0].text !== '|')) return [{ kind: 'return', says: `Returns ${pw.says.replace(/^Makes /, '')}`, implicit: true, ...base(s, e) }];
1102
+ return [{ kind: 'call', says: pw.says, ...(callee ? { callee } : {}), ...base(s, e) }];
1103
+ }
1104
+ return [{ kind: 'other', says: code(s, e), ...base(s, e) }];
1105
+ }
1106
+
1107
+ // ── Functions, classes, routes ──
1108
+ function bodyParts(from, to) {
1109
+ let params = [];
1110
+ let k = nextTok(from, to);
1111
+ while (k < to && (toks[k].t === 'attr' || toks[k].t === 'nl' || toks[k].t === 'comment')) k++;
1112
+ if (/^param$/i.test(toks[k]?.text ?? '')) { const p = nextTok(k + 1, to); if (toks[p]?.text === '(') { params = paramsOf(toks.slice(p + 1, toks[p].match)); k = toks[p].match + 1; } }
1113
+ return { params, from: k };
1114
+ }
1115
+ function lastValueToReturn(list) {
1116
+ // PowerShell outputs a bare value; the function's last one is the answer it gives back.
1117
+ const last = list[list.length - 1];
1118
+ if (!last) return;
1119
+ if (last.kind === 'branch') { for (const side of [last.children, last.otherwise]) lastValueToReturn(side || []); for (const c of last.children || []) if (c.caseLabel) lastValueToReturn(c.children || []); }
1120
+ }
1121
+ function cleanSteps(list) { for (const s of list || []) { delete s._value; delete s.implicit; cleanSteps(s.children); cleanSteps(s.otherwise); for (const h of s.handlers || []) cleanSteps(h.steps); if (s.always) cleanSteps(s.always.steps); } return list; }
1122
+
1123
+ function defineFunction(s, e) {
1124
+ const k = nextTok(s + 1, e);
1125
+ const nameTok = toks[k];
1126
+ if (!nameTok) return;
1127
+ const name = nameTok.text.replace(/^(?:script|global|local):/i, '');
1128
+ let i = nextTok(k + 1, e), params = [];
1129
+ if (toks[i]?.text === '(') { params = paramsOf(toks.slice(i + 1, toks[i].match)); i = toks[i].match + 1; }
1130
+ const blk = blockAt(i, e);
1131
+ if (!blk) return;
1132
+ const parts = bodyParts(blk[0], blk[1]);
1133
+ if (parts.params.length) params = parts.params;
1134
+ const inner = toks.slice(blk[0], blk[1]).find((x) => x.t === 'comment' && x.block && /\.SYNOPSIS|\.DESCRIPTION/i.test(x.text));
1135
+ const doc = docBefore(toks, s) ?? (inner ? helpText(inner.text) : null);
1136
+ const steps = stepsIn(parts.from, blk[1]);
1137
+ if (!steps.length) steps.push({ kind: 'return', says: 'Does nothing', ...base(s, e, head(s, e)) });
1138
+ lastValueToReturn(steps);
1139
+ const first = nextTok(parts.from, blk[1]);
1140
+ fns.push({ name, line: lineAt(nameTok.at), params, doc, steps, body: first < blk[1] ? [lineAt(toks[first].at), lineAt(toks[blk[1]].at)] : null, _range: [parts.from, blk[1]] });
1141
+ }
1142
+
1143
+ function podeRoute(s, e) {
1144
+ const a = argsOf(toks.slice(s + 1, e));
1145
+ const method = String(a.named.method ? at0(a.named.method)[0]?.text ?? 'GET' : 'GET').replace(/['"]/g, '').toUpperCase();
1146
+ const pathTok = a.named.path ? at0(a.named.path)[0] : null;
1147
+ const path = pathTok ? (pathTok.t === 'str' ? stringText(pathTok) : pathTok.text) : '/';
1148
+ const sb = a.named.scriptblock;
1149
+ if (!sb || sb[0].text !== '{') return;
1150
+ const open = sb[0].i;
1151
+ fns.push({ name: `${method} ${path}`, line: lineAt(toks[s].at), params: [], route: { method, path }, steps: stepsIn(open + 1, sb[0].match), body: [lineAt(toks[nextTok(open + 1, sb[0].match)]?.at ?? toks[open].at), lineAt(toks[sb[0].match].at)] });
1152
+ }
1153
+
1154
+ function defineType(s, e, kw) {
1155
+ const nameTok = toks[nextTok(s + 1, e)];
1156
+ const blk = toks.slice(s, e).find((x) => x.text === '{' && x.match != null);
1157
+ if (!nameTok || !blk) return;
1158
+ const open = blk.i, close = blk.match;
1159
+ const lines = [lineAt(toks[s].at), lineAt(toks[close].at)];
1160
+ const doc = docBefore(toks, s);
1161
+ if (kw === 'enum') {
1162
+ const choices = [];
1163
+ for (const [a] of splitStatements(toks, open + 1, close)) if (toks[a].t === 'word') choices.push(words(toks[a].text));
1164
+ things.push({ kind: 'choices', name: nameTok.text, lines, ...(doc ? { doc } : {}), knows: [], choices });
1165
+ return;
1166
+ }
1167
+ const thing = { kind: 'thing', name: nameTok.text, lines, ...(doc ? { doc } : {}), knows: [], choices: [], methods: 0 };
1168
+ for (const [a, b] of splitStatements(toks, open + 1, close)) {
1169
+ const st = at0(toks.slice(a, b)).filter((x) => x.t !== 'attr' && !/^(hidden|static)$/i.test(x.text));
1170
+ const v = st.findIndex((x) => x.t === 'var');
1171
+ const paren = st.findIndex((x) => x.text === '(');
1172
+ if (v >= 0 && (paren < 0 || paren > v)) {
1173
+ const type = st.slice(0, v).reverse().find((x) => x.t === 'type');
1174
+ const eq = st.findIndex((x, i) => i > v && x.text === '=');
1175
+ const def = eq > 0 ? st.slice(eq + 1) : null;
1176
+ thing.knows.push({ name: st[v].name, type: type?.name ?? null, start: def ? def.map((x) => x.text).join(' ') : null, line: lineAt(st[v].at) });
1177
+ continue;
1178
+ }
1179
+ // A method: [returnType] Name(params) { … }, or the constructor Name(params) { … }.
1180
+ const nameAt = st.findIndex((x, i) => x.t === 'word' && st[i + 1]?.text === '(');
1181
+ if (nameAt < 0) continue;
1182
+ const mTok = st[nameAt];
1183
+ const pOpen = st[nameAt + 1];
1184
+ const body = st.slice(nameAt).find((x) => x.text === '{' && x.match != null);
1185
+ if (!body) continue;
1186
+ const params = paramsOf(toks.slice(pOpen.i + 1, pOpen.match));
1187
+ const bOpen = body.i;
1188
+ const steps = stepsIn(bOpen + 1, body.match);
1189
+ if (!steps.length) steps.push({ kind: 'return', says: 'Does nothing', ...base(mTok.i, body.match + 1, head(mTok.i, body.match + 1)) });
1190
+ const first = nextTok(bOpen + 1, body.match);
1191
+ const ret = st.slice(0, nameAt).reverse().find((x) => x.t === 'type');
1192
+ if (mTok.text !== nameTok.text) thing.methods++;
1193
+ fns.push({ name: mTok.text, line: lineAt(mTok.at), params, returns: ret && !/^void$/i.test(ret.name) ? ret.name : null, doc: docBefore(toks, st[0].i), steps, body: first < body.match ? [lineAt(toks[first].at), lineAt(toks[body.match].at)] : null, _range: [bOpen + 1, body.match] });
1194
+ if (mTok.text === nameTok.text) {
1195
+ // Starting values from the constructor: $this.X = $x (a parameter) or a fixed value.
1196
+ for (const [x, y] of splitStatements(toks, bOpen + 1, body.match)) {
1197
+ const st2 = at0(toks.slice(x, y));
1198
+ if (!(st2[0]?.t === 'var' && /^this$/i.test(st2[0].name) && st2[1]?.text === '.' && st2[3]?.text === '=')) continue;
1199
+ const k2 = thing.knows.find((kk) => kk.name.toLowerCase() === st2[2].text.toLowerCase());
1200
+ const val = st2.slice(4);
1201
+ const param = val.length === 1 && val[0].t === 'var' ? params.find((p) => p.name.toLowerCase() === val[0].name.toLowerCase()) : null;
1202
+ const start = param ? (param.default ? { param: param.default } : { given: true }) : val.map((q) => q.text).join(' ');
1203
+ if (k2) { if (k2.start == null || param) k2.start = start; } else thing.knows.push({ name: st2[2].text, type: null, start, line: lineAt(st2[0].at) });
1204
+ }
1205
+ }
1206
+ }
1207
+ if (!thing.methods) thing.kind = 'record';
1208
+ delete thing.methods;
1209
+ things.push(thing);
1210
+ }
1211
+
1212
+ return { toks, fns, things, errors, tests, stepsIn, lineAt, splitStatements: () => splitStatements(toks, 0, toks.length), statement, nextTok, code, cleanSteps };
1213
+ }
1214
+
1215
+ // ── Decisions: a function that only chooses between fixed answers ─────────────────────────────────────────
1216
+
1217
+ const fixedOf = (toks) => {
1218
+ const v = at0(toks || []);
1219
+ if (v.length !== 1) return null;
1220
+ const t = v[0];
1221
+ if (t.t === 'str' && !(t.quote === '"' && /\$/.test(t.body))) return JSON.stringify(t.quote === "'" ? t.body.replace(/''/g, "'") : t.body);
1222
+ if (t.t === 'num' && /^-?\d+(\.\d+)?$/.test(t.text)) return t.text;
1223
+ if (t.t === 'var' && /^(true|false)$/i.test(t.name)) return t.name.toLowerCase();
1224
+ return null;
1225
+ };
1226
+
1227
+ /**
1228
+ * Rules from the function's statements when every path ends in a fixed answer: `if (…) { 'A' } elseif … else { 'C' }`,
1229
+ * guards `if (…) { return 'A' }` before a last answer, or a `switch` whose cases each give one. Null otherwise.
1230
+ */
1231
+ function decisionOf(r, from, to, subjectNames) {
1232
+ const stmts = r.splitStatements ? splitStatements(r.toks, from, to) : [];
1233
+ const toks = r.toks;
1234
+ const valueOfBlock = (a, b) => {
1235
+ const st = splitStatements(toks, a, b);
1236
+ if (st.length !== 1) return null;
1237
+ let [x, y] = st[0];
1238
+ if (/^return$/i.test(toks[x].text)) x++;
1239
+ return fixedOf(toks.slice(x, y));
1240
+ };
1241
+ const rules = [];
1242
+ let otherwise = null;
1243
+ const nextTok = r.nextTok;
1244
+ const blockAt = (i, e) => { const k = nextTok(i, e); return toks[k]?.text === '{' && toks[k].match != null ? [k + 1, toks[k].match] : null; };
1245
+ for (let n = 0; n < stmts.length; n++) {
1246
+ const [s, e] = stmts[n];
1247
+ const kw = toks[s].text.toLowerCase();
1248
+ const isLast = n === stmts.length - 1;
1249
+ if (toks[s].t === 'attr' || /^param$/i.test(kw)) continue;
1250
+ if (kw === 'if') {
1251
+ let i = s;
1252
+ const local = [];
1253
+ let fb = null, ok = true;
1254
+ while (i < e) {
1255
+ const w = toks[i].text.toLowerCase();
1256
+ if (w === 'if' || w === 'elseif') {
1257
+ const p = nextTok(i + 1, e);
1258
+ if (toks[p]?.text !== '(') { ok = false; break; }
1259
+ const blk = blockAt(toks[p].match + 1, e);
1260
+ if (!blk) { ok = false; break; }
1261
+ const cond = condJs(toks.slice(p + 1, toks[p].match));
1262
+ const val = valueOfBlock(blk[0], blk[1]);
1263
+ if (!cond || !val) { ok = false; break; }
1264
+ local.push({ cond, result: val, line: r.lineAt(toks[i].at) });
1265
+ i = nextTok(blk[1] + 1, e);
1266
+ continue;
1267
+ }
1268
+ if (w === 'else') { const blk = blockAt(i + 1, e); const val = blk ? valueOfBlock(blk[0], blk[1]) : null; if (!val) { ok = false; break; } fb = { result: val, line: r.lineAt(toks[i].at) }; i = blk[1] + 1; continue; }
1269
+ break;
1270
+ }
1271
+ if (!ok) return null;
1272
+ rules.push(...local);
1273
+ if (fb) { if (!isLast) return null; otherwise = fb; }
1274
+ continue;
1275
+ }
1276
+ if (kw === 'switch' && isLast) {
1277
+ let i = s + 1;
1278
+ while (toks[i]?.t === 'param' || toks[i]?.t === 'nl') { if (toks[i].t === 'param' && !/^-exact$/i.test(toks[i].text)) return null; i++; }
1279
+ const p = nextTok(i, e);
1280
+ if (toks[p]?.text !== '(') return null;
1281
+ const subj = condJs(toks.slice(p + 1, toks[p].match));
1282
+ if (!subj || /\s/.test(subj)) return null;
1283
+ const blk = blockAt(toks[p].match + 1, e);
1284
+ if (!blk) return null;
1285
+ let k = blk[0];
1286
+ while (k < blk[1]) {
1287
+ k = nextTok(k, blk[1]);
1288
+ if (k >= blk[1]) break;
1289
+ const pat = toks[k];
1290
+ const body = blockAt(k + 1, blk[1]);
1291
+ if (!body) return null;
1292
+ const val = valueOfBlock(body[0], body[1]);
1293
+ if (!val) return null;
1294
+ if (/^default$/i.test(pat.text)) otherwise = { result: val, line: r.lineAt(pat.at) };
1295
+ else { const pv = fixedOf([pat]) ?? (pat.t === 'word' && /^\w+$/.test(pat.text) ? JSON.stringify(pat.text) : null); if (!pv) return null; rules.push({ cond: `${subj} == ${pv}`, result: val, line: r.lineAt(pat.at) }); }
1296
+ k = body[1] + 1;
1297
+ }
1298
+ continue;
1299
+ }
1300
+ if (isLast) {
1301
+ let x = s;
1302
+ if (/^return$/i.test(kw)) x++;
1303
+ const val = fixedOf(toks.slice(x, e));
1304
+ if (!val) return null;
1305
+ otherwise = { result: val, line: r.lineAt(toks[s].at) };
1306
+ continue;
1307
+ }
1308
+ return null;
1309
+ }
1310
+ return rules.length && otherwise ? { rules, otherwise } : null;
1311
+ }
1312
+
1313
+ /** Read a PowerShell file into functions (with steps or decision rules), Things, errors, and Pester tests. */
1314
+ export function powershellReading(src, file = '') {
1315
+ STOP_ON_ERROR = /\$ErrorActionPreference\s*=\s*['"]Stop['"]/i.test(src);
1316
+ KNOWN_FNS = new Set([...src.matchAll(/^\s*(?:function|filter)\s+(?:(?:script|global):)?([\w-]+)/gim)].map((m) => m[1].toLowerCase()));
1317
+ const r = makeReader(src);
1318
+ const top = [];
1319
+ const scriptParams = [];
1320
+ for (const [s, e] of r.splitStatements()) {
1321
+ const t = r.toks[s];
1322
+ if (/^param$/i.test(t.text)) { const p = r.nextTok(s + 1, e); if (r.toks[p]?.text === '(') scriptParams.push(...paramsOf(r.toks.slice(p + 1, r.toks[p].match))); continue; }
1323
+ const st = r.statement(s, e, {});
1324
+ if (/^(function|filter|workflow)$/i.test(t.text)) continue;
1325
+ for (const x of st) if (x.code && !/^(Set-StrictMode|#requires|using)\b/i.test(x.code)) top.push(x);
1326
+ }
1327
+ for (const f of r.fns) {
1328
+ if (f._range) {
1329
+ const d = decisionOf(r, f._range[0], f._range[1]);
1330
+ if (d) f.decision = d;
1331
+ delete f._range;
1332
+ }
1333
+ r.cleanSteps(f.steps);
1334
+ }
1335
+ const fns = [...r.fns];
1336
+ const real = top.filter((x) => !/^(Export-ModuleMember|Set-StrictMode)\b/i.test(x.code ?? ''));
1337
+ if (real.length) {
1338
+ r.cleanSteps(real);
1339
+ const name = file ? String(file).split(/[\\/]/).pop() : 'script';
1340
+ const firstBlock = r.toks.find((x) => x.t !== 'nl');
1341
+ const doc = firstBlock?.t === 'comment' ? helpText(firstBlock.block ? firstBlock.text : r.toks.filter((x, i) => i < 40 && x.t === 'comment' && !x.block && x.at < (r.toks.find((y) => y.t !== 'comment' && y.t !== 'nl')?.at ?? 0)).map((x) => x.text).join('\n')) : null;
1342
+ fns.push({ name, line: real[0].line, params: scriptParams, doc, steps: real, body: [real[0].span.startLine, real[real.length - 1].span.endLine], topLevel: true, headline: `Runs ${name}, from top to bottom.` });
1343
+ }
1344
+ fns.sort((a, b) => a.line - b.line);
1345
+ const out = { fns, things: r.things, errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
1346
+ STOP_ON_ERROR = false; KNOWN_FNS = new Set();
1347
+ return out;
1348
+ }
1349
+
1350
+ /** Things (classes) and Choices (enums) from a PowerShell file, in the model's shape. */
1351
+ export function psThings(src, file, { words: w, kindWords, startValue }) {
1352
+ const { things } = powershellReading(src, file);
1353
+ const norm = (v) => String(v ?? '').trim().replace(/^@\(\s*\)$/, '[]').replace(/^@\{\s*\}$/, '{}').replace(/^\$null$/i, 'null').replace(/^\$true$/i, 'true').replace(/^\$false$/i, 'false').replace(/^'(.*)'$/, '"$1"');
1354
+ const kind = (t) => { const x = String(t ?? '').toLowerCase(); if (!x) return null; if (/\[\]$/.test(x)) return kindWords(`List<${String(t).slice(0, -2).replace(/^string$/i, 'string').replace(/^int$/i, 'int')}>`); if (/(?:arraylist|list|collection|hashset)(?:\[|$)/.test(x)) return 'a list'; if (/^(?:hashtable|dictionary|ordered)/.test(x)) return 'a lookup table'; return kindWords(/^(int|int32|int64|long|double|decimal|float)$/.test(x) ? 'int' : /^(string|char)$/.test(x) ? 'string' : /^(bool|boolean|switch)$/.test(x) ? 'bool' : /^datetime$/.test(x) ? 'DateTime' : String(t).split('.').pop()); };
1355
+ return things.map((t) => ({
1356
+ kind: t.kind, name: t.name, file, lines: t.lines, ...(t.doc ? { doc: t.doc } : {}), choices: t.choices,
1357
+ knows: t.knows.map((k) => ({ name: k.name, label: w(k.name), kind: kind(k.type), start: k.start == null ? null : typeof k.start === 'object' ? (k.start.given ? 'given when it starts' : `${startValue(norm(k.start.param))?.replace(/ at first$/, '')} unless told otherwise`) : startValue(norm(k.start)), line: k.line })),
1358
+ }));
1359
+ }
1360
+
1361
+ export { cap };