fauxnix-cli 1.0.0 → 2.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.
package/dist/parser.js CHANGED
@@ -123,6 +123,12 @@ export function tokenize(input) {
123
123
  let buf = '';
124
124
  while (i < n && input[i] !== '"') {
125
125
  const c = input[i];
126
+ // A quoted continuation joins the physical lines just as it does
127
+ // outside quotes; unlike an ordinary quoted newline it adds no text.
128
+ if (c === '\\' && input[i + 1] === '\n') {
129
+ i += 2;
130
+ continue;
131
+ }
126
132
  if (c === '\\' && i + 1 < n && '"$`\\'.includes(input[i + 1])) {
127
133
  buf += input[i + 1];
128
134
  i += 2;
@@ -441,6 +447,12 @@ function readDollar(input, i) {
441
447
  let depth = 1;
442
448
  let k = j + 1;
443
449
  while (k < n && depth > 0) {
450
+ // Escaped delimiters belong to the command text, not the enclosing
451
+ // substitution. Preserve both characters for its recursive tokenizer.
452
+ if (input[k] === '\\' && k + 1 < n) {
453
+ k += 2;
454
+ continue;
455
+ }
444
456
  if (input[k] === '(')
445
457
  depth++;
446
458
  else if (input[k] === ')')
@@ -449,7 +461,8 @@ function readDollar(input, i) {
449
461
  const q = input[k];
450
462
  k++;
451
463
  while (k < n && input[k] !== q) {
452
- if (input[k] === '\\')
464
+ // Single quotes are fully literal, including a final backslash.
465
+ if (q === '"' && input[k] === '\\')
453
466
  k++;
454
467
  k++;
455
468
  }
@@ -913,6 +926,10 @@ export function parseCommand(input) {
913
926
  const t = peek();
914
927
  if (t.type === 'OP' && t.op === '|') {
915
928
  next();
929
+ // Bash permits physical newlines (and comments on those lines)
930
+ // while waiting for the next pipeline stage, as after && and ||.
931
+ while (peek().type === 'OP' && peek().op === '\n')
932
+ next();
916
933
  continue;
917
934
  }
918
935
  break;
@@ -1029,11 +1046,9 @@ export function parseCommand(input) {
1029
1046
  next();
1030
1047
  expectKw('in');
1031
1048
  const words = [];
1032
- for (;;) {
1033
- while (peek().type === 'OP' && (peek().op === ';' || peek().op === '\n'))
1034
- next();
1035
- if (peekKw() === 'do')
1036
- break;
1049
+ // Reserved words are ordinary list elements until the header's separator:
1050
+ // `for x in do; do ...` iterates over the literal word "do".
1051
+ while (!(peek().type === 'OP' && isListSep(peek().op))) {
1037
1052
  const t = peek();
1038
1053
  if (t.type !== 'WORD' || !t.parts) {
1039
1054
  throw new FauxnixParseError("fauxnix: `for` expected `do`");
@@ -1041,6 +1056,11 @@ export function parseCommand(input) {
1041
1056
  words.push(t.parts);
1042
1057
  next();
1043
1058
  }
1059
+ // A semicolon may be followed by newlines, but another semicolon (or
1060
+ // more words before `do`) is not another part of the word list.
1061
+ next();
1062
+ while (peek().type === 'OP' && peek().op === '\n')
1063
+ next();
1044
1064
  expectKw('do');
1045
1065
  const body = parseListUntil(['done']);
1046
1066
  expectKw('done');
@@ -1410,38 +1430,27 @@ export function parseCommand(input) {
1410
1430
  * is not a valid assignment.
1411
1431
  */
1412
1432
  function splitAssignment(w) {
1413
- // merge adjacent Text parts first — the tokenizer emits per-char parts
1414
- const merged = [];
1415
- for (const p of w) {
1416
- const last = merged[merged.length - 1];
1417
- if (p.kind === 'Text' && last && last.kind === 'Text') {
1418
- last.text += p.text;
1419
- }
1420
- else if (p.kind === 'SingleQuoted' && last && last.kind === 'SingleQuoted') {
1421
- last.text += p.text;
1422
- }
1423
- else {
1424
- merged.push({ ...p });
1425
- }
1426
- }
1427
- for (let idx = 0; idx < merged.length; idx++) {
1428
- const p = merged[idx];
1429
- if (p.kind !== 'Text')
1430
- continue;
1433
+ let name = '';
1434
+ for (let idx = 0; idx < w.length; idx++) {
1435
+ const p = w[idx];
1436
+ // Quoting/escaping anywhere in NAME= makes this a command word.
1437
+ // Do not merge parts here: the value's escapes also distinguish
1438
+ // literal tildes/parentheses from home expansion/array assignment.
1439
+ if (p.kind !== 'Text' || p.escaped)
1440
+ return null;
1431
1441
  const eq = p.text.indexOf('=');
1432
- if (eq <= 0)
1433
- continue;
1434
- const name = merged
1435
- .slice(0, idx)
1436
- .map((q) => (q.kind === 'Text' || q.kind === 'SingleQuoted' ? q.text : ''))
1437
- .join('') + p.text.slice(0, eq);
1438
- if (!isNameStart(name[0]) || !name.split('').every(isNameChar))
1442
+ if (eq < 0) {
1443
+ name += p.text;
1439
1444
  continue;
1445
+ }
1446
+ name += p.text.slice(0, eq);
1447
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
1448
+ return null;
1440
1449
  const value = [];
1441
1450
  const tail = p.text.slice(eq + 1);
1442
1451
  if (tail)
1443
- value.push({ kind: 'Text', text: tail });
1444
- value.push(...merged.slice(idx + 1));
1452
+ value.push({ ...p, text: tail });
1453
+ value.push(...w.slice(idx + 1));
1445
1454
  return { name, value };
1446
1455
  }
1447
1456
  return null;
package/dist/ps-host.js CHANGED
@@ -152,7 +152,38 @@ export class PowerShellHost {
152
152
  await this.stop();
153
153
  return this.cancelledResult();
154
154
  }
155
- const started = await this.ensureStarted();
155
+ // Startup is part of the caller's deadline. A cold host must not send a
156
+ // command after its caller has already cancelled or exhausted its budget.
157
+ const deadline = Date.now() + timeoutMs;
158
+ let startupTimer;
159
+ let onStartupAbort;
160
+ const interrupted = new Promise((resolve) => {
161
+ startupTimer = setTimeout(() => resolve('timed_out'), Math.max(0, timeoutMs));
162
+ onStartupAbort = () => resolve('cancelled');
163
+ signal?.addEventListener('abort', onStartupAbort, { once: true });
164
+ if (signal?.aborted)
165
+ resolve('cancelled');
166
+ });
167
+ let started;
168
+ try {
169
+ started = await Promise.race([this.ensureStarted(), interrupted]);
170
+ }
171
+ finally {
172
+ clearTimeout(startupTimer);
173
+ if (onStartupAbort)
174
+ signal?.removeEventListener('abort', onStartupAbort);
175
+ }
176
+ if (started === 'cancelled' || signal?.aborted) {
177
+ await this.stop();
178
+ return this.cancelledResult();
179
+ }
180
+ if (started === 'timed_out' || Date.now() >= deadline) {
181
+ await this.stop();
182
+ return {
183
+ stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), exitCode: 124,
184
+ timedOut: true, cancelled: false, truncated: false,
185
+ };
186
+ }
156
187
  if (started)
157
188
  return { ...started, cancelled: false, truncated: false };
158
189
  const id = 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
@@ -199,9 +230,9 @@ export class PowerShellHost {
199
230
  signal?.addEventListener('abort', onAbort, { once: true });
200
231
  try {
201
232
  if (this.protocol === 2) {
202
- return await this.collectV2(id, timeoutMs, resolvedLimits);
233
+ return await this.collectV2(id, Math.max(0, deadline - Date.now()), resolvedLimits);
203
234
  }
204
- const raw = await this.nextJsonLine(timeoutMs, id);
235
+ const raw = await this.nextJsonLine(Math.max(0, deadline - Date.now()), id);
205
236
  const msg = decodeHostResponse(raw);
206
237
  const native = this.drainNativeStderr();
207
238
  return {
@@ -68,6 +68,11 @@ export interface WordArgs {
68
68
  flags: Set<string>;
69
69
  longs: Set<string>;
70
70
  values: Map<string, string>;
71
+ /** Every option value in argv order, including repeated options/aliases. */
72
+ valueEntries: Array<{
73
+ name: string;
74
+ value: string;
75
+ }>;
71
76
  /** Options that take a value but were not followed by one. */
72
77
  missingValue: string[];
73
78
  operandWords: Word[];
package/dist/registry.js CHANGED
@@ -96,6 +96,11 @@ export function parseWords(args, shortValues = [], longValues = []) {
96
96
  const flags = new Set();
97
97
  const longs = new Set();
98
98
  const values = new Map();
99
+ const valueEntries = [];
100
+ const addValue = (name, value) => {
101
+ values.set(name, value);
102
+ valueEntries.push({ name, value });
103
+ };
99
104
  const missingValue = [];
100
105
  const operandWords = [];
101
106
  let i = 0;
@@ -109,12 +114,12 @@ export function parseWords(args, shortValues = [], longValues = []) {
109
114
  const eq = t.indexOf('=');
110
115
  if (eq >= 0) {
111
116
  longs.add(t.slice(0, eq));
112
- values.set(t.slice(0, eq), t.slice(eq + 1));
117
+ addValue(t.slice(0, eq), t.slice(eq + 1));
113
118
  }
114
119
  else if (longValues.includes(t)) {
115
120
  longs.add(t);
116
121
  if (i + 1 < args.length) {
117
- values.set(t, wordToString(args[i + 1]));
122
+ addValue(t, wordToString(args[i + 1]));
118
123
  i++;
119
124
  }
120
125
  else
@@ -133,10 +138,10 @@ export function parseWords(args, shortValues = [], longValues = []) {
133
138
  // value-taking options report via `values`, not `flags`
134
139
  const rest = body.slice(c + 1);
135
140
  if (rest) {
136
- values.set('-' + ch, rest);
141
+ addValue('-' + ch, rest);
137
142
  }
138
143
  else if (i + 1 < args.length) {
139
- values.set('-' + ch, wordToString(args[i + 1]));
144
+ addValue('-' + ch, wordToString(args[i + 1]));
140
145
  i++;
141
146
  }
142
147
  else
@@ -151,7 +156,7 @@ export function parseWords(args, shortValues = [], longValues = []) {
151
156
  }
152
157
  i++;
153
158
  }
154
- return { flags, longs, values, missingValue, operandWords };
159
+ return { flags, longs, values, valueEntries, missingValue, operandWords };
155
160
  }
156
161
  const specs = new Map();
157
162
  /**
@@ -0,0 +1,3 @@
1
+ export declare let nodeEngineRange: string;
2
+ /** This package uses one inclusive stable-version floor, not general semver ranges. */
3
+ export declare function supportsNode(version: string): boolean;
@@ -0,0 +1,31 @@
1
+ import { readFileSync } from 'node:fs';
2
+ // Keep diagnostics and the entrypoint aligned with the install contract.
3
+ // The SEA launcher bundle has no package.json beside its executable; the
4
+ // launcher build injects the engine range as a banner global instead.
5
+ const bundledRange = globalThis.__FAUXNIX_ENGINES_NODE__;
6
+ export let nodeEngineRange;
7
+ if (typeof bundledRange === 'string') {
8
+ nodeEngineRange = bundledRange;
9
+ }
10
+ else {
11
+ const metadata = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
12
+ nodeEngineRange = metadata.engines?.node;
13
+ }
14
+ const minimum = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(nodeEngineRange);
15
+ if (!minimum)
16
+ throw new Error('fauxnix: unsupported package.json Node engine range');
17
+ const required = minimum.slice(1).map(Number);
18
+ /** This package uses one inclusive stable-version floor, not general semver ranges. */
19
+ export function supportsNode(version) {
20
+ const match = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[\w.-]+)?$/.exec(version);
21
+ if (!match)
22
+ return false;
23
+ const actual = match.slice(1, 4).map(Number);
24
+ if (!actual.every(Number.isSafeInteger))
25
+ return false;
26
+ for (let i = 0; i < 3; i++) {
27
+ if (actual[i] !== required[i])
28
+ return actual[i] > required[i];
29
+ }
30
+ return true;
31
+ }
@@ -50,7 +50,8 @@ export declare function pathExpr(s: string): string;
50
50
  /**
51
51
  * Convert a Word to a PowerShell string expression.
52
52
  * Literal words become single-quoted strings; dynamic ones become
53
- * double-quoted strings with $(...) interpolation.
53
+ * double-quoted strings with $(...) interpolation, concatenating command
54
+ * substitutions outside those strings so their scriptblocks parse independently.
54
55
  */
55
56
  export declare function exprOfWord(w: Word, opts?: {
56
57
  preserveCmdSub?: boolean;
@@ -101,6 +102,7 @@ export declare function wrapTempEnv(sets: Assignment[], body: string, extra?: {
101
102
  unsets?: string[];
102
103
  persistNames?: Set<string>;
103
104
  persistWords?: Word[];
105
+ preserveArgumentStatus?: boolean;
104
106
  }): string;
105
107
  export interface PipelineParts {
106
108
  /** Generated function definitions (empty for single commands). */
@@ -366,12 +366,13 @@ export function pathExpr(s) {
366
366
  /**
367
367
  * Convert a Word to a PowerShell string expression.
368
368
  * Literal words become single-quoted strings; dynamic ones become
369
- * double-quoted strings with $(...) interpolation.
369
+ * double-quoted strings with $(...) interpolation, concatenating command
370
+ * substitutions outside those strings so their scriptblocks parse independently.
370
371
  */
371
372
  export function exprOfWord(w, opts) {
372
373
  // tilde expansion (unquoted leading ~)
373
374
  const expanded = [];
374
- if (w.length > 0 && w[0].kind === 'Text' && w[0].text.startsWith('~')) {
375
+ if (w.length > 0 && w[0].kind === 'Text' && !w[0].escaped && w[0].text.startsWith('~')) {
375
376
  expanded.push({ kind: 'Var', name: 'HOME' });
376
377
  const rest = w[0].text.slice(1);
377
378
  if (rest)
@@ -399,35 +400,59 @@ export function exprOfWord(w, opts) {
399
400
  const text = expanded.map((p) => p.text).join('');
400
401
  return pathExpr(normalizeLiteralPath(text));
401
402
  }
402
- // dynamic — build a PS double-quoted string with interpolation
403
- let out = '"';
403
+ return interpolatedWordExpr(expanded, opts?.preserveCmdSub === true);
404
+ }
405
+ function containsCmdSub(parts) {
406
+ return parts.some((part) => part.kind === 'CmdSub' ||
407
+ ((part.kind === 'DoubleQuoted' || part.kind === 'Arith') && containsCmdSub(part.parts)));
408
+ }
409
+ /** Keep generated scriptblocks out of PowerShell's expandable-string lexer. */
410
+ function interpolatedWordExpr(parts, preserveCmdSub) {
411
+ const expressions = [];
412
+ let text = '';
413
+ const flushText = () => {
414
+ if (text)
415
+ expressions.push('"' + text + '"');
416
+ text = '';
417
+ };
404
418
  const emitPart = (p, quoted) => {
405
419
  switch (p.kind) {
406
420
  case 'Text':
407
- out += escapeDq(p.text);
408
- break;
409
421
  case 'SingleQuoted':
410
- out += escapeDq(p.text);
422
+ text += escapeDq(p.text);
411
423
  break;
412
424
  case 'DoubleQuoted':
413
425
  for (const q of p.parts)
414
426
  emitPart(q, true);
415
427
  break;
416
428
  case 'Var':
417
- out += '$(' + varExpr(p.name, p.index, p.param, p.length === true, varExtraOf(p)) + ')';
429
+ text += '$(' + varExpr(p.name, p.index, p.param, p.length === true, varExtraOf(p)) + ')';
418
430
  break;
419
431
  case 'CmdSub':
420
- out += '$(' + translateCmdSub(p.cmd, quoted || opts?.preserveCmdSub === true) + ')';
432
+ flushText();
433
+ // fx-csub returns one string. Preserve an empty result and prevent '+'
434
+ // from acquiring array/numeric semantics when this starts a mixed word.
435
+ expressions.push('[string](' + translateCmdSub(p.cmd, quoted || preserveCmdSub) + ')');
421
436
  break;
422
437
  case 'Arith':
423
- out += arithExpr(p.parts);
438
+ if (containsCmdSub(p.parts)) {
439
+ flushText();
440
+ expressions.push('[string](' + arithExpr(p.parts) + ')');
441
+ }
442
+ else {
443
+ text += arithExpr(p.parts);
444
+ }
424
445
  break;
425
446
  }
426
447
  };
427
- for (const p of expanded)
448
+ for (const p of parts)
428
449
  emitPart(p, false);
429
- out += '"';
430
- return out;
450
+ flushText();
451
+ if (expressions.length === 0)
452
+ return '""';
453
+ if (expressions.length === 1)
454
+ return expressions[0];
455
+ return '(' + expressions.join(' + ') + ')';
431
456
  }
432
457
  let arithHelperPreamble = '';
433
458
  /** Registered by sysinfo so wrapScript can emit fx-arith without a circular import. */
@@ -458,39 +483,14 @@ function arithSourceExpr(parts) {
458
483
  if (parts.every((p) => p.kind === 'Text')) {
459
484
  return psStr(parts.map((p) => p.text).join(''));
460
485
  }
461
- let out = '"';
462
- const emit = (p) => {
463
- switch (p.kind) {
464
- case 'Text':
465
- case 'SingleQuoted':
466
- out += escapeDq(p.text);
467
- break;
468
- case 'DoubleQuoted':
469
- for (const q of p.parts)
470
- emit(q);
471
- break;
472
- case 'Var':
473
- out += '$(' + varExpr(p.name, p.index, p.param, p.length === true, varExtraOf(p)) + ')';
474
- break;
475
- case 'CmdSub':
476
- out += '$(' + translateCmdSub(p.cmd, true) + ')';
477
- break;
478
- case 'Arith':
479
- out += arithExpr(p.parts);
480
- break;
481
- }
482
- };
483
- for (const p of parts)
484
- emit(p);
485
- out += '"';
486
- return out;
486
+ return interpolatedWordExpr(parts, true);
487
487
  }
488
488
  /** Literal text of a word when it contains no interpolation, else null. */
489
489
  export function literalOfWord(w) {
490
490
  if (!w.every((p) => p.kind === 'Text' || p.kind === 'SingleQuoted'))
491
491
  return null;
492
492
  const text = w.map((p) => p.text).join('');
493
- if (w.length > 0 && w[0].kind === 'Text' && w[0].text.startsWith('~'))
493
+ if (w.length > 0 && w[0].kind === 'Text' && !w[0].escaped && w[0].text.startsWith('~'))
494
494
  return null; // needs $HOME
495
495
  return text;
496
496
  }
@@ -597,7 +597,14 @@ export function argListExpr(words, fn = exprOfWord) {
597
597
  */
598
598
  export function translateCmdSub(cmdText, keepNl = false, translation = EXECUTE_TRANSLATION) {
599
599
  const inner = translateListInline(parseCommand(cmdText), translation);
600
- const collected = '(fx-csub { ' + inner + ' })';
600
+ // Isolate the substitution's execution status in its generated block, so
601
+ // pipeline stage-slot rewriting also covers save/restore. The caller sees
602
+ // its last result through a separate accumulator: assignment-only commands
603
+ // commit it, while commands such as echo retain their own execution status.
604
+ const collected = '$( $fx_cs_output = fx-csub { ' +
605
+ '$fx_cs_saved = $script:fx_exit; $script:fx_exit = 0; try {\n' + inner +
606
+ '\n} finally { $script:fx_csub_exit = $script:fx_exit; $script:fx_exit = $fx_cs_saved }' +
607
+ ' }; $fx_prev = [string]$script:fx_csub_exit; $fx_cs_output )';
601
608
  if (keepNl)
602
609
  return collected;
603
610
  return ('((' +
@@ -623,7 +630,9 @@ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_T
623
630
  // deviation: shell var vs exported var are indistinguishable here).
624
631
  if (cmd.name === null) {
625
632
  const exportHandler = lookup('export');
626
- const chunks = [];
633
+ // Reset once for the whole assignment list: a later literal assignment
634
+ // must not erase an earlier substitution's status (x=$(false) y=plain).
635
+ const chunks = ['$script:fx_csub_exit = 0'];
627
636
  for (const a of cmd.assignments) {
628
637
  if (a.values) {
629
638
  chunks.push('fx-arrput ' +
@@ -638,6 +647,9 @@ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_T
638
647
  }
639
648
  }
640
649
  }
650
+ // Preserve expansion failures; otherwise the last substitution owns the
651
+ // status of a command with no command word. No substitutions means 0.
652
+ chunks.push('if ($script:fx_exit -eq 0) { $script:fx_exit = $script:fx_csub_exit }');
641
653
  return chunks.join('\n');
642
654
  }
643
655
  const nameLit = literalOfWord(cmd.name);
@@ -719,7 +731,7 @@ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_T
719
731
  persistWords.push(w);
720
732
  }
721
733
  }
722
- body = wrapTempEnv(cmd.assignments, body, { persistNames, persistWords });
734
+ body = wrapTempEnv(cmd.assignments, body, { persistNames, persistWords, preserveArgumentStatus: true });
723
735
  }
724
736
  return body;
725
737
  }
@@ -781,6 +793,7 @@ export function wrapTempEnv(sets, body, extra) {
781
793
  const arrSave = '$fx_ar' + id;
782
794
  const keep = persistWords && persistWords.length > 0 ? '$fx_ek' + id : '';
783
795
  const lines = [
796
+ ...(extra?.preserveArgumentStatus ? ['$fx_eprev' + id + ' = $fx_prev'] : []),
784
797
  save + ' = @{}',
785
798
  arrSave + ' = @{}',
786
799
  '$fx_sv0' + id + ' = $env:FAUXNIX_SETVARS',
@@ -815,6 +828,11 @@ export function wrapTempEnv(sets, body, extra) {
815
828
  lines.push(vn + ' = ' + exprOfWord(sets[i].value, { preserveCmdSub: true }));
816
829
  }
817
830
  }
831
+ // Prefix substitutions may advance $? for later prefix assignments, but
832
+ // their snapshots must not replace the command arguments' incoming status.
833
+ // `env X=... cmd` passes ordinary argv and must keep those updates instead.
834
+ if (extra?.preserveArgumentStatus)
835
+ lines.push('$fx_prev = $fx_eprev' + id);
818
836
  lines.push('try {');
819
837
  for (const u of unsets) {
820
838
  const uq = u.replace(/'/g, "''");
@@ -990,29 +1008,46 @@ let pipelineSeq = 0;
990
1008
  */
991
1009
  function translateListInline(list, translation = EXECUTE_TRANSLATION) {
992
1010
  const chunks = [];
993
- for (const seg of list.segments) {
1011
+ list.segments.forEach((seg, i) => {
994
1012
  const { defs, call } = translatePipelineBody(seg.pipeline, translation);
995
1013
  const body = (defs ? defs + '\n' : '') + call;
1014
+ if (i === 0) {
1015
+ chunks.push(body);
1016
+ return;
1017
+ }
1018
+ // Bash: every completed command updates $?, and the next element's own
1019
+ // &&/|| chain starts fresh (#238). Snapshot the running status into
1020
+ // $fx_prev (the $? source inside a segment — this also preserves the
1021
+ // pre-compound status a body-entry $? reads), then reset the chain
1022
+ // state inside the element's guard so a skipped element cannot clobber
1023
+ // it.
1024
+ const snapshot = '$fx_prev = [string]$script:fx_exit';
996
1025
  if (seg.op === '&&') {
997
- chunks.push('if ($script:fx_exit -eq 0) {\n' + body + '\n}');
1026
+ chunks.push(snapshot + '\nif ($script:fx_exit -eq 0) {\n$script:fx_exit = 0\n' + body + '\n}');
998
1027
  }
999
1028
  else if (seg.op === '||') {
1000
- chunks.push('if ($script:fx_exit -ne 0) {\n' + body + '\n}');
1029
+ chunks.push(snapshot + '\nif ($script:fx_exit -ne 0) {\n$script:fx_exit = 0\n' + body + '\n}');
1001
1030
  }
1002
1031
  else {
1003
- chunks.push(body);
1032
+ chunks.push(snapshot + '\n$script:fx_exit = 0\n' + body);
1004
1033
  }
1005
- }
1034
+ });
1006
1035
  return chunks.join('\n');
1007
1036
  }
1008
1037
  function translateIf(cmd, translation) {
1009
1038
  // Branch bodies reset fx_exit first: the compound's exit status must come
1010
1039
  // from the taken branch's last command (bash semantics), not leak the test's
1011
1040
  // failure — `if false; then A; else B; fi` exits 0 in bash.
1012
- const lines = [translateListInline(cmd.test, translation), 'if ($script:fx_exit -eq 0) {', ' $script:fx_exit = 0'];
1041
+ const lines = [
1042
+ translateListInline(cmd.test, translation),
1043
+ 'if ($script:fx_exit -eq 0) {',
1044
+ // Body-entry $? reads the test's status (bash); then reset the chain.
1045
+ ' $fx_prev = [string]$script:fx_exit',
1046
+ ' $script:fx_exit = 0',
1047
+ ];
1013
1048
  for (const l of translateListInline(cmd.then, translation).split('\n'))
1014
1049
  lines.push(l ? ' ' + l : l);
1015
- lines.push('} else {', ' $script:fx_exit = 0');
1050
+ lines.push('} else {', ' $fx_prev = [string]$script:fx_exit', ' $script:fx_exit = 0');
1016
1051
  if (cmd.else) {
1017
1052
  for (const l of translateListInline(cmd.else, translation).split('\n'))
1018
1053
  lines.push(l ? ' ' + l : l);
@@ -1029,6 +1064,9 @@ function translateCase(cmd, translation) {
1029
1064
  lines.push(head + ' (fx-casematch $fx_cw @(' + pats + ')) {');
1030
1065
  const body = translateListInline(arm.body, translation);
1031
1066
  if (body) {
1067
+ // Arm entry starts the body's own chain fresh (#238); an empty arm
1068
+ // keeps the top-of-case 0, matching bash's empty-body case status.
1069
+ lines.push(' $script:fx_exit = 0');
1032
1070
  for (const l of body.split('\n'))
1033
1071
  lines.push(l ? ' ' + l : l);
1034
1072
  }
@@ -1057,9 +1095,17 @@ function translateFor(cmd, translation) {
1057
1095
  " $fx_sv += ('" +
1058
1096
  n +
1059
1097
  "' + [string][char]61 + (fx-svenc ([string]$fx_it))); $env:FAUXNIX_SETVALS = ($fx_sv -join [string][char]10)",
1098
+ // Each iteration starts the body's own chain fresh (#238); the loop's
1099
+ // exit status is still the last command of the final iteration.
1100
+ ' $script:fx_exit = 0',
1060
1101
  ];
1061
- for (const l of translateListInline(cmd.body, translation).split('\n'))
1062
- lines.push(l ? ' ' + l : l);
1102
+ lines.push(' try {');
1103
+ for (const l of withLoopBody(() => translateListInline(cmd.body, translation)).split('\n'))
1104
+ lines.push(l ? ' ' + l : l);
1105
+ // Continue exits nested command script blocks before reaching the ordinary
1106
+ // body epilogue. Finally still snapshots its successful status for the next
1107
+ // iteration; the first iteration inherits the caller's snapshot.
1108
+ lines.push(' } finally {', ' $fx_prev = [string]$script:fx_exit', ' }');
1063
1109
  lines.push('}');
1064
1110
  return lines.join('\n');
1065
1111
  }
@@ -1069,13 +1115,24 @@ function translateWhile(cmd, translation) {
1069
1115
  // exit 0. Save the body status and restore it on the failing test.
1070
1116
  const fail = cmd.until ? '$script:fx_exit -eq 0' : '$script:fx_exit -ne 0';
1071
1117
  const lines = ['$fx_wst = 0', 'do {'];
1072
- for (const l of translateListInline(cmd.test, translation).split('\n'))
1118
+ // The test list re-runs every iteration: start its chain fresh too, or a
1119
+ // failing body status leaks into the next fail-check through handlers that
1120
+ // legitimately emit nothing on success (`true`).
1121
+ lines.push(' $script:fx_exit = 0');
1122
+ for (const l of withLoopBody(() => translateListInline(cmd.test, translation)).split('\n'))
1073
1123
  lines.push(l ? ' ' + l : l);
1074
1124
  lines.push(' if (' + fail + ') { $script:fx_exit = $fx_wst; break }');
1125
+ // Body-entry $? reads the test's status (bash: the passing while test / the
1126
+ // failing until test), then each iteration's chain starts fresh.
1127
+ lines.push(' $fx_prev = [string]$script:fx_exit');
1075
1128
  lines.push(' $script:fx_exit = 0');
1076
- for (const l of translateListInline(cmd.body, translation).split('\n'))
1077
- lines.push(l ? ' ' + l : l);
1078
- lines.push(' $fx_wst = $script:fx_exit');
1129
+ lines.push(' try {');
1130
+ for (const l of withLoopBody(() => translateListInline(cmd.body, translation)).split('\n'))
1131
+ lines.push(l ? ' ' + l : l);
1132
+ // Continue skips the ordinary body epilogue, including from nested if/case
1133
+ // blocks. Finally records the completed body's status on every exit path,
1134
+ // so the terminating test and the next condition's $? both see it.
1135
+ lines.push(' } finally {', ' $fx_wst = $script:fx_exit', ' $fx_prev = [string]$script:fx_exit', ' }');
1079
1136
  lines.push('} while ($true)');
1080
1137
  return lines.join('\n');
1081
1138
  }
@@ -1124,6 +1181,46 @@ function rejectNonLastFdRedirects(commands) {
1124
1181
  }
1125
1182
  }
1126
1183
  }
1184
+ /** Loop-control translation depth: >0 while translating for/while bodies. */
1185
+ let loopDepth = 0;
1186
+ function withLoopBody(emit) {
1187
+ loopDepth++;
1188
+ try {
1189
+ return emit();
1190
+ }
1191
+ finally {
1192
+ loopDepth--;
1193
+ }
1194
+ }
1195
+ function isLoopControl(c) {
1196
+ if (c.assignments.length > 0 || c.redirects.length > 0 || c.name === null)
1197
+ return false;
1198
+ const n = wordToString(c.name);
1199
+ return n === 'break' || n === 'continue';
1200
+ }
1201
+ /**
1202
+ * `break` / `continue` map to PowerShell loop flow with bash's status-0
1203
+ * semantics (`false; break` leaves the loop at 0). Bare and `break 1` are
1204
+ * supported; deeper N, pipelines, and top-level use fail loud — bash's own
1205
+ * top-level message is a non-fatal diagnostic, but silently aborting the
1206
+ * whole PowerShell script would be worse.
1207
+ */
1208
+ function translateLoopControl(c, inPipeline) {
1209
+ const name = wordToString(c.name);
1210
+ const argText = c.args.length === 0 ? '' : wordToString(c.args[0]);
1211
+ if (c.args.length > 1 || (c.args.length === 1 && argText !== '1')) {
1212
+ throw new FauxnixParseError(`fauxnix: ${name} ${argText}: breaking more than one loop level is not supported yet`);
1213
+ }
1214
+ if (inPipeline) {
1215
+ throw new FauxnixParseError(`fauxnix: ${name} in a pipeline is not supported yet`);
1216
+ }
1217
+ if (loopDepth === 0) {
1218
+ return ("[Console]::Error.WriteLine('bash: " +
1219
+ name +
1220
+ ": only meaningful in a for, while, or until loop'); $script:fx_exit = 0");
1221
+ }
1222
+ return '$script:fx_exit = 0\n' + name;
1223
+ }
1127
1224
  export function translatePipelineBody(p, translation = EXECUTE_TRANSLATION) {
1128
1225
  if (translation.mode === 'pure') {
1129
1226
  for (const command of p.commands)
@@ -1152,6 +1249,8 @@ export function translatePipelineBody(p, translation = EXECUTE_TRANSLATION) {
1152
1249
  bodies.push(translateWhile(c, translation));
1153
1250
  else if (c.kind === 'Case')
1154
1251
  bodies.push(translateCase(c, translation));
1252
+ else if (isLoopControl(c))
1253
+ bodies.push(translateLoopControl(c, p.commands.length > 1));
1155
1254
  else
1156
1255
  bodies.push(translateSimple(c, position, hasStdin, translation));
1157
1256
  }