@glassbox-ai/engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +31 -2
  3. package/dist/action/acc.d.ts +48 -0
  4. package/dist/action/acc.js +117 -0
  5. package/dist/action/inline.d.ts +14 -0
  6. package/dist/action/inline.js +54 -0
  7. package/dist/action/paths.d.ts +71 -0
  8. package/dist/action/paths.js +398 -0
  9. package/dist/action/powershell.d.ts +9 -0
  10. package/dist/action/powershell.js +848 -0
  11. package/dist/action/protected-write.d.ts +11 -0
  12. package/dist/action/protected-write.js +113 -0
  13. package/dist/action/schedule.d.ts +43 -0
  14. package/dist/action/schedule.js +213 -0
  15. package/dist/action/shell/analyze.d.ts +28 -0
  16. package/dist/action/shell/analyze.js +2030 -0
  17. package/dist/action/shell/parse.d.ts +74 -0
  18. package/dist/action/shell/parse.js +1037 -0
  19. package/dist/action/shell/view.d.ts +6 -0
  20. package/dist/action/shell/view.js +89 -0
  21. package/dist/action/sql.d.ts +3 -0
  22. package/dist/action/sql.js +259 -0
  23. package/dist/action/tools.d.ts +20 -0
  24. package/dist/action/tools.js +240 -0
  25. package/dist/action/upload.d.ts +17 -0
  26. package/dist/action/upload.js +72 -0
  27. package/dist/analysis/fields.d.ts +14 -0
  28. package/dist/analysis/fields.js +136 -0
  29. package/dist/analysis/findings.d.ts +25 -0
  30. package/dist/analysis/findings.js +82 -0
  31. package/dist/analysis/gate.d.ts +16 -0
  32. package/dist/analysis/gate.js +660 -0
  33. package/dist/analysis/manifest.d.ts +3 -0
  34. package/dist/analysis/manifest.js +369 -0
  35. package/dist/analysis/match.d.ts +54 -0
  36. package/dist/analysis/match.js +352 -0
  37. package/dist/analysis/scan.d.ts +17 -0
  38. package/dist/analysis/scan.js +97 -0
  39. package/dist/canon/confusables.generated.d.ts +3 -0
  40. package/dist/canon/confusables.generated.js +6 -0
  41. package/dist/canon/decode.d.ts +11 -0
  42. package/dist/canon/decode.js +147 -0
  43. package/dist/canon/views.d.ts +36 -0
  44. package/dist/canon/views.js +283 -0
  45. package/dist/evidence/evidence.d.ts +12 -0
  46. package/dist/evidence/evidence.js +149 -0
  47. package/dist/fingerprint/diff.d.ts +3 -0
  48. package/dist/fingerprint/diff.js +273 -0
  49. package/dist/fingerprint/fingerprint.d.ts +4 -0
  50. package/dist/fingerprint/fingerprint.js +77 -0
  51. package/dist/grade/score.d.ts +19 -0
  52. package/dist/grade/score.js +89 -0
  53. package/dist/index.d.ts +22 -0
  54. package/dist/index.js +148 -0
  55. package/dist/intake/json.d.ts +17 -0
  56. package/dist/intake/json.js +284 -0
  57. package/dist/intake/snapshot.d.ts +14 -0
  58. package/dist/intake/snapshot.js +130 -0
  59. package/dist/limits.d.ts +4 -0
  60. package/dist/limits.js +30 -0
  61. package/dist/policy/decide.d.ts +26 -0
  62. package/dist/policy/decide.js +74 -0
  63. package/dist/rules/ids.d.ts +2 -0
  64. package/dist/rules/ids.js +99 -0
  65. package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
  66. package/dist/ruleset/baseline-tests.generated.js +2935 -0
  67. package/dist/ruleset/baseline.d.ts +3 -0
  68. package/dist/ruleset/baseline.generated.d.ts +3 -0
  69. package/dist/ruleset/baseline.generated.js +5 -0
  70. package/dist/ruleset/baseline.js +44 -0
  71. package/dist/ruleset/fakes.d.ts +3 -0
  72. package/dist/ruleset/fakes.js +26 -0
  73. package/dist/ruleset/load.d.ts +14 -0
  74. package/dist/ruleset/load.js +173 -0
  75. package/dist/ruleset/schema.d.ts +120 -0
  76. package/dist/ruleset/schema.js +54 -0
  77. package/dist/ruleset/selftest.d.ts +18 -0
  78. package/dist/ruleset/selftest.js +42 -0
  79. package/dist/ruleset-entry.d.ts +5 -0
  80. package/dist/ruleset-entry.js +7 -0
  81. package/dist/secrets/detect.d.ts +17 -0
  82. package/dist/secrets/detect.js +236 -0
  83. package/dist/secrets/redact.d.ts +19 -0
  84. package/dist/secrets/redact.js +116 -0
  85. package/dist/types.d.ts +434 -0
  86. package/dist/types.js +10 -0
  87. package/dist/util/hash.d.ts +4 -0
  88. package/dist/util/hash.js +16 -0
  89. package/dist/util/initclock.d.ts +3 -0
  90. package/dist/util/initclock.js +17 -0
  91. package/dist/util/jcs.d.ts +4 -0
  92. package/dist/util/jcs.js +91 -0
  93. package/dist/util/misc.d.ts +17 -0
  94. package/dist/util/misc.js +77 -0
  95. package/dist/util/re.d.ts +14 -0
  96. package/dist/util/re.js +47 -0
  97. package/dist/version.d.ts +2 -0
  98. package/dist/version.js +2 -0
  99. package/package.json +55 -3
@@ -0,0 +1,1037 @@
1
+ // Hand-written bash/sh parser (engine-spec §7.3, Q2). Recursive descent over a defined
2
+ // subset, bounded (bytes, nesting, tokens). Anything outside the subset → unanalyzable.
3
+ export const MAX_NESTING = 8;
4
+ export const MAX_TOKENS = 4096;
5
+ export class Unanalyzable extends Error {
6
+ reason;
7
+ constructor(reason) {
8
+ super(reason);
9
+ this.reason = reason;
10
+ }
11
+ }
12
+ const META = new Set([" ", "\t", "\n", ";", "&", "|", "(", ")", "<", ">"]);
13
+ const RESERVED_UNSUPPORTED = new Set(["case", "esac", "select", "coproc", "until_unsupported"]);
14
+ function isNameStart(c) {
15
+ return c !== undefined && ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_");
16
+ }
17
+ function isNameChar(c) {
18
+ return isNameStart(c) || (c !== undefined && c >= "0" && c <= "9");
19
+ }
20
+ export function parseShell(src, opts = { maxBytes: 16 * 1024 }) {
21
+ if (src.length > opts.maxBytes)
22
+ throw new Unanalyzable("command longer than the analysis limit");
23
+ const p = new Parser(src, 0);
24
+ const script = p.parseScript(null);
25
+ if (p.i < src.length)
26
+ throw new Unanalyzable(`unexpected '${src[p.i]}'`);
27
+ return script;
28
+ }
29
+ class Parser {
30
+ src;
31
+ depth;
32
+ i = 0;
33
+ tokens = 0;
34
+ pendingHeredocs = [];
35
+ constructor(src, depth) {
36
+ this.src = src;
37
+ this.depth = depth;
38
+ if (depth > MAX_NESTING)
39
+ throw new Unanalyzable("nesting too deep");
40
+ }
41
+ peek(k = 0) { return this.src[this.i + k]; }
42
+ bump() { if (++this.tokens > MAX_TOKENS)
43
+ throw new Unanalyzable("too many tokens"); }
44
+ /** Skip blanks and comments (not newlines). Handles line continuations. */
45
+ blanks() {
46
+ while (this.i < this.src.length) {
47
+ const c = this.src[this.i];
48
+ if (c === " " || c === "\t") {
49
+ this.i++;
50
+ continue;
51
+ }
52
+ if (c === "\\" && this.src[this.i + 1] === "\n") {
53
+ this.i += 2;
54
+ continue;
55
+ }
56
+ if (c === "#") {
57
+ while (this.i < this.src.length && this.src[this.i] !== "\n")
58
+ this.i++;
59
+ continue;
60
+ }
61
+ break;
62
+ }
63
+ }
64
+ newline() {
65
+ if (this.src[this.i] !== "\n")
66
+ return false;
67
+ this.i++;
68
+ this.readHeredocBodies();
69
+ return true;
70
+ }
71
+ readHeredocBodies() {
72
+ const pending = this.pendingHeredocs;
73
+ this.pendingHeredocs = [];
74
+ for (const r of pending) {
75
+ const h = r.heredoc;
76
+ const delim = r.delim;
77
+ const stripTabs = r.op === "<<-";
78
+ const lines = [];
79
+ let found = false;
80
+ while (this.i <= this.src.length) {
81
+ let nl = this.src.indexOf("\n", this.i);
82
+ if (nl < 0)
83
+ nl = this.src.length;
84
+ let line = this.src.slice(this.i, nl);
85
+ this.i = Math.min(nl + 1, this.src.length + 1);
86
+ if (stripTabs)
87
+ line = line.replace(/^\t+/, "");
88
+ if (line === delim) {
89
+ found = true;
90
+ break;
91
+ }
92
+ lines.push(line);
93
+ if (nl >= this.src.length)
94
+ break;
95
+ }
96
+ if (this.i > this.src.length)
97
+ this.i = this.src.length;
98
+ if (!found)
99
+ throw new Unanalyzable("here-doc without its terminator");
100
+ h.body = lines.join("\n") + (lines.length ? "\n" : "");
101
+ if (!h.quoted)
102
+ h.script = expansionsOfHeredoc(h.body, this.depth);
103
+ }
104
+ }
105
+ /** Parse a list of and-or items until `stop` (")" , "}" , keyword set) or EOF. */
106
+ parseScript(stop, stopWords = null) {
107
+ const script = { commands: [], functions: [] };
108
+ for (;;) {
109
+ this.blanks();
110
+ if (this.i >= this.src.length)
111
+ break;
112
+ const c = this.peek();
113
+ if (c === "\n") {
114
+ this.newline();
115
+ continue;
116
+ }
117
+ if (c === ";") {
118
+ if (this.peek(1) === ";")
119
+ throw new Unanalyzable("case syntax is not supported");
120
+ this.i++;
121
+ continue;
122
+ }
123
+ if (stop !== null && c === stop)
124
+ break;
125
+ if (stopWords && this.atWord(stopWords))
126
+ break;
127
+ if (c === ")" || c === "&" || c === "|")
128
+ throw new Unanalyzable(`unexpected '${c}'`);
129
+ this.parseAndOr(script);
130
+ this.blanks();
131
+ const d = this.peek();
132
+ if (d === ";" && this.peek(1) !== ";") {
133
+ this.i++;
134
+ continue;
135
+ }
136
+ if (d === "&" && this.peek(1) !== "&" && this.peek(1) !== ">") {
137
+ this.i++;
138
+ continue;
139
+ }
140
+ if (d === "\n") {
141
+ this.newline();
142
+ continue;
143
+ }
144
+ if (d === undefined)
145
+ break;
146
+ if (stop !== null && d === stop)
147
+ break;
148
+ if (stopWords && this.atWord(stopWords))
149
+ break;
150
+ throw new Unanalyzable(`unexpected '${d}'`);
151
+ }
152
+ if (this.pendingHeredocs.length > 0)
153
+ throw new Unanalyzable("here-doc without a body");
154
+ return script;
155
+ }
156
+ /** Is the next word exactly one of `words` (followed by a metachar or EOF)? */
157
+ atWord(words) {
158
+ for (const w of words) {
159
+ if (this.src.startsWith(w, this.i)) {
160
+ const after = this.src[this.i + w.length];
161
+ if (after === undefined || META.has(after))
162
+ return w;
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+ expectWord(w) {
168
+ this.blanksAndNewlines();
169
+ if (!this.atWord(new Set([w])))
170
+ throw new Unanalyzable(`expected '${w}'`);
171
+ this.i += w.length;
172
+ }
173
+ blanksAndNewlines() {
174
+ for (;;) {
175
+ this.blanks();
176
+ if (this.peek() === "\n") {
177
+ this.newline();
178
+ continue;
179
+ }
180
+ if (this.peek() === ";" && this.peek(1) !== ";") {
181
+ this.i++;
182
+ continue;
183
+ }
184
+ break;
185
+ }
186
+ }
187
+ parseAndOr(script) {
188
+ this.parsePipeline(script);
189
+ for (;;) {
190
+ this.blanks();
191
+ if ((this.peek() === "&" && this.peek(1) === "&") || (this.peek() === "|" && this.peek(1) === "|")) {
192
+ this.i += 2;
193
+ this.bump();
194
+ this.blanksAndNewlinesOnly();
195
+ if (this.i >= this.src.length)
196
+ throw new Unanalyzable("command list ends with an operator");
197
+ this.parsePipeline(script);
198
+ continue;
199
+ }
200
+ break;
201
+ }
202
+ }
203
+ blanksAndNewlinesOnly() {
204
+ for (;;) {
205
+ this.blanks();
206
+ if (this.peek() === "\n") {
207
+ this.newline();
208
+ continue;
209
+ }
210
+ break;
211
+ }
212
+ }
213
+ parsePipeline(script) {
214
+ this.blanks();
215
+ if (this.peek() === "!" && (this.peek(1) === " " || this.peek(1) === "\t")) {
216
+ this.i++;
217
+ this.blanks();
218
+ }
219
+ if (this.atWord(new Set(["time"]))) {
220
+ this.i += 4;
221
+ this.blanks();
222
+ if (this.src.startsWith("-p", this.i) && META.has(this.src[this.i + 2] ?? " ")) {
223
+ this.i += 2;
224
+ this.blanks();
225
+ }
226
+ }
227
+ let prev = null;
228
+ let first = true;
229
+ for (;;) {
230
+ const before = script.commands.length;
231
+ this.parseCommand(script);
232
+ const last = script.commands[script.commands.length - 1];
233
+ if (!first && last && script.commands.length > before) {
234
+ // The first simple command of this stage reads from the pipe.
235
+ const head = script.commands[before];
236
+ if (head) {
237
+ head.pipedIn = true;
238
+ head.pipedFrom = prev;
239
+ }
240
+ }
241
+ prev = last ?? null;
242
+ first = false;
243
+ this.blanks();
244
+ if (this.peek() === "|" && this.peek(1) !== "|") {
245
+ this.i += this.peek(1) === "&" ? 2 : 1;
246
+ this.bump();
247
+ this.blanksAndNewlinesOnly();
248
+ if (this.i >= this.src.length)
249
+ throw new Unanalyzable("pipeline ends with '|'");
250
+ continue;
251
+ }
252
+ break;
253
+ }
254
+ }
255
+ parseCommand(script) {
256
+ this.blanks();
257
+ const c = this.peek();
258
+ if (c === "(") {
259
+ if (this.peek(1) === "(")
260
+ throw new Unanalyzable("(( )) arithmetic commands are not supported");
261
+ this.i++;
262
+ const inner = new Parser(this.src, this.depth + 1);
263
+ inner.i = this.i;
264
+ inner.tokens = this.tokens;
265
+ const s = inner.parseScript(")");
266
+ if (inner.peek() !== ")")
267
+ throw new Unanalyzable("unclosed subshell");
268
+ this.i = inner.i + 1;
269
+ this.tokens = inner.tokens;
270
+ this.absorb(script, s);
271
+ this.trailingRedirects(script, before(script, s));
272
+ return;
273
+ }
274
+ const kw = this.atWord(new Set(["{", "if", "for", "while", "until", "function", "case", "select", "coproc", "[[", "}"]));
275
+ if (kw === "}")
276
+ throw new Unanalyzable("unexpected '}'");
277
+ // A reserved word that closes or continues a compound command, where a command is
278
+ // expected, is a syntax error in bash (T-DIFF: `…; then x; fi` without an `if`).
279
+ const stray = this.atWord(new Set(["then", "else", "elif", "fi", "do", "done", "esac"]));
280
+ if (stray)
281
+ throw new Unanalyzable(`unexpected '${stray}'`);
282
+ if (kw && RESERVED_UNSUPPORTED.has(kw))
283
+ throw new Unanalyzable(`'${kw}' is not supported`);
284
+ if (kw === "{") {
285
+ this.i += 1;
286
+ const s = this.sub(() => this.parseScript(null, new Set(["}"])));
287
+ this.expectWord("}");
288
+ this.absorb(script, s);
289
+ this.trailingRedirects(script, before(script, s));
290
+ return;
291
+ }
292
+ if (kw === "if") {
293
+ this.i += 2;
294
+ const stops = new Set(["then"]);
295
+ this.absorb(script, this.sub(() => this.parseScript(null, stops)));
296
+ this.expectWord("then");
297
+ for (;;) {
298
+ const body = this.sub(() => this.parseScript(null, new Set(["elif", "else", "fi"])));
299
+ this.absorb(script, body);
300
+ this.blanksAndNewlines();
301
+ const w = this.atWord(new Set(["elif", "else", "fi"]));
302
+ if (w === "fi") {
303
+ this.i += 2;
304
+ break;
305
+ }
306
+ if (w === "else") {
307
+ this.i += 4;
308
+ continue;
309
+ }
310
+ if (w === "elif") {
311
+ this.i += 4;
312
+ this.absorb(script, this.sub(() => this.parseScript(null, new Set(["then"]))));
313
+ this.expectWord("then");
314
+ continue;
315
+ }
316
+ throw new Unanalyzable("unterminated if");
317
+ }
318
+ return;
319
+ }
320
+ if (kw === "while" || kw === "until") {
321
+ this.i += kw.length;
322
+ this.absorb(script, this.sub(() => this.parseScript(null, new Set(["do"]))));
323
+ this.expectWord("do");
324
+ this.absorb(script, this.sub(() => this.parseScript(null, new Set(["done"]))));
325
+ this.expectWord("done");
326
+ return;
327
+ }
328
+ if (kw === "for") {
329
+ this.i += 3;
330
+ this.blanks();
331
+ if (this.peek() === "(")
332
+ throw new Unanalyzable("C-style for loops are not supported");
333
+ const name = this.readWord();
334
+ if (!name || !isPlainName(name))
335
+ throw new Unanalyzable("bad for loop");
336
+ this.blanksAndNewlinesOnly();
337
+ const loopWords = [];
338
+ if (this.atWord(new Set(["in"]))) {
339
+ this.i += 2;
340
+ for (;;) {
341
+ this.blanks();
342
+ const ch = this.peek();
343
+ if (ch === undefined || ch === ";" || ch === "\n")
344
+ break;
345
+ const w = this.readWord();
346
+ if (!w)
347
+ throw new Unanalyzable("bad for loop");
348
+ loopWords.push(w);
349
+ }
350
+ }
351
+ // Loop words become a pseudo-command so their substitutions are analyzed.
352
+ if (loopWords.length)
353
+ script.commands.push({ kind: "simple", assigns: [], words: [{ parts: [{ t: "lit", s: "true", quoted: false }], raw: "true", brace: false }, ...loopWords], redirects: [], pipedIn: false, pipedFrom: null, });
354
+ this.expectWord("do");
355
+ this.absorb(script, this.sub(() => this.parseScript(null, new Set(["done"]))));
356
+ this.expectWord("done");
357
+ return;
358
+ }
359
+ if (kw === "function") {
360
+ this.i += 8;
361
+ this.blanks();
362
+ const name = this.readWord();
363
+ if (!name || !isPlainName(name))
364
+ throw new Unanalyzable("bad function definition");
365
+ this.blanks();
366
+ if (this.peek() === "(" && this.peek(1) === ")") {
367
+ this.i += 2;
368
+ }
369
+ this.blanksAndNewlinesOnly();
370
+ this.functionBody(script, plainText(name));
371
+ return;
372
+ }
373
+ if (kw === "[[") {
374
+ this.i += 2;
375
+ const end = this.src.indexOf("]]", this.i);
376
+ if (end < 0)
377
+ throw new Unanalyzable("unterminated [[");
378
+ const inner = this.src.slice(this.i, end);
379
+ if (inner.includes("$(") || inner.includes("`") || inner.includes("<("))
380
+ throw new Unanalyzable("substitution inside [[ ]]");
381
+ this.i = end + 2;
382
+ script.commands.push({ kind: "simple", assigns: [], words: [litWord("[[")], redirects: [], pipedIn: false, pipedFrom: null });
383
+ return;
384
+ }
385
+ // Simple command (or `name() { … }` function definition).
386
+ this.simpleCommand(script);
387
+ }
388
+ nest = 0;
389
+ sub(fn) {
390
+ if (this.depth + ++this.nest > MAX_NESTING)
391
+ throw new Unanalyzable("nesting too deep");
392
+ try {
393
+ return fn();
394
+ }
395
+ finally {
396
+ this.nest--;
397
+ }
398
+ }
399
+ absorb(into, s) {
400
+ into.commands.push(...s.commands);
401
+ into.functions.push(...s.functions);
402
+ }
403
+ trailingRedirects(script, firstIdx) {
404
+ // Redirects after a compound command apply to all its commands.
405
+ const reds = [];
406
+ for (;;) {
407
+ this.blanks();
408
+ const r = this.tryRedirect();
409
+ if (!r)
410
+ break;
411
+ reds.push(r);
412
+ }
413
+ if (reds.length)
414
+ for (let k = firstIdx; k < script.commands.length; k++)
415
+ script.commands[k]?.redirects.push(...reds);
416
+ }
417
+ functionBody(script, name) {
418
+ this.blanksAndNewlinesOnly();
419
+ const c = this.peek();
420
+ let body;
421
+ if (c === "{" && META.has(this.peek(1) ?? " ")) {
422
+ this.i++;
423
+ body = this.sub(() => this.parseScript(null, new Set(["}"])));
424
+ this.expectWord("}");
425
+ }
426
+ else if (c === "(") {
427
+ this.i++;
428
+ body = this.sub(() => this.parseScript(")"));
429
+ if (this.peek() !== ")")
430
+ throw new Unanalyzable("bad function body");
431
+ this.i++;
432
+ }
433
+ else
434
+ throw new Unanalyzable("unsupported function body");
435
+ script.functions.push(name);
436
+ this.absorb(script, body);
437
+ }
438
+ simpleCommand(script) {
439
+ const cmd = { kind: "simple", assigns: [], words: [], redirects: [], pipedIn: false, pipedFrom: null };
440
+ for (;;) {
441
+ this.blanks();
442
+ const c = this.peek();
443
+ if (c === undefined || c === "\n" || c === ";" || c === "&" && this.peek(1) !== ">" || c === "|" || c === ")")
444
+ break;
445
+ if (c === "(") {
446
+ // name() { … }
447
+ if (cmd.words.length === 1 && cmd.assigns.length === 0 && this.peek(1) === ")") {
448
+ const name = plainText(cmd.words[0]);
449
+ if (!isPlainNameStr(name))
450
+ throw new Unanalyzable("bad function name");
451
+ this.i += 2;
452
+ this.functionBody(script, name);
453
+ return;
454
+ }
455
+ throw new Unanalyzable("unexpected '('");
456
+ }
457
+ const r = this.tryRedirect();
458
+ if (r) {
459
+ cmd.redirects.push(r);
460
+ continue;
461
+ }
462
+ // Assignment (only before the command name).
463
+ if (cmd.words.length === 0 && isNameStart(c)) {
464
+ let j = this.i;
465
+ while (isNameChar(this.src[j]))
466
+ j++;
467
+ if (this.src[j] === "[") {
468
+ const close = this.src.indexOf("]", j);
469
+ if (close > 0)
470
+ j = close + 1;
471
+ }
472
+ if (this.src[j] === "+" && this.src[j + 1] === "=")
473
+ j++;
474
+ if (this.src[j] === "=") {
475
+ const raw = this.src.slice(this.i, j);
476
+ const plus = raw.endsWith("+") ? raw.slice(0, -1) : raw;
477
+ const name = plus.includes("[") ? plus.slice(0, plus.indexOf("[")) : plus;
478
+ this.i = j + 1;
479
+ if (this.peek() === "(")
480
+ throw new Unanalyzable("array assignment is not supported");
481
+ const start = this.i;
482
+ const value = META.has(this.peek() ?? " ") ? null : this.readWord(true);
483
+ cmd.assigns.push({ name, value, raw: this.src.slice(start, this.i) });
484
+ this.bump();
485
+ continue;
486
+ }
487
+ }
488
+ const w = this.readWord();
489
+ if (!w)
490
+ throw new Unanalyzable(`unexpected '${c}'`);
491
+ cmd.words.push(w);
492
+ this.bump();
493
+ }
494
+ if (cmd.words.length === 0 && cmd.assigns.length === 0 && cmd.redirects.length === 0)
495
+ throw new Unanalyzable("empty command");
496
+ script.commands.push(cmd);
497
+ }
498
+ tryRedirect() {
499
+ const s = this.src;
500
+ let j = this.i;
501
+ let fd = null;
502
+ while (s[j] !== undefined && s[j] >= "0" && s[j] <= "9")
503
+ j++;
504
+ if (j > this.i && (s[j] === "<" || s[j] === ">"))
505
+ fd = Number(s.slice(this.i, j));
506
+ else
507
+ j = this.i;
508
+ const ops = ["&>>", "&>", "<<<", "<<-", "<<", "<>", ">>", ">|", ">&", "<&", ">", "<"];
509
+ const op = ops.find((o) => s.startsWith(o, j));
510
+ if (!op)
511
+ return null;
512
+ if ((op === ">" || op === "<") && s[j + 1] === "(")
513
+ throw new Unanalyzable("process substitution");
514
+ this.i = j + op.length;
515
+ this.bump();
516
+ this.blanks();
517
+ if (op === "<<" || op === "<<-") {
518
+ const start = this.i;
519
+ const w = this.readWord();
520
+ if (!w)
521
+ throw new Unanalyzable("here-doc without a delimiter");
522
+ const raw = this.src.slice(start, this.i);
523
+ const quoted = /['"\\]/.test(raw);
524
+ const delim = plainText(w);
525
+ const r = { op, fd, target: null, heredoc: { body: "", quoted, script: null }, delim };
526
+ this.pendingHeredocs.push(r);
527
+ return r;
528
+ }
529
+ if ((op === ">&" || op === "<&") && /^[0-9-]/.test(s[this.i] ?? "")) {
530
+ while (/[0-9-]/.test(s[this.i] ?? ""))
531
+ this.i++;
532
+ return { op, fd, target: null };
533
+ }
534
+ const w = this.readWord();
535
+ if (!w)
536
+ throw new Unanalyzable("redirection without a target");
537
+ return { op, fd, target: w };
538
+ }
539
+ /** Read one word. `assignment` enables tilde expansion after ':' as in assignments. */
540
+ readWord(assignment = false) {
541
+ const start = this.i;
542
+ const parts = [];
543
+ let brace = false;
544
+ let lit = "";
545
+ const flush = () => { if (lit) {
546
+ parts.push({ t: "lit", s: lit, quoted: false });
547
+ lit = "";
548
+ } };
549
+ const s = this.src;
550
+ // Tilde prefix.
551
+ if (s[this.i] === "~") {
552
+ let j = this.i + 1;
553
+ while (j < s.length && !META.has(s[j]) && s[j] !== "/" && s[j] !== ":" && s[j] !== '"' && s[j] !== "'" && s[j] !== "$" && s[j] !== "\\")
554
+ j++;
555
+ parts.push({ t: "tilde", user: s.slice(this.i + 1, j) });
556
+ this.i = j;
557
+ }
558
+ while (this.i < s.length) {
559
+ const c = s[this.i];
560
+ if (META.has(c))
561
+ break;
562
+ if (c === "\\") {
563
+ const n = s[this.i + 1];
564
+ if (n === undefined)
565
+ throw new Unanalyzable("trailing backslash");
566
+ if (n === "\n") {
567
+ this.i += 2;
568
+ continue;
569
+ }
570
+ lit += n;
571
+ this.i += 2;
572
+ continue;
573
+ }
574
+ if (c === "'") {
575
+ const end = s.indexOf("'", this.i + 1);
576
+ if (end < 0)
577
+ throw new Unanalyzable("unterminated single quote");
578
+ flush();
579
+ parts.push({ t: "lit", s: s.slice(this.i + 1, end), quoted: true });
580
+ this.i = end + 1;
581
+ continue;
582
+ }
583
+ if (c === "$" && s[this.i + 1] === "'") {
584
+ flush();
585
+ const [text, end] = ansiC(s, this.i + 2);
586
+ parts.push({ t: "lit", s: text, quoted: true });
587
+ this.i = end;
588
+ continue;
589
+ }
590
+ if (c === '"' || (c === "$" && s[this.i + 1] === '"')) {
591
+ flush();
592
+ this.i += c === "$" ? 2 : 1;
593
+ this.doubleQuoted(parts);
594
+ continue;
595
+ }
596
+ if (c === "$" || c === "`") {
597
+ flush();
598
+ this.dollarOrBacktick(parts, false);
599
+ continue;
600
+ }
601
+ if (c === "*" || c === "?" || (c === "[" && bracketClose(s, this.i) > 0)) {
602
+ flush();
603
+ if (c === "[") {
604
+ const end = bracketClose(s, this.i);
605
+ parts.push({ t: "glob", s: s.slice(this.i, end + 1) });
606
+ this.i = end + 1;
607
+ }
608
+ else {
609
+ parts.push({ t: "glob", s: c });
610
+ this.i++;
611
+ }
612
+ continue;
613
+ }
614
+ if (c === "{") {
615
+ const close = findBraceClose(s, this.i);
616
+ if (close > 0) {
617
+ const inner = s.slice(this.i + 1, close);
618
+ if (inner.includes(",") || /^[^.]*\.\.[^.]*$/.test(inner))
619
+ brace = true;
620
+ }
621
+ }
622
+ if (assignment && c === ":" && s[this.i + 1] === "~") {
623
+ lit += ":";
624
+ flush();
625
+ this.i++;
626
+ let j = this.i + 1;
627
+ while (j < s.length && !META.has(s[j]) && s[j] !== "/" && s[j] !== ":")
628
+ j++;
629
+ parts.push({ t: "tilde", user: s.slice(this.i + 1, j) });
630
+ this.i = j;
631
+ continue;
632
+ }
633
+ lit += c;
634
+ this.i++;
635
+ }
636
+ flush();
637
+ if (this.i === start)
638
+ return null;
639
+ return { parts, raw: s.slice(start, this.i), brace };
640
+ }
641
+ doubleQuoted(parts) {
642
+ const s = this.src;
643
+ let lit = "";
644
+ const flush = () => { if (lit) {
645
+ parts.push({ t: "lit", s: lit, quoted: true });
646
+ lit = "";
647
+ } };
648
+ let sawAny = false;
649
+ for (;;) {
650
+ if (this.i >= s.length)
651
+ throw new Unanalyzable("unterminated double quote");
652
+ const c = s[this.i];
653
+ if (c === '"') {
654
+ this.i++;
655
+ break;
656
+ }
657
+ if (c === "\\") {
658
+ const n = s[this.i + 1];
659
+ if (n === "$" || n === "`" || n === '"' || n === "\\") {
660
+ lit += n;
661
+ this.i += 2;
662
+ continue;
663
+ }
664
+ if (n === "\n") {
665
+ this.i += 2;
666
+ continue;
667
+ }
668
+ lit += "\\";
669
+ this.i++;
670
+ continue;
671
+ }
672
+ if (c === "$" || c === "`") {
673
+ if (c === "$" && !isNameStart(s[this.i + 1]) && !"{(0123456789@*#?$!-".includes(s[this.i + 1] ?? "x")) {
674
+ lit += c;
675
+ this.i++;
676
+ continue;
677
+ }
678
+ flush();
679
+ sawAny = true;
680
+ this.dollarOrBacktick(parts, true);
681
+ continue;
682
+ }
683
+ lit += c;
684
+ this.i++;
685
+ }
686
+ if (lit || !sawAny)
687
+ parts.push({ t: "lit", s: lit, quoted: true });
688
+ else
689
+ flush();
690
+ }
691
+ dollarOrBacktick(parts, quoted) {
692
+ const s = this.src;
693
+ if (s[this.i] === "`") {
694
+ // Find the closing unescaped backtick; unescape \` \\ \$ inside.
695
+ let j = this.i + 1;
696
+ let inner = "";
697
+ while (j < s.length && s[j] !== "`") {
698
+ if (s[j] === "\\" && (s[j + 1] === "`" || s[j + 1] === "\\" || s[j + 1] === "$")) {
699
+ inner += s[j + 1];
700
+ j += 2;
701
+ continue;
702
+ }
703
+ inner += s[j];
704
+ j++;
705
+ }
706
+ if (j >= s.length)
707
+ throw new Unanalyzable("unterminated backtick");
708
+ this.i = j + 1;
709
+ const p = new Parser(inner, this.depth + 1);
710
+ const script = p.parseScript(null);
711
+ parts.push({ t: "subst", script, quoted });
712
+ return;
713
+ }
714
+ // s[i] === "$"
715
+ const n = s[this.i + 1];
716
+ if (n === "(" && s[this.i + 2] === "(") {
717
+ const end = findArithClose(s, this.i + 3);
718
+ if (end < 0)
719
+ throw new Unanalyzable("unterminated $(( ))");
720
+ const raw = s.slice(this.i + 3, end);
721
+ if (raw.includes("$(") || raw.includes("`") || raw.includes("["))
722
+ throw new Unanalyzable("command inside arithmetic");
723
+ if (!validArithmetic(raw))
724
+ throw new Unanalyzable("arithmetic expression the parser doesn't understand");
725
+ parts.push({ t: "arith", raw });
726
+ this.i = end + 2;
727
+ return;
728
+ }
729
+ if (n === "(") {
730
+ const p = new Parser(s, this.depth + 1);
731
+ p.i = this.i + 2;
732
+ p.tokens = this.tokens;
733
+ const script = p.parseScript(")");
734
+ if (p.peek() !== ")")
735
+ throw new Unanalyzable("unterminated $( )");
736
+ this.i = p.i + 1;
737
+ this.tokens = p.tokens;
738
+ parts.push({ t: "subst", script, quoted });
739
+ return;
740
+ }
741
+ if (n === "{") {
742
+ const end = findBraceClose(s, this.i + 1);
743
+ if (end < 0)
744
+ throw new Unanalyzable("unterminated ${ }");
745
+ const inner = s.slice(this.i + 2, end);
746
+ if (inner.includes("$(") || inner.includes("`"))
747
+ throw new Unanalyzable("substitution inside ${ }");
748
+ const m = /^[#!]?([A-Za-z_][A-Za-z0-9_]*|[0-9@*#?$!-])/.exec(inner);
749
+ if (!m)
750
+ throw new Unanalyzable("unsupported ${ } form");
751
+ parts.push({ t: "var", name: inner, braced: true, quoted });
752
+ this.i = end + 1;
753
+ return;
754
+ }
755
+ if (isNameStart(n)) {
756
+ let j = this.i + 1;
757
+ while (isNameChar(s[j]))
758
+ j++;
759
+ parts.push({ t: "var", name: s.slice(this.i + 1, j), braced: false, quoted });
760
+ this.i = j;
761
+ return;
762
+ }
763
+ if (n !== undefined && "0123456789@*#?$!-".includes(n)) {
764
+ parts.push({ t: "var", name: n, braced: false, quoted });
765
+ this.i += 2;
766
+ return;
767
+ }
768
+ // A lone "$" is literal.
769
+ parts.push({ t: "lit", s: "$", quoted });
770
+ this.i += 1;
771
+ }
772
+ }
773
+ /**
774
+ * A conservative check that $(( … )) holds a plain arithmetic expression: numbers,
775
+ * names, $vars, operators and parentheses, with no two operands in a row (T-DIFF found
776
+ * `$(( X=1 cp *.log ))`, which bash rejects but a looser check accepted).
777
+ */
778
+ function validArithmetic(raw) {
779
+ let i = 0;
780
+ let expectOperand = true;
781
+ let depth = 0;
782
+ const ops = ["<<=", ">>=", "**", "++", "--", "<<", ">>", "<=", ">=", "==", "!=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "+", "-", "*", "/", "%", "<", ">", "=", "&", "|", "^", "!", "~", "?", ":", ","];
783
+ while (i < raw.length) {
784
+ const c = raw[i];
785
+ if (c === " " || c === "\t" || c === "\n") {
786
+ i++;
787
+ continue;
788
+ }
789
+ if (c === "(") {
790
+ if (!expectOperand)
791
+ return false;
792
+ depth++;
793
+ i++;
794
+ continue;
795
+ }
796
+ if (c === ")") {
797
+ if (expectOperand || depth === 0)
798
+ return false;
799
+ depth--;
800
+ i++;
801
+ continue;
802
+ }
803
+ const m = /^(\$\{[^}]*\}|\$?[A-Za-z_][A-Za-z0-9_]*|\$[0-9#?@*$!-]|[0-9][0-9A-Za-z#@_]*)/.exec(raw.slice(i, i + 200));
804
+ if (m) {
805
+ if (!expectOperand)
806
+ return false;
807
+ expectOperand = false;
808
+ i += m[0].length;
809
+ continue;
810
+ }
811
+ const op = ops.find((o) => raw.startsWith(o, i));
812
+ if (!op)
813
+ return false;
814
+ if (op === "++" || op === "--" || op === "!" || op === "~") {
815
+ i += op.length;
816
+ continue;
817
+ }
818
+ if ((op === "+" || op === "-") && expectOperand) {
819
+ i++;
820
+ continue;
821
+ }
822
+ if (expectOperand)
823
+ return false;
824
+ expectOperand = true;
825
+ i += op.length;
826
+ }
827
+ return !expectOperand && depth === 0 || raw.trim() === "";
828
+ }
829
+ /** Index of the `]` closing a glob bracket expression within the same word, or -1. */
830
+ function bracketClose(s, open) {
831
+ for (let j = open + 1; j < s.length && j < open + 256; j++) {
832
+ const c = s[j];
833
+ if (META.has(c) || c === "'" || c === '"')
834
+ return -1;
835
+ if (c === "]" && j > open + 1)
836
+ return j;
837
+ }
838
+ return -1;
839
+ }
840
+ function before(script, s) {
841
+ return script.commands.length - s.commands.length;
842
+ }
843
+ function findBraceClose(s, open) {
844
+ let depth = 0;
845
+ for (let j = open; j < s.length && j < open + 4096; j++) {
846
+ const c = s[j];
847
+ if (c === "\\") {
848
+ j++;
849
+ continue;
850
+ }
851
+ if (c === "{")
852
+ depth++;
853
+ else if (c === "}") {
854
+ depth--;
855
+ if (depth === 0)
856
+ return j;
857
+ }
858
+ else if (c === " " || c === "\n" || c === "\t" || c === ";" || c === "|" || c === "&") {
859
+ if (s[open - 1] !== "$")
860
+ return -1;
861
+ }
862
+ }
863
+ return -1;
864
+ }
865
+ function findArithClose(s, from) {
866
+ let depth = 0;
867
+ for (let j = from; j < s.length - 1; j++) {
868
+ if (s[j] === "(")
869
+ depth++;
870
+ else if (s[j] === ")") {
871
+ if (depth === 0 && s[j + 1] === ")")
872
+ return j;
873
+ depth--;
874
+ }
875
+ }
876
+ return -1;
877
+ }
878
+ /** Decode $'…' (ANSI-C quoting). Returns [text, index after closing quote]. */
879
+ function ansiC(s, from) {
880
+ let out = "";
881
+ let j = from;
882
+ while (j < s.length) {
883
+ const c = s[j];
884
+ if (c === "'")
885
+ return [out, j + 1];
886
+ if (c !== "\\") {
887
+ out += c;
888
+ j++;
889
+ continue;
890
+ }
891
+ const n = s[j + 1];
892
+ j += 2;
893
+ switch (n) {
894
+ case "n":
895
+ out += "\n";
896
+ break;
897
+ case "t":
898
+ out += "\t";
899
+ break;
900
+ case "r":
901
+ out += "\r";
902
+ break;
903
+ case "a":
904
+ out += "\x07";
905
+ break;
906
+ case "b":
907
+ out += "\b";
908
+ break;
909
+ case "e":
910
+ case "E":
911
+ out += "\x1b";
912
+ break;
913
+ case "f":
914
+ out += "\f";
915
+ break;
916
+ case "v":
917
+ out += "\v";
918
+ break;
919
+ case "\\":
920
+ out += "\\";
921
+ break;
922
+ case "'":
923
+ out += "'";
924
+ break;
925
+ case '"':
926
+ out += '"';
927
+ break;
928
+ case "?":
929
+ out += "?";
930
+ break;
931
+ case "c": throw new Unanalyzable("$'\\c' control escapes are not supported");
932
+ case "x": {
933
+ const m = /^[0-9a-fA-F]{1,2}/.exec(s.slice(j, j + 2));
934
+ if (!m) {
935
+ out += "\\x";
936
+ break;
937
+ }
938
+ out += String.fromCharCode(parseInt(m[0], 16));
939
+ j += m[0].length;
940
+ break;
941
+ }
942
+ case "u":
943
+ case "U": {
944
+ const m = (n === "u" ? /^[0-9a-fA-F]{1,4}/ : /^[0-9a-fA-F]{1,8}/).exec(s.slice(j, j + (n === "u" ? 4 : 8)));
945
+ if (!m) {
946
+ out += "\\" + n;
947
+ break;
948
+ }
949
+ const cp = parseInt(m[0], 16);
950
+ if (cp > 0x10ffff)
951
+ throw new Unanalyzable("bad \\U escape");
952
+ out += String.fromCodePoint(cp);
953
+ j += m[0].length;
954
+ break;
955
+ }
956
+ default: {
957
+ if (n !== undefined && n >= "0" && n <= "7") {
958
+ const m = /^[0-7]{1,3}/.exec(s.slice(j - 1, j + 2));
959
+ out += String.fromCharCode(parseInt(m[0], 8) & 0xff);
960
+ j += m[0].length - 1;
961
+ break;
962
+ }
963
+ if (n === undefined)
964
+ throw new Unanalyzable("unterminated $'");
965
+ out += "\\" + n;
966
+ }
967
+ }
968
+ }
969
+ throw new Unanalyzable("unterminated $'");
970
+ }
971
+ /** Command substitutions inside an unquoted here-doc body are real. Parse them. */
972
+ function expansionsOfHeredoc(body, depth) {
973
+ if (!body.includes("$(") && !body.includes("`"))
974
+ return null;
975
+ const script = { commands: [], functions: [] };
976
+ let i = 0;
977
+ while (i < body.length) {
978
+ const c = body[i];
979
+ if (c === "\\") {
980
+ i += 2;
981
+ continue;
982
+ }
983
+ if (c === "$" && body[i + 1] === "(" && body[i + 2] !== "(") {
984
+ const p = new Parser(body, depth + 1);
985
+ p.i = i + 2;
986
+ const inner = p.parseScript(")");
987
+ if (body[p.i] !== ")")
988
+ throw new Unanalyzable("unterminated $( ) in here-doc");
989
+ script.commands.push(...inner.commands);
990
+ i = p.i + 1;
991
+ continue;
992
+ }
993
+ if (c === "$" && body[i + 1] === "(" && body[i + 2] === "(") {
994
+ const end = findArithClose(body, i + 3);
995
+ if (end < 0)
996
+ throw new Unanalyzable("unterminated $(( )) in here-doc");
997
+ if (body.slice(i, end).includes("$(") || body.slice(i, end).includes("`"))
998
+ throw new Unanalyzable("command inside arithmetic");
999
+ i = end + 2;
1000
+ continue;
1001
+ }
1002
+ if (c === "`") {
1003
+ let j = i + 1;
1004
+ let inner = "";
1005
+ while (j < body.length && body[j] !== "`") {
1006
+ if (body[j] === "\\" && (body[j + 1] === "`" || body[j + 1] === "\\" || body[j + 1] === "$")) {
1007
+ inner += body[j + 1];
1008
+ j += 2;
1009
+ continue;
1010
+ }
1011
+ inner += body[j];
1012
+ j++;
1013
+ }
1014
+ if (j >= body.length)
1015
+ throw new Unanalyzable("unterminated backtick in here-doc");
1016
+ script.commands.push(...new Parser(inner, depth + 1).parseScript(null).commands);
1017
+ i = j + 1;
1018
+ continue;
1019
+ }
1020
+ i++;
1021
+ }
1022
+ return script;
1023
+ }
1024
+ export function litWord(s) {
1025
+ return { parts: [{ t: "lit", s, quoted: false }], raw: s, brace: false };
1026
+ }
1027
+ /** Text of a word whose parts are all literal; otherwise the raw text. */
1028
+ export function plainText(w) {
1029
+ return w.parts.every((p) => p.t === "lit") ? w.parts.map((p) => p.s).join("") : w.raw;
1030
+ }
1031
+ function isPlainName(w) {
1032
+ return w.parts.length === 1 && w.parts[0]?.t === "lit" && !w.parts[0].quoted && isPlainNameStr(w.parts[0].s);
1033
+ }
1034
+ function isPlainNameStr(s) {
1035
+ return /^[A-Za-z_][A-Za-z0-9_.:-]*$/.test(s);
1036
+ }
1037
+ //# sourceMappingURL=parse.js.map