fauxnix-cli 0.11.0 → 0.13.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.
@@ -1,7 +1,181 @@
1
- import { FauxnixParseError, isUnquotedLiteral, } from './ast.js';
1
+ import { FauxnixParseError, isUnquotedLiteral, wordToString, } from './ast.js';
2
2
  import { parseCommand } from './parser.js';
3
3
  import { lookup, psStr } from './registry.js';
4
4
  import { PYTHON3_WINDOWS_HINT, SH_SCRIPT_WINDOWS_HINT } from './errors.js';
5
+ export const EXECUTE_TRANSLATION = Object.freeze({ mode: 'execute' });
6
+ export const PURE_TRANSLATION = Object.freeze({ mode: 'pure' });
7
+ export const PURE_SED_FILE_MESSAGE = 'fauxnix: translate does not read sed script files; use -e with the script text, or run the command to use -f';
8
+ /** Match the sed option rules without opening the referenced script file. */
9
+ function sedUsesScriptFile(args) {
10
+ const raw = args.map((word) => wordToString(word));
11
+ let onlyOperands = false;
12
+ for (let i = 0; i < raw.length; i++) {
13
+ const arg = raw[i];
14
+ if (!onlyOperands && arg === '--') {
15
+ onlyOperands = true;
16
+ continue;
17
+ }
18
+ if (onlyOperands || !arg.startsWith('-') || arg.length === 1 || arg.startsWith('--')) {
19
+ continue;
20
+ }
21
+ const body = arg.slice(1);
22
+ for (let c = 0; c < body.length; c++) {
23
+ const flag = body[c];
24
+ if (flag === 'f')
25
+ return c < body.length - 1 || i + 1 < raw.length;
26
+ if (flag === 'e') {
27
+ if (c === body.length - 1)
28
+ i++;
29
+ break;
30
+ }
31
+ if (flag === 'i')
32
+ break;
33
+ if (!['n', 'E', 'r', 's', 'u', 'z'].includes(flag))
34
+ return false;
35
+ }
36
+ }
37
+ return false;
38
+ }
39
+ function assertPureWord(word) {
40
+ const visitPart = (part) => {
41
+ if (part.kind === 'CmdSub') {
42
+ assertPureCommandList(parseCommand(part.cmd));
43
+ }
44
+ else if (part.kind === 'DoubleQuoted' || part.kind === 'Arith') {
45
+ for (const nested of part.parts)
46
+ visitPart(nested);
47
+ }
48
+ };
49
+ for (const part of word)
50
+ visitPart(part);
51
+ }
52
+ function wrappedSimpleCommand(command, name) {
53
+ const raw = command.args.map((word) => wordToString(word));
54
+ let commandIndex = -1;
55
+ if (name === 'env') {
56
+ for (let i = 0; i < raw.length;) {
57
+ const arg = raw[i];
58
+ if (arg === '--') {
59
+ commandIndex = i + 1;
60
+ break;
61
+ }
62
+ if (arg === '-i' || arg === '--ignore-environment')
63
+ return null;
64
+ if (arg === '-u' || arg === '--unset') {
65
+ i += 2;
66
+ continue;
67
+ }
68
+ if (arg.startsWith('-u=') || arg.startsWith('--unset=')) {
69
+ i++;
70
+ continue;
71
+ }
72
+ if (arg.startsWith('-')) {
73
+ i++;
74
+ continue;
75
+ }
76
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
77
+ i++;
78
+ continue;
79
+ }
80
+ commandIndex = i;
81
+ break;
82
+ }
83
+ }
84
+ else if (name === 'command') {
85
+ let identify = false;
86
+ let i = 0;
87
+ while (i < raw.length) {
88
+ const arg = raw[i];
89
+ if (arg === '-v' || arg === '-V') {
90
+ identify = true;
91
+ i++;
92
+ continue;
93
+ }
94
+ if (arg === '--') {
95
+ i++;
96
+ break;
97
+ }
98
+ if (arg.startsWith('-')) {
99
+ i++;
100
+ continue;
101
+ }
102
+ break;
103
+ }
104
+ if (identify)
105
+ return null;
106
+ commandIndex = i;
107
+ }
108
+ else if (name === 'timeout') {
109
+ let i = 0;
110
+ while (i < raw.length && raw[i].startsWith('-') && raw[i] !== '-' && raw[i] !== '--')
111
+ i++;
112
+ if (i < raw.length && raw[i] === '--')
113
+ i++;
114
+ commandIndex = i + 1;
115
+ }
116
+ if (commandIndex < 0 || commandIndex >= command.args.length)
117
+ return null;
118
+ return {
119
+ kind: 'SimpleCommand',
120
+ assignments: [],
121
+ name: command.args[commandIndex],
122
+ args: command.args.slice(commandIndex + 1),
123
+ redirects: [],
124
+ };
125
+ }
126
+ function assertPureShellCommand(command) {
127
+ if (command.kind === 'SimpleCommand') {
128
+ const name = command.name === null ? null : literalOfWord(command.name);
129
+ if (name === 'sed' && sedUsesScriptFile(command.args)) {
130
+ throw new FauxnixParseError(PURE_SED_FILE_MESSAGE);
131
+ }
132
+ if (command.name)
133
+ assertPureWord(command.name);
134
+ for (const arg of command.args)
135
+ assertPureWord(arg);
136
+ for (const assignment of command.assignments) {
137
+ assertPureWord(assignment.value);
138
+ for (const value of assignment.values ?? [])
139
+ assertPureWord(value);
140
+ }
141
+ if (name === 'env' || name === 'command' || name === 'timeout') {
142
+ const nested = wrappedSimpleCommand(command, name);
143
+ if (nested)
144
+ assertPureShellCommand(nested);
145
+ }
146
+ return;
147
+ }
148
+ if (command.kind === 'If') {
149
+ assertPureCommandList(command.test);
150
+ assertPureCommandList(command.then);
151
+ if (command.else)
152
+ assertPureCommandList(command.else);
153
+ return;
154
+ }
155
+ if (command.kind === 'For') {
156
+ for (const word of command.words)
157
+ assertPureWord(word);
158
+ assertPureCommandList(command.body);
159
+ return;
160
+ }
161
+ if (command.kind === 'While') {
162
+ assertPureCommandList(command.test);
163
+ assertPureCommandList(command.body);
164
+ return;
165
+ }
166
+ assertPureWord(command.word);
167
+ for (const arm of command.arms) {
168
+ for (const pattern of arm.patterns)
169
+ assertPureWord(pattern);
170
+ assertPureCommandList(arm.body);
171
+ }
172
+ }
173
+ function assertPureCommandList(list) {
174
+ for (const segment of list.segments) {
175
+ for (const command of segment.pipeline.commands)
176
+ assertPureShellCommand(command);
177
+ }
178
+ }
5
179
  /* ------------------------------------------------------------------ */
6
180
  /* Variable mapping */
7
181
  /* ------------------------------------------------------------------ */
@@ -421,8 +595,8 @@ export function argListExpr(words, fn = exprOfWord) {
421
595
  * Lists (`;` `&&` `||`) reuse translateListInline inside the fx-csub
422
596
  * scriptblock so the newline contract is unchanged.
423
597
  */
424
- export function translateCmdSub(cmdText, keepNl = false) {
425
- const inner = translateListInline(parseCommand(cmdText));
598
+ export function translateCmdSub(cmdText, keepNl = false, translation = EXECUTE_TRANSLATION) {
599
+ const inner = translateListInline(parseCommand(cmdText), translation);
426
600
  const collected = '(fx-csub { ' + inner + ' })';
427
601
  if (keepNl)
428
602
  return collected;
@@ -439,7 +613,10 @@ function indentBlock(s) {
439
613
  .map((l) => (l ? ' ' + l : l))
440
614
  .join('\n');
441
615
  }
442
- export function translateSimple(cmd, position, hasStdin) {
616
+ export function translateSimple(cmd, position, hasStdin, translation = EXECUTE_TRANSLATION) {
617
+ const nativeTerm = "(-not $script:fx_csub -and (($MyInvocation.MyCommand.Name -eq '') -or " +
618
+ (position === 'last' ? '$true' : '$false') +
619
+ '))';
443
620
  // assignment-only segment (`X=1; cmd`): bash semantics are "set for the
444
621
  // rest of the shell". Reuse the export code path — persist + env shadow —
445
622
  // so empty values (`X=`) and `[[ -v X ]]` behave like bash (documented
@@ -456,8 +633,9 @@ export function translateSimple(cmd, position, hasStdin) {
456
633
  }
457
634
  else {
458
635
  const words = [[{ kind: 'Text', text: a.name + '=' }, ...a.value]];
459
- if (exportHandler)
460
- chunks.push(exportHandler(words, { position, hasStdin }));
636
+ if (exportHandler) {
637
+ chunks.push(exportHandler(words, { position, hasStdin, translationMode: translation.mode }));
638
+ }
461
639
  }
462
640
  }
463
641
  return chunks.join('\n');
@@ -475,7 +653,7 @@ export function translateSimple(cmd, position, hasStdin) {
475
653
  name: cmd.args[0],
476
654
  args: cmd.args.slice(1),
477
655
  redirects: cmd.redirects,
478
- }, position, hasStdin);
656
+ }, position, hasStdin, translation);
479
657
  const emptyCmdLines = [
480
658
  '$fx_cw = @(' + splatLoadCall(nameSplat.name) + ')',
481
659
  ];
@@ -491,20 +669,23 @@ export function translateSimple(cmd, position, hasStdin) {
491
669
  emptyCmdLines.push('if ($fx_cw.Count -eq 0) {',
492
670
  // No words left → bash null command (exit 0). Remaining words are
493
671
  // known at compile time, so reuse translateSimple (handlers, not `&`).
494
- promoted ? indentBlock(promoted) : ' ', '} else {', ' $fx_na = [object[]](' + argListExpr(cmd.args) + ')', ' $fx_cmd = [string]$fx_cw[0]', ' if ($fx_cw.Count -gt 1) { $fx_na = [object[]](@($fx_cw[1..($fx_cw.Count - 1)]) + $fx_na) }', ' ' + (hasStdin ? '($input | fx-native $fx_cmd $fx_na)' : 'fx-native $fx_cmd $fx_na'), '}');
672
+ promoted ? indentBlock(promoted) : ' ', '} else {', ' $fx_na = [object[]](' + argListExpr(cmd.args) + ')', ' $fx_cmd = [string]$fx_cw[0]', ' if ($fx_cw.Count -gt 1) { $fx_na = [object[]](@($fx_cw[1..($fx_cw.Count - 1)]) + $fx_na) }', ' ' +
673
+ (hasStdin
674
+ ? '($input | fx-native $fx_cmd $fx_na ' + nativeTerm + ')'
675
+ : 'fx-native $fx_cmd $fx_na ' + nativeTerm), '}');
495
676
  body = emptyCmdLines.join('\n');
496
677
  }
497
678
  else if (nameLit !== null) {
498
679
  const handler = lookup(nameLit);
499
680
  if (handler && !(nameLit === '[[' && !isUnquotedLiteral(cmd.name, '[['))) {
500
- body = handler(cmd.args, { position, hasStdin });
681
+ body = handler(cmd.args, { position, hasStdin, translationMode: translation.mode });
501
682
  }
502
683
  else {
503
684
  // passthrough: native command (git, node, npm, python, cargo, ...)
504
685
  // via fx-native (Win32 command line + Process). `& name @array` on
505
686
  // PS 5.1 drops empty argv entries and eats embedded quotes.
506
687
  const nameExpr = psStr(nameLit);
507
- const invoke = 'fx-native ' + nameExpr + ' $fx_na';
688
+ const invoke = 'fx-native ' + nameExpr + ' $fx_na ' + nativeTerm;
508
689
  body = [
509
690
  '$fx_na = [object[]](' + argListExpr(cmd.args) + ')',
510
691
  (hasStdin ? '($input | ' + invoke + ')' : invoke),
@@ -514,7 +695,7 @@ export function translateSimple(cmd, position, hasStdin) {
514
695
  else {
515
696
  // dynamic command name — evaluate it
516
697
  const nameExpr = exprOfWord(cmd.name);
517
- const invoke = 'fx-native (' + nameExpr + ') $fx_na';
698
+ const invoke = 'fx-native (' + nameExpr + ') $fx_na ' + nativeTerm;
518
699
  body = [
519
700
  '$fx_na = [object[]](' + argListExpr(cmd.args) + ')',
520
701
  (hasStdin ? '($input | ' + invoke + ')' : invoke),
@@ -807,10 +988,10 @@ let pipelineSeq = 0;
807
988
  * multi-command pipelines become generated functions chained with `|`
808
989
  * (PS 5.1 forbids parenthesized expressions as non-first pipeline elements).
809
990
  */
810
- function translateListInline(list) {
991
+ function translateListInline(list, translation = EXECUTE_TRANSLATION) {
811
992
  const chunks = [];
812
993
  for (const seg of list.segments) {
813
- const { defs, call } = translatePipelineBody(seg.pipeline);
994
+ const { defs, call } = translatePipelineBody(seg.pipeline, translation);
814
995
  const body = (defs ? defs + '\n' : '') + call;
815
996
  if (seg.op === '&&') {
816
997
  chunks.push('if ($script:fx_exit -eq 0) {\n' + body + '\n}');
@@ -824,29 +1005,29 @@ function translateListInline(list) {
824
1005
  }
825
1006
  return chunks.join('\n');
826
1007
  }
827
- function translateIf(cmd) {
1008
+ function translateIf(cmd, translation) {
828
1009
  // Branch bodies reset fx_exit first: the compound's exit status must come
829
1010
  // from the taken branch's last command (bash semantics), not leak the test's
830
1011
  // failure — `if false; then A; else B; fi` exits 0 in bash.
831
- const lines = [translateListInline(cmd.test), 'if ($script:fx_exit -eq 0) {', ' $script:fx_exit = 0'];
832
- for (const l of translateListInline(cmd.then).split('\n'))
1012
+ const lines = [translateListInline(cmd.test, translation), 'if ($script:fx_exit -eq 0) {', ' $script:fx_exit = 0'];
1013
+ for (const l of translateListInline(cmd.then, translation).split('\n'))
833
1014
  lines.push(l ? ' ' + l : l);
834
1015
  lines.push('} else {', ' $script:fx_exit = 0');
835
1016
  if (cmd.else) {
836
- for (const l of translateListInline(cmd.else).split('\n'))
1017
+ for (const l of translateListInline(cmd.else, translation).split('\n'))
837
1018
  lines.push(l ? ' ' + l : l);
838
1019
  }
839
1020
  lines.push('}');
840
1021
  return lines.join('\n');
841
1022
  }
842
- function translateCase(cmd) {
1023
+ function translateCase(cmd, translation) {
843
1024
  const lines = ['$script:fx_exit = 0', '$fx_cw = ' + exprOfWord(cmd.word)];
844
1025
  for (let i = 0; i < cmd.arms.length; i++) {
845
1026
  const arm = cmd.arms[i];
846
1027
  const pats = arm.patterns.map((w) => exprOfWord(w)).join(',');
847
1028
  const head = i === 0 ? 'if' : 'elseif';
848
1029
  lines.push(head + ' (fx-casematch $fx_cw @(' + pats + ')) {');
849
- const body = translateListInline(arm.body);
1030
+ const body = translateListInline(arm.body, translation);
850
1031
  if (body) {
851
1032
  for (const l of body.split('\n'))
852
1033
  lines.push(l ? ' ' + l : l);
@@ -855,7 +1036,7 @@ function translateCase(cmd) {
855
1036
  }
856
1037
  return lines.join('\n');
857
1038
  }
858
- function translateFor(cmd) {
1039
+ function translateFor(cmd, translation) {
859
1040
  const n = cmd.name.replace(/'/g, "''");
860
1041
  const lines = [
861
1042
  '$fx_for = ' + argListExpr(cmd.words),
@@ -877,22 +1058,22 @@ function translateFor(cmd) {
877
1058
  n +
878
1059
  "' + [string][char]61 + (fx-svenc ([string]$fx_it))); $env:FAUXNIX_SETVALS = ($fx_sv -join [string][char]10)",
879
1060
  ];
880
- for (const l of translateListInline(cmd.body).split('\n'))
1061
+ for (const l of translateListInline(cmd.body, translation).split('\n'))
881
1062
  lines.push(l ? ' ' + l : l);
882
1063
  lines.push('}');
883
1064
  return lines.join('\n');
884
1065
  }
885
- function translateWhile(cmd) {
1066
+ function translateWhile(cmd, translation) {
886
1067
  // Bash: last executed body owns status; a test that ends the loop does not.
887
1068
  // Never-entered loops (`while false; do …; done`, `until true; do …; done`)
888
1069
  // exit 0. Save the body status and restore it on the failing test.
889
1070
  const fail = cmd.until ? '$script:fx_exit -eq 0' : '$script:fx_exit -ne 0';
890
1071
  const lines = ['$fx_wst = 0', 'do {'];
891
- for (const l of translateListInline(cmd.test).split('\n'))
1072
+ for (const l of translateListInline(cmd.test, translation).split('\n'))
892
1073
  lines.push(l ? ' ' + l : l);
893
1074
  lines.push(' if (' + fail + ') { $script:fx_exit = $fx_wst; break }');
894
1075
  lines.push(' $script:fx_exit = 0');
895
- for (const l of translateListInline(cmd.body).split('\n'))
1076
+ for (const l of translateListInline(cmd.body, translation).split('\n'))
896
1077
  lines.push(l ? ' ' + l : l);
897
1078
  lines.push(' $fx_wst = $script:fx_exit');
898
1079
  lines.push('} while ($true)');
@@ -917,19 +1098,41 @@ function isStdoutFileRedirect(op) {
917
1098
  return op === '>' || op === '>>' || op === '&>' || op === '&>>';
918
1099
  }
919
1100
  const NONLAST_STDOUT_REDIRECT_MSG = 'fauxnix: stdout redirect on a non-last pipeline stage is not supported yet; write the file in a previous list segment (cmd >f; cat f) or wait for per-stage fds (#157)';
920
- function rejectNonLastStdoutRedirects(commands) {
1101
+ const NONLAST_STDERR_FILE_REDIRECT_MSG = 'fauxnix: stderr redirect ({op}) on a non-last pipeline stage is not supported yet; spool the stage first (cmd >out {op}err; cat out | next) or wait for per-stage fds (#157)';
1102
+ function nonLastFdRedirectMessage(op) {
1103
+ if (isStdoutFileRedirect(op))
1104
+ return NONLAST_STDOUT_REDIRECT_MSG;
1105
+ if (op === '2>' || op === '2>>') {
1106
+ return NONLAST_STDERR_FILE_REDIRECT_MSG.replaceAll('{op}', op);
1107
+ }
1108
+ if (op === '2>&1') {
1109
+ return 'fauxnix: 2>&1 on a non-last pipeline stage is not supported yet; spool the merged output first (cmd >out 2>&1; cat out | next) or wait for per-stage fds (#157)';
1110
+ }
1111
+ if (op === '1>&2') {
1112
+ return 'fauxnix: 1>&2 on a non-last pipeline stage is not supported yet; run the stage separately (cmd 1>&2; next </dev/null) or wait for per-stage fds (#157)';
1113
+ }
1114
+ return null;
1115
+ }
1116
+ function rejectNonLastFdRedirects(commands) {
921
1117
  if (commands.length < 2)
922
1118
  return;
923
1119
  for (let i = 0; i < commands.length - 1; i++) {
924
- if (commands[i].redirects.some((r) => isStdoutFileRedirect(r.op))) {
925
- throw new FauxnixParseError(NONLAST_STDOUT_REDIRECT_MSG);
1120
+ for (const redirect of commands[i].redirects) {
1121
+ const message = nonLastFdRedirectMessage(redirect.op);
1122
+ if (message)
1123
+ throw new FauxnixParseError(message);
926
1124
  }
927
1125
  }
928
1126
  }
929
- export function translatePipelineBody(p) {
930
- // Last-stage `>` is Node apply; a non-last `>` would truncate the file and
931
- // still feed the pipe. Fail loud until in-stage writes (#157).
932
- rejectNonLastStdoutRedirects(p.commands);
1127
+ export function translatePipelineBody(p, translation = EXECUTE_TRANSLATION) {
1128
+ if (translation.mode === 'pure') {
1129
+ for (const command of p.commands)
1130
+ assertPureShellCommand(command);
1131
+ }
1132
+ // Last-stage output fds are applied by Node. On an earlier stage they would
1133
+ // be prepared but not owned by that stage, so output would still reach the
1134
+ // wrong destination. Fail loud until routed in-stage fds land (#157).
1135
+ rejectNonLastFdRedirects(p.commands);
933
1136
  // Every pipeline stage needs its own status slot. Handlers deliberately use
934
1137
  // `$script:fx_exit` because their helper functions run in child scopes; in a
935
1138
  // pipeline that shared flag lets an earlier failure leak into a successful
@@ -942,15 +1145,15 @@ export function translatePipelineBody(p) {
942
1145
  const hasStdin = i > 0 || c.redirects.some((r) => r.op === '<');
943
1146
  const position = i === 0 ? 'first' : i === p.commands.length - 1 ? 'last' : 'middle';
944
1147
  if (c.kind === 'If')
945
- bodies.push(translateIf(c));
1148
+ bodies.push(translateIf(c, translation));
946
1149
  else if (c.kind === 'For')
947
- bodies.push(translateFor(c));
1150
+ bodies.push(translateFor(c, translation));
948
1151
  else if (c.kind === 'While')
949
- bodies.push(translateWhile(c));
1152
+ bodies.push(translateWhile(c, translation));
950
1153
  else if (c.kind === 'Case')
951
- bodies.push(translateCase(c));
1154
+ bodies.push(translateCase(c, translation));
952
1155
  else
953
- bodies.push(translateSimple(c, position, hasStdin));
1156
+ bodies.push(translateSimple(c, position, hasStdin, translation));
954
1157
  }
955
1158
  if (bodies.length === 1) {
956
1159
  return { defs: '', call: '(& {\n' + bodies[0] + '\n})' };
@@ -1009,7 +1212,7 @@ export function translatePipelineBody(p) {
1009
1212
  ].join('\n'));
1010
1213
  return { defs: defs.join('\n'), call: pipelineName };
1011
1214
  }
1012
- export function translateCommandList(list) {
1215
+ export function translateCommandList(list, translation = EXECUTE_TRANSLATION) {
1013
1216
  const plans = [];
1014
1217
  for (const seg of list.segments) {
1015
1218
  const cmds = seg.pipeline.commands;
@@ -1020,7 +1223,7 @@ export function translateCommandList(list) {
1020
1223
  const stdinRedirects = cmds.length
1021
1224
  ? cmds[0].redirects.filter((r) => r.op === '<')
1022
1225
  : [];
1023
- const { defs, call } = translatePipelineBody(seg.pipeline);
1226
+ const { defs, call } = translatePipelineBody(seg.pipeline, translation);
1024
1227
  let body = defs ? defs + '\n' + call : call;
1025
1228
  // First-stage `< file` feeds stage zero via FAUXNIX_STDIN_FILE.
1026
1229
  // Later-stage `<` is owned inside the pipeline body, not this wrapper.
@@ -1070,6 +1273,7 @@ const WRAP_HELPER_ORDER = [
1070
1273
  'fx-subst',
1071
1274
  'fx-slice',
1072
1275
  'fx-winargv',
1276
+ 'fx-cmdargv',
1073
1277
  'fx-native',
1074
1278
  ];
1075
1279
  const WRAP_HELPER_DEPS = {
@@ -1095,7 +1299,8 @@ const WRAP_HELPER_DEPS = {
1095
1299
  'fx-subst': [],
1096
1300
  'fx-slice': [],
1097
1301
  'fx-winargv': [],
1098
- 'fx-native': ['fx-winargv'],
1302
+ 'fx-cmdargv': ['fx-winargv'],
1303
+ 'fx-native': ['fx-cmdargv'],
1099
1304
  };
1100
1305
  /** Helpers the body calls that wrapScript still has to emit (not already defined there). */
1101
1306
  function wrapHelpersNeeded(body) {
@@ -1144,13 +1349,13 @@ function wrapCwdPreamble() {
1144
1349
  '$script:fx_exit = 0',
1145
1350
  '$fx_prev = 0',
1146
1351
  'if ($env:FAUXNIX_PREV_EXIT) { try { $fx_prev = [int]$env:FAUXNIX_PREV_EXIT } catch { $fx_prev = 0 } }',
1147
- 'if ($env:FAUXNIX_CWD) { try { Set-Location -LiteralPath $env:FAUXNIX_CWD } catch {} }',
1352
+ 'if ($env:FAUXNIX_CWD -and (Get-Location).ProviderPath -cne $env:FAUXNIX_CWD) { try { Set-Location -LiteralPath $env:FAUXNIX_CWD } catch {} }',
1148
1353
  // capture AFTER the session cwd is applied — OLDPWD must refer to the
1149
1354
  // shell's previous directory, not the host process' startup directory
1150
1355
  '$fx_oldcwd = (Get-Location).ProviderPath',
1151
1356
  // .NET APIs (ReadAllBytes & friends) resolve relative paths against the
1152
1357
  // process working directory, NOT the PS location — keep them in sync.
1153
- 'try { [Environment]::CurrentDirectory = (Get-Location).ProviderPath } catch {}',
1358
+ 'try { if ([Environment]::CurrentDirectory -cne $fx_oldcwd) { [Environment]::CurrentDirectory = $fx_oldcwd } } catch {}',
1154
1359
  ];
1155
1360
  }
1156
1361
  function wrapBodyAndPersist(body, exitProcess) {
@@ -1165,12 +1370,20 @@ function wrapBodyAndPersist(body, exitProcess) {
1165
1370
  ' $script:fx_exit = 1',
1166
1371
  '}',
1167
1372
  '# persist session cwd and environment for the next segment',
1168
- 'try { [IO.File]::WriteAllText($env:FAUXNIX_CWD_FILE, (Get-Location).Path) } catch {}',
1373
+ ...(exitProcess ? [
1374
+ 'try { [IO.File]::WriteAllText($env:FAUXNIX_CWD_FILE, (Get-Location).Path) } catch {}',
1375
+ ] : [
1376
+ 'try { [FauxnixSessionState]::SaveCwd($env:FAUXNIX_CWD_FILE, (Get-Location).Path) } catch {}',
1377
+ ]),
1169
1378
  'if ((Get-Location).Path -ne $fx_oldcwd) { $env:FAUXNIX_OLDPWD = $fx_oldcwd }',
1170
1379
  'try {',
1171
- ' $envObj = @{}',
1172
- ' Get-ChildItem Env: | ForEach-Object { $envObj[$_.Name] = $_.Value }',
1173
- ' [IO.File]::WriteAllText($env:FAUXNIX_ENV_FILE, (ConvertTo-Json $envObj -Compress))',
1380
+ ...(exitProcess ? [
1381
+ ' $envObj = @{}',
1382
+ ' Get-ChildItem Env: | ForEach-Object { $envObj[$_.Name] = $_.Value }',
1383
+ ' [IO.File]::WriteAllText($env:FAUXNIX_ENV_FILE, (ConvertTo-Json $envObj -Compress))',
1384
+ ] : [
1385
+ ' [FauxnixSessionState]::SaveEnvironment($env:FAUXNIX_ENV_FILE)',
1386
+ ]),
1174
1387
  '} catch {}',
1175
1388
  ];
1176
1389
  if (exitProcess)
@@ -1529,8 +1742,48 @@ export function wrapScript(body, opts = {}) {
1529
1742
  " return (($parts.ToArray()) -join ' ')",
1530
1743
  '}',
1531
1744
  ],
1745
+ 'fx-cmdargv': [
1746
+ 'function fx-cmdargv($argv) {',
1747
+ // cmd.exe performs percent expansion even inside quotes, and embedded
1748
+ // quotes can reopen its metacharacter grammar. CR/LF/NUL cannot be
1749
+ // represented as one batch argument. Reject those values instead of
1750
+ // silently handing a different argv to the shim.
1751
+ ' if ($null -eq $argv) { $argv = @() }',
1752
+ ' foreach ($a in @($argv)) {',
1753
+ ' $s = [string]$a',
1754
+ " if ($s.IndexOf('%') -ge 0) { throw \"fauxnix: cannot pass '%' to a .cmd/.bat file without changing the argument; invoke the underlying executable directly\" }",
1755
+ ' if ($s.IndexOf([char]34) -ge 0) { throw \'fauxnix: cannot pass a double quote to a .cmd/.bat file without changing the argument; invoke the underlying executable directly\' }',
1756
+ ' if ($s.IndexOf([char]13) -ge 0 -or $s.IndexOf([char]10) -ge 0) { throw \'fauxnix: cannot pass a line break to a .cmd/.bat file as one argument; invoke the underlying executable directly\' }',
1757
+ ' if ($s.IndexOf([char]0) -ge 0) { throw \'fauxnix: cannot pass NUL to a .cmd/.bat file as one argument; invoke the underlying executable directly\' }',
1758
+ ' }',
1759
+ ' return (fx-winargv $argv $true)',
1760
+ '}',
1761
+ ],
1532
1762
  'fx-native': [
1533
- 'function fx-native($name, $argv) {',
1763
+ "if (-not ('FauxnixTextPump' -as [type])) {",
1764
+ " Add-Type -TypeDefinition @'",
1765
+ 'using System;',
1766
+ 'using System.IO;',
1767
+ 'using System.Text;',
1768
+ 'using System.Threading.Tasks;',
1769
+ 'public static class FauxnixTextPump {',
1770
+ ' public static async Task CopyAsync(TextReader reader, TextWriter writer) {',
1771
+ ' var buffer = new char[4096];',
1772
+ ' int read;',
1773
+ ' while ((read = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) {',
1774
+ ' await writer.WriteAsync(buffer, 0, read).ConfigureAwait(false);',
1775
+ ' }',
1776
+ ' await writer.FlushAsync().ConfigureAwait(false);',
1777
+ ' }',
1778
+ ' public static async Task CopyFileAsync(TextReader reader, string path) {',
1779
+ ' using (var writer = new StreamWriter(path, false, new UTF8Encoding(false))) {',
1780
+ ' await CopyAsync(reader, writer).ConfigureAwait(false);',
1781
+ ' }',
1782
+ ' }',
1783
+ '}',
1784
+ "'@",
1785
+ '}',
1786
+ 'function fx-native($name, $argv, $term) {',
1534
1787
  ' if ($null -eq $argv) { $argv = @() } else { $argv = [object[]]@($argv) }',
1535
1788
  ' $app = Get-Command -Name $name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1',
1536
1789
  ' if ($null -eq $app) {',
@@ -1559,8 +1812,8 @@ export function wrapScript(body, opts = {}) {
1559
1812
  ' $psi = New-Object System.Diagnostics.ProcessStartInfo',
1560
1813
  ' $ext = [IO.Path]::GetExtension([string]$app.Source)',
1561
1814
  // CreateProcess cannot launch .cmd/.bat with UseShellExecute=false (npm.cmd).
1562
- // /s strips one outer quote pair from the /c tail; CRT-quote cmd
1563
- // metacharacters so `&`/`|`/`()` do not start a second command.
1815
+ // /s strips one outer quote pair from the /c tail. Build only the
1816
+ // subset of batch argv that cmd.exe can pass through unchanged.
1564
1817
  " if ($ext -eq '.cmd' -or $ext -eq '.bat') {",
1565
1818
  ' $comspec = Get-Command -Name cmd -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1',
1566
1819
  ' if ($null -eq $comspec) {',
@@ -1569,10 +1822,16 @@ export function wrapScript(body, opts = {}) {
1569
1822
  ' return',
1570
1823
  ' }',
1571
1824
  ' $psi.FileName = $comspec.Source',
1572
- ' $fx_app = fx-winargv $app.Source $true',
1573
- ' $fx_rest = fx-winargv $argv $true',
1825
+ ' try {',
1826
+ ' $fx_app = fx-cmdargv $app.Source',
1827
+ ' $fx_rest = fx-cmdargv $argv',
1828
+ ' } catch {',
1829
+ // Let the common wrapper report the validation error and stop the
1830
+ // current pipeline. Returning here would let xargs mask the failure.
1831
+ ' throw $_.Exception',
1832
+ ' }',
1574
1833
  " if ($fx_rest.Length -gt 0) { $fx_tail = $fx_app + ' ' + $fx_rest } else { $fx_tail = $fx_app }",
1575
- ' $psi.Arguments = \'/d /s /c "\' + $fx_tail + \'"\'',
1834
+ ' $psi.Arguments = \'/d /s /v:off /c "\' + $fx_tail + \'"\'',
1576
1835
  ' } else {',
1577
1836
  ' $psi.FileName = $app.Source',
1578
1837
  ' $psi.Arguments = fx-winargv $argv',
@@ -1583,35 +1842,40 @@ export function wrapScript(body, opts = {}) {
1583
1842
  ' $psi.RedirectStandardError = $true',
1584
1843
  ' $psi.CreateNoWindow = $true',
1585
1844
  ' $psi.WorkingDirectory = [Environment]::CurrentDirectory',
1586
- // StreamReader.ReadToEndAsync is .NET 4.5 (PS 5.1). Start readers
1587
- // before writing stdin so a chatty child cannot fill the 64KB pipe.
1845
+ // Drain both child pipes concurrently into disk-backed spools before
1846
+ // replaying them. This prevents either 64KB OS pipe from blocking the
1847
+ // child and avoids retaining the complete output in a .NET string.
1588
1848
  " if ($env:FAUXNIX_NATIVE_ENCODING -eq 'ansi') { $enc = [System.Text.Encoding]::GetEncoding(936) } else { $enc = New-Object System.Text.UTF8Encoding $false }",
1589
1849
  ' $psi.StandardOutputEncoding = $enc',
1590
1850
  ' $psi.StandardErrorEncoding = $enc',
1591
1851
  ' $p = New-Object System.Diagnostics.Process',
1592
1852
  ' $p.StartInfo = $psi',
1593
- ' [void]$p.Start()',
1594
- ' $outTask = $p.StandardOutput.ReadToEndAsync()',
1595
- ' $errTask = $p.StandardError.ReadToEndAsync()',
1596
- ' $ins = @($input)',
1597
- ' if ($ins.Count -gt 0) {',
1598
- ' foreach ($fx_ln in $ins) { $p.StandardInput.WriteLine([string]$fx_ln) }',
1599
- ' }',
1600
- ' $p.StandardInput.Close()',
1601
- ' [void][System.Threading.Tasks.Task]::WaitAll(@($outTask, $errTask))',
1602
- ' [void]$p.WaitForExit()',
1603
- ' $errt = [string]$errTask.Result',
1604
- ' if ($errt.Length -gt 0) { [Console]::Error.Write($errt) }',
1605
- ' $t = [string]$outTask.Result',
1606
- " $t = $t.Replace(([string][char]13 + [string][char]10), [string][char]10).Replace([string][char]13, [string][char]10)",
1607
- " if ($t -ne '') {",
1608
- ' $parts = @($t.Split([char]10))',
1609
- " if ($parts.Count -gt 0 -and $parts[$parts.Count - 1] -eq '') { $parts = $parts[0..($parts.Count - 2)] }",
1610
- ' foreach ($fx_ol in $parts) { $fx_ol }',
1853
+ ' $fx_no = $null',
1854
+ ' $fx_spoolUtf8 = New-Object System.Text.UTF8Encoding $false',
1855
+ ' try {',
1856
+ ' if (-not $term) {',
1857
+ " if ($env:FAUXNIX_NATIVE_SPOOL_DIR) { [void][IO.Directory]::CreateDirectory($env:FAUXNIX_NATIVE_SPOOL_DIR); $fx_no = Join-Path $env:FAUXNIX_NATIVE_SPOOL_DIR (([guid]::NewGuid().ToString('N')) + '.out') }",
1858
+ ' else { $fx_no = [IO.Path]::GetTempFileName() }',
1859
+ ' }',
1860
+ ' [void]$p.Start()',
1861
+ ' if ($term) { $outTask = [FauxnixTextPump]::CopyAsync($p.StandardOutput, [Console]::Out) }',
1862
+ ' else { $outTask = [FauxnixTextPump]::CopyFileAsync($p.StandardOutput, $fx_no) }',
1863
+ ' $errTask = [FauxnixTextPump]::CopyAsync($p.StandardError, [Console]::Error)',
1864
+ ' foreach ($fx_ln in $input) { $p.StandardInput.WriteLine([string]$fx_ln) }',
1865
+ ' $p.StandardInput.Close()',
1866
+ ' [void][System.Threading.Tasks.Task]::WaitAll(@($outTask, $errTask))',
1867
+ ' [void]$p.WaitForExit()',
1868
+ ' if (-not $term) {',
1869
+ ' $fx_or = New-Object System.IO.StreamReader($fx_no, $fx_spoolUtf8)',
1870
+ ' try { while (($fx_line = $fx_or.ReadLine()) -ne $null) { $fx_line } }',
1871
+ ' finally { $fx_or.Dispose() }',
1872
+ ' }',
1873
+ ' $code = [int]$p.ExitCode',
1874
+ ' if ($code -gt 0) { $script:fx_exit = $code } elseif ($code -lt 0) { $script:fx_exit = 1 }',
1875
+ ' } finally {',
1876
+ ' try { $p.Close() } catch {}',
1877
+ ' if ($null -ne $fx_no) { Remove-Item -LiteralPath $fx_no -Force -ErrorAction SilentlyContinue }',
1611
1878
  ' }',
1612
- ' $code = [int]$p.ExitCode',
1613
- ' if ($code -gt 0) { $script:fx_exit = $code } elseif ($code -lt 0) { $script:fx_exit = 1 }',
1614
- ' try { $p.Close() } catch {}',
1615
1879
  '}',
1616
1880
  ],
1617
1881
  };
@@ -1631,7 +1895,7 @@ function wrapHelperCatalog() {
1631
1895
  }
1632
1896
  /**
1633
1897
  * Resident-host bootstrap: encoding + full fx-* catalog + JSON-line RPC loop.
1634
- * Loaded once via `powershell.exe -File`. Must never `exit` a successful frame.
1898
+ * Loaded once via the selected PowerShell's `-File`. Must never `exit` a successful frame.
1635
1899
  */
1636
1900
  export function hostBootstrapScript() {
1637
1901
  const helpers = wrapHelperCatalog();
@@ -1647,6 +1911,103 @@ export function hostBootstrapScript() {
1647
1911
  }
1648
1912
  /** Raw UTF-8 JSON lines on stdin/stdout; command streams captured per frame. */
1649
1913
  const HOST_RPC_LOOP = `
1914
+ if (-not ('FauxnixBoundedStream' -as [type])) {
1915
+ Add-Type -TypeDefinition @'
1916
+ using System;
1917
+ using System.IO;
1918
+ using System.Collections;
1919
+ using System.Text;
1920
+ public static class FauxnixSessionState {
1921
+ private static string previousCwdPath;
1922
+ private static string previousCwd;
1923
+ private static string previousEnvironmentPath;
1924
+ private static string previousEnvironment;
1925
+ public static void SaveCwd(string path, string cwd) {
1926
+ if (path == previousCwdPath && cwd == previousCwd && File.Exists(path)) return;
1927
+ File.WriteAllText(path, cwd, new UTF8Encoding(false));
1928
+ previousCwdPath = path;
1929
+ previousCwd = cwd;
1930
+ }
1931
+ private static void AppendJsonString(StringBuilder json, string value) {
1932
+ json.Append((char)34);
1933
+ foreach (char c in value) {
1934
+ if (c == (char)34 || c == (char)92) {
1935
+ json.Append((char)92).Append(c);
1936
+ } else if (c < 32 || Char.IsSurrogate(c)) {
1937
+ json.Append((char)92).Append('u').Append(((int)c).ToString("x4"));
1938
+ } else {
1939
+ json.Append(c);
1940
+ }
1941
+ }
1942
+ json.Append((char)34);
1943
+ }
1944
+ public static void SaveEnvironment(string path) {
1945
+ // Keep a complete snapshot: merging with the parent's environment on a
1946
+ // later restart would resurrect values removed by unset.
1947
+ IDictionary environment = Environment.GetEnvironmentVariables();
1948
+ var json = new StringBuilder(4096);
1949
+ json.Append('{');
1950
+ bool first = true;
1951
+ var keys = new string[environment.Count];
1952
+ environment.Keys.CopyTo(keys, 0);
1953
+ Array.Sort(keys, StringComparer.Ordinal);
1954
+ foreach (string key in keys) {
1955
+ // These values are request transport metadata and are always supplied
1956
+ // afresh by Node; changing them does not change persistent shell state.
1957
+ if (String.Equals(key, "FAUXNIX_NATIVE_SPOOL_DIR", StringComparison.OrdinalIgnoreCase) ||
1958
+ String.Equals(key, "FAUXNIX_PREV_EXIT", StringComparison.OrdinalIgnoreCase) ||
1959
+ String.Equals(key, "FAUXNIX_STDIN_FILE", StringComparison.OrdinalIgnoreCase) ||
1960
+ String.Equals(key, "FAUXNIX_CWD", StringComparison.OrdinalIgnoreCase)) continue;
1961
+ if (!first) json.Append(',');
1962
+ first = false;
1963
+ AppendJsonString(json, key);
1964
+ json.Append(':');
1965
+ AppendJsonString(json, (string)environment[key]);
1966
+ }
1967
+ json.Append('}');
1968
+ string current = json.ToString();
1969
+ if (path == previousEnvironmentPath && current == previousEnvironment && File.Exists(path)) return;
1970
+ File.WriteAllText(path, current, new UTF8Encoding(false));
1971
+ previousEnvironmentPath = path;
1972
+ previousEnvironment = current;
1973
+ }
1974
+ }
1975
+ public sealed class FauxnixBoundedStream : Stream {
1976
+ private readonly MemoryStream inner;
1977
+ private readonly long limit;
1978
+ private readonly long storageLimit;
1979
+ private long totalWritten;
1980
+ public bool Truncated { get; private set; }
1981
+ public FauxnixBoundedStream(long limit) {
1982
+ this.limit = Math.Max(0, limit);
1983
+ this.storageLimit = this.limit + 3;
1984
+ this.inner = new MemoryStream((int)Math.Min(this.storageLimit, 65536));
1985
+ }
1986
+ public byte[] ToArray() { return inner.ToArray(); }
1987
+ public override bool CanRead { get { return false; } }
1988
+ public override bool CanSeek { get { return false; } }
1989
+ public override bool CanWrite { get { return true; } }
1990
+ public override long Length { get { return inner.Length; } }
1991
+ public override long Position { get { return inner.Position; } set { throw new NotSupportedException(); } }
1992
+ public override void Flush() { }
1993
+ public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
1994
+ public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
1995
+ public override void SetLength(long value) { throw new NotSupportedException(); }
1996
+ public override void Write(byte[] buffer, int offset, int count) {
1997
+ long remaining = Math.Max(0, storageLimit - inner.Length);
1998
+ int keep = (int)Math.Min((long)count, remaining);
1999
+ if (keep > 0) inner.Write(buffer, offset, keep);
2000
+ totalWritten += count;
2001
+ if (totalWritten > limit) Truncated = true;
2002
+ }
2003
+ public override void WriteByte(byte value) {
2004
+ if (inner.Length < storageLimit) inner.WriteByte(value);
2005
+ totalWritten++;
2006
+ if (totalWritten > limit) Truncated = true;
2007
+ }
2008
+ }
2009
+ '@
2010
+ }
1650
2011
  $fx_utf8 = New-Object System.Text.UTF8Encoding $false
1651
2012
  $fx_in = [Console]::OpenStandardInput()
1652
2013
  $fx_out = [Console]::OpenStandardOutput()
@@ -1666,8 +2027,8 @@ function fx-emit-chunks($type, $id, [byte[]]$bytes, $limit, [ref]$seq) {
1666
2027
  if ($null -ne $bytes) { $n = $bytes.Length }
1667
2028
  $use = $n
1668
2029
  $trunc = $false
1669
- # limit 0 = uncapped (file-redirected streams must never be budget-clipped)
1670
- if ($limit -gt 0 -and $use -gt $limit) {
2030
+ # limit -1 = uncapped; zero is a real empty caller budget
2031
+ if ($limit -ge 0 -and $use -gt $limit) {
1671
2032
  $use = $limit
1672
2033
  $trunc = $true
1673
2034
  # back the cut off to a valid UTF-8 boundary — a split codepoint makes
@@ -1693,6 +2054,18 @@ function fx-emit-chunks($type, $id, [byte[]]$bytes, $limit, [ref]$seq) {
1693
2054
  }
1694
2055
  return $trunc
1695
2056
  }
2057
+ function fx-new-capture($mode, $limit, $spoolPath) {
2058
+ if ([string]$mode -eq 'discard') { return [System.IO.Stream]::Null }
2059
+ if ([string]$mode -eq 'spool') {
2060
+ return (New-Object System.IO.FileStream([string]$spoolPath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::Read))
2061
+ }
2062
+ return (New-Object FauxnixBoundedStream ([Math]::Max(0, [long]$limit)))
2063
+ }
2064
+ function fx-capture-bytes($stream) {
2065
+ if ($stream -is [FauxnixBoundedStream]) { return $stream.ToArray() }
2066
+ if ($stream -is [System.IO.MemoryStream]) { return $stream.ToArray() }
2067
+ return (New-Object byte[] 0)
2068
+ }
1696
2069
  while ($true) {
1697
2070
  $fx_line = $fx_reader.ReadLine()
1698
2071
  if ($null -eq $fx_line) { break }
@@ -1720,12 +2093,24 @@ while ($true) {
1720
2093
  }
1721
2094
  }
1722
2095
  $fx_script = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([string]$fx_req.scriptB64))
1723
- $fx_msOut = New-Object System.IO.MemoryStream
1724
- $fx_msErr = New-Object System.IO.MemoryStream
2096
+ $fx_outLimit = 8388608
2097
+ $fx_errLimit = 1048576
2098
+ if ($null -ne $fx_req.PSObject.Properties['stdoutLimit']) { $fx_outLimit = [int]$fx_req.stdoutLimit }
2099
+ if ($null -ne $fx_req.PSObject.Properties['stderrLimit']) { $fx_errLimit = [int]$fx_req.stderrLimit }
2100
+ $fx_outMode = 'capture'
2101
+ $fx_errMode = 'capture'
2102
+ $fx_outSpool = ''
2103
+ $fx_errSpool = ''
2104
+ if ($null -ne $fx_req.PSObject.Properties['stdoutMode']) { $fx_outMode = [string]$fx_req.stdoutMode }
2105
+ if ($null -ne $fx_req.PSObject.Properties['stderrMode']) { $fx_errMode = [string]$fx_req.stderrMode }
2106
+ if ($null -ne $fx_req.PSObject.Properties['stdoutSpoolPath']) { $fx_outSpool = [string]$fx_req.stdoutSpoolPath }
2107
+ if ($null -ne $fx_req.PSObject.Properties['stderrSpoolPath']) { $fx_errSpool = [string]$fx_req.stderrSpoolPath }
2108
+ $fx_msOut = fx-new-capture $fx_outMode $fx_outLimit $fx_outSpool
2109
+ $fx_msErr = fx-new-capture $fx_errMode $fx_errLimit $fx_errSpool
1725
2110
  $fx_outW = New-Object System.IO.StreamWriter($fx_msOut, $fx_utf8, 1024, $true)
1726
2111
  $fx_errW = New-Object System.IO.StreamWriter($fx_msErr, $fx_utf8, 1024, $true)
1727
- $fx_outW.NewLine = [string][char]13 + [string][char]10
1728
- $fx_errW.NewLine = [string][char]13 + [string][char]10
2112
+ $fx_outW.NewLine = [string][char]10
2113
+ $fx_errW.NewLine = [string][char]10
1729
2114
  $fx_outW.AutoFlush = $true
1730
2115
  $fx_errW.AutoFlush = $true
1731
2116
  [Console]::SetOut($fx_outW)
@@ -1753,24 +2138,29 @@ while ($true) {
1753
2138
  }
1754
2139
  $fx_outBytes = New-Object byte[] 0
1755
2140
  $fx_errBytes = New-Object byte[] 0
1756
- if ($null -ne $fx_msOut) { $fx_outBytes = $fx_msOut.ToArray() }
1757
- if ($null -ne $fx_msErr) { $fx_errBytes = $fx_msErr.ToArray() }
2141
+ if ($null -ne $fx_msOut) { $fx_outBytes = fx-capture-bytes $fx_msOut }
2142
+ if ($null -ne $fx_msErr) { $fx_errBytes = fx-capture-bytes $fx_msErr }
2143
+ try { if ($null -ne $fx_outW) { $fx_outW.Dispose() } } catch {}
2144
+ try { if ($null -ne $fx_errW) { $fx_errW.Dispose() } } catch {}
2145
+ try { if ($null -ne $fx_msOut -and $fx_msOut -ne [System.IO.Stream]::Null) { $fx_msOut.Dispose() } } catch {}
2146
+ try { if ($null -ne $fx_msErr -and $fx_msErr -ne [System.IO.Stream]::Null) { $fx_msErr.Dispose() } } catch {}
1758
2147
  if ($fx_v2) {
1759
- $fx_outLimit = 8388608
1760
- $fx_errLimit = 1048576
1761
- if ($null -ne $fx_req.PSObject.Properties['stdoutLimit']) { $fx_outLimit = [int]$fx_req.stdoutLimit }
1762
- if ($null -ne $fx_req.PSObject.Properties['stderrLimit']) { $fx_errLimit = [int]$fx_req.stderrLimit }
1763
2148
  $fx_outSeq = 0
1764
2149
  $fx_errSeq = 0
1765
- $fx_trunc = $false
1766
- if (fx-emit-chunks 'stdout' $fx_id $fx_outBytes $fx_outLimit ([ref]$fx_outSeq)) { $fx_trunc = $true }
1767
- if (fx-emit-chunks 'stderr' $fx_id $fx_errBytes $fx_errLimit ([ref]$fx_errSeq)) { $fx_trunc = $true }
2150
+ $fx_outTrunc = $false
2151
+ $fx_errTrunc = $false
2152
+ if ($fx_msOut -is [FauxnixBoundedStream] -and $fx_msOut.Truncated) { $fx_outTrunc = $true }
2153
+ if ($fx_msErr -is [FauxnixBoundedStream] -and $fx_msErr.Truncated) { $fx_errTrunc = $true }
2154
+ $fx_outEmitLimit = $(if ($fx_outMode -eq 'capture') { $fx_outLimit } else { -1 })
2155
+ $fx_errEmitLimit = $(if ($fx_errMode -eq 'capture') { $fx_errLimit } else { -1 })
2156
+ if (fx-emit-chunks 'stdout' $fx_id $fx_outBytes $fx_outEmitLimit ([ref]$fx_outSeq)) { $fx_outTrunc = $true }
2157
+ if (fx-emit-chunks 'stderr' $fx_id $fx_errBytes $fx_errEmitLimit ([ref]$fx_errSeq)) { $fx_errTrunc = $true }
1768
2158
  $fx_nativeErr = [Console]::OpenStandardError()
1769
2159
  $fx_mark = $fx_utf8.GetBytes(('FAUXNIX_ERR_END:' + $fx_id + [char]10))
1770
2160
  $fx_nativeErr.Write($fx_mark, 0, $fx_mark.Length)
1771
2161
  $fx_nativeErr.Flush()
1772
- $fx_end = '{"v":2,"type":"end","id":"' + $fx_id + '","exitCode":' + $fx_code + ',"timedOut":false,"cancelled":false,"truncated":'
1773
- if ($fx_trunc) { $fx_end = $fx_end + 'true}' } else { $fx_end = $fx_end + 'false}' }
2162
+ $fx_trunc = $fx_outTrunc -or $fx_errTrunc
2163
+ $fx_end = '{"v":2,"type":"end","id":"' + $fx_id + '","exitCode":' + $fx_code + ',"timedOut":false,"cancelled":false,"truncated":' + ([string]$fx_trunc).ToLowerInvariant() + ',"stdoutTruncated":' + ([string]$fx_outTrunc).ToLowerInvariant() + ',"stderrTruncated":' + ([string]$fx_errTrunc).ToLowerInvariant() + '}'
1774
2164
  $fx_proto.WriteLine($fx_end)
1775
2165
  } else {
1776
2166
  $fx_outB64 = ''