fauxnix-cli 0.13.0 → 2.0.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,5 +1,5 @@
1
1
  import { wordToString } from '../ast.js';
2
- import { parseWords, psErr, psStr } from '../registry.js';
2
+ import { parseWords, psErr, psErr2, psStr } from '../registry.js';
3
3
  import { argListExpr, exprOfWord, literalOfWord, operandExpr } from '../translator.js';
4
4
  /* ------------------------------------------------------------------ */
5
5
  /* Shared PS snippets */
@@ -162,7 +162,19 @@ function mapWgetArgs(args) {
162
162
  const margs = [];
163
163
  const urls = [];
164
164
  let sawOutput = false;
165
- const raw = args.map(wordToString);
165
+ let outputIndex = -1;
166
+ // wget has one output destination. curl associates repeated -o options with
167
+ // successive URLs, so keep only wget's last choice, including stdout.
168
+ const setOutput = (word) => {
169
+ if (outputIndex >= 0)
170
+ margs.splice(outputIndex, 2);
171
+ outputIndex = -1;
172
+ sawOutput = true;
173
+ if (word !== null) {
174
+ outputIndex = margs.length;
175
+ margs.push("'-o'", operandExpr(word));
176
+ }
177
+ };
166
178
  let i = 0;
167
179
  while (i < args.length) {
168
180
  const lit = literalOfWord(args[i]);
@@ -178,49 +190,30 @@ function mapWgetArgs(args) {
178
190
  margs.push("'-s'");
179
191
  const rest = m[2];
180
192
  if (rest === '') {
181
- if (i + 1 < args.length) {
182
- const v = wordToString(args[i + 1]);
183
- if (v === '-') {
184
- sawOutput = true; // -O - → curl writes to stdout by default
185
- }
186
- else {
187
- margs.push("'-o'", operandExpr(args[i + 1]));
188
- sawOutput = true;
189
- }
190
- i++;
193
+ if (i + 1 >= args.length) {
194
+ return { margs, sawOutput, urls, error: "option requires an argument -- 'O'" };
191
195
  }
192
- }
193
- else if (rest === '-') {
194
- sawOutput = true; // -O- → stdout passthrough (curl default)
196
+ const value = args[++i];
197
+ setOutput(wordToString(value) === '-' ? null : value);
195
198
  }
196
199
  else {
197
- margs.push("'-o'", operandExpr(synthWord(rest)));
198
- sawOutput = true;
200
+ setOutput(rest === '-' ? null : synthWord(rest));
199
201
  }
200
202
  i++;
201
203
  continue;
202
204
  }
203
- if (lit === '--output-document' && i + 1 < args.length) {
204
- const v = wordToString(args[i + 1]);
205
- if (v === '-') {
206
- sawOutput = true;
207
- }
208
- else {
209
- margs.push("'-o'", operandExpr(args[i + 1]));
210
- sawOutput = true;
205
+ if (lit === '--output-document') {
206
+ if (i + 1 >= args.length) {
207
+ return { margs, sawOutput, urls, error: "option requires an argument -- 'output-document'" };
211
208
  }
209
+ const value = args[i + 1];
210
+ setOutput(wordToString(value) === '-' ? null : value);
212
211
  i += 2;
213
212
  continue;
214
213
  }
215
214
  const eq = /^--output-document=(.*)$/.exec(lit);
216
215
  if (eq) {
217
- if (eq[1] === '') {
218
- sawOutput = true;
219
- }
220
- else {
221
- margs.push("'-o'", operandExpr(synthWord(eq[1])));
222
- sawOutput = true;
223
- }
216
+ setOutput(eq[1] === '-' ? null : synthWord(eq[1]));
224
217
  i++;
225
218
  continue;
226
219
  }
@@ -247,7 +240,6 @@ function mapWgetArgs(args) {
247
240
  return { margs, sawOutput, urls };
248
241
  }
249
242
  const wget = (args) => {
250
- const orig = args.map((w) => exprOfWord(w));
251
243
  const mapped = mapWgetArgs(args);
252
244
  return [
253
245
  PS_NETGUARD_FNS,
@@ -262,7 +254,7 @@ const wget = (args) => {
262
254
  '}',
263
255
  // otherwise map onto curl.exe
264
256
  'else {',
265
- " " + nativeCall('curl.exe', '$fx_margs'),
257
+ ' ' + (mapped.error ? psErr2('wget', mapped.error) : nativeCall('curl.exe', '$fx_margs')),
266
258
  '}',
267
259
  ].join('\n');
268
260
  };
@@ -151,7 +151,8 @@ const cd = (args) => {
151
151
  if (wordToString(operandWords[0]) === '-') {
152
152
  return [
153
153
  "if (-not $env:FAUXNIX_OLDPWD) { [Console]::Error.WriteLine('bash: cd: OLDPWD not set'); $script:fx_exit = 1 }",
154
- 'else { try { Set-Location -LiteralPath $env:FAUXNIX_OLDPWD } catch { [Console]::Error.WriteLine("bash: cd: " + $env:FAUXNIX_OLDPWD + ": No such file or directory"); $script:fx_exit = 1 } }',
154
+ // bash echoes the new cwd for `cd -` (and CDPATH hits); $OLDPWD/$PWD agree (#223).
155
+ 'else { try { Set-Location -LiteralPath $env:FAUXNIX_OLDPWD; fx-posix((Get-Location).Path) } catch { [Console]::Error.WriteLine("bash: cd: " + $env:FAUXNIX_OLDPWD + ": No such file or directory"); $script:fx_exit = 1 } }',
155
156
  ].join('\n');
156
157
  }
157
158
  return [
@@ -168,7 +169,8 @@ const pwd = (args) => {
168
169
  if (operandWords.length > 0)
169
170
  return psErr('pwd', "extra operand '" + wordToString(operandWords[0]) + "'. Try 'pwd --help'.");
170
171
  // -L is the default. CommandSpec rejects -P because junctions make it distinct.
171
- return "(Get-Location).Path.Replace('\\', '/')";
172
+ // bash renders the cwd POSIX-form (/d/foo); $PWD and `cd -` must agree (#223).
173
+ return 'fx-posix((Get-Location).Path)';
172
174
  };
173
175
  /* ------------------------------------------------------------------ */
174
176
  /* export / unset / env / printenv */
@@ -801,13 +803,16 @@ const date = (args) => {
801
803
  const raw = args.map(wordToString);
802
804
  let dWord = null;
803
805
  for (let k = 0; k < raw.length; k++) {
806
+ if (raw[k] === '--')
807
+ break;
804
808
  if (raw[k] === '-d' || raw[k] === '--date') {
805
809
  dWord = args[k + 1] ?? null;
806
- break;
810
+ k++;
811
+ continue;
807
812
  }
808
813
  if (raw[k].startsWith('--date=')) {
809
814
  dWord = wordAfterPrefix(args[k], '--date=');
810
- break;
815
+ continue;
811
816
  }
812
817
  if (raw[k].startsWith('-') && !raw[k].startsWith('--')) {
813
818
  const body = raw[k].slice(1);
@@ -816,7 +821,8 @@ const date = (args) => {
816
821
  const prefix = '-' + body.slice(0, dIndex + 1);
817
822
  const attached = wordAfterPrefix(args[k], prefix);
818
823
  dWord = attached && attached.length > 0 ? attached : (args[k + 1] ?? null);
819
- break;
824
+ if (body.slice(dIndex + 1) === '')
825
+ k++;
820
826
  }
821
827
  }
822
828
  }
@@ -1537,12 +1543,12 @@ const FX_ENVGET_FN = [
1537
1543
  " if (@($env:FAUXNIX_UNSETVARS -split ';' | Where-Object { $_ -ceq $n }).Count -gt 0) { return '' }",
1538
1544
  " if (@($env:FAUXNIX_SETVARS -split ';' | Where-Object { $_ -ceq $n }).Count -gt 0) { return (fx-envexplicit $n) }",
1539
1545
  " if ($n -ceq 'HOME') { return [string]$HOME }",
1540
- " if ($n -ceq 'PWD') { return [string]$PWD.Path }",
1546
+ " if ($n -ceq 'PWD') { return fx-posix([string]$PWD.Path) }",
1541
1547
  " if ($n -ceq 'USER' -or $n -ceq 'LOGNAME') { return [string]$env:USERNAME }",
1542
1548
  " if ($n -ceq 'PATH') { return [string]$env:PATH }",
1543
1549
  " if ($n -ceq 'SHELL') { return 'powershell' }",
1544
1550
  " if ($n -ceq 'TERM') { return 'xterm-256color' }",
1545
- " if ($n -ceq 'OLDPWD') { return [string]$env:FAUXNIX_OLDPWD }",
1551
+ " if ($n -ceq 'OLDPWD') { return fx-posix([string]$env:FAUXNIX_OLDPWD) }",
1546
1552
  " if ($n -ceq '?') { return [string]$fx_prev }",
1547
1553
  " if ($n -ceq '$') { return [string]$PID }",
1548
1554
  " if ($n -ceq 'HOSTNAME') { return [string]$env:COMPUTERNAME }",
@@ -2427,9 +2433,9 @@ const DIRS_STACK_PS = [
2427
2433
  "if ($env:FAUXNIX_DIRSTACK) { $fx_st = @($env:FAUXNIX_DIRSTACK -split ';' | Where-Object { $_ -ne '' }) }",
2428
2434
  ].join('\n');
2429
2435
  const DIRS_PRINT_PS = [
2430
- '$fx_l = @((Get-Location).Path)',
2431
- 'foreach ($fx_s in $fx_st) { $fx_l += $fx_s }',
2432
- "($fx_l -join ' ').Replace('\\', '/')",
2436
+ '$fx_l = @(fx-posix((Get-Location).Path))',
2437
+ 'foreach ($fx_s in $fx_st) { $fx_l += fx-posix($fx_s) }',
2438
+ "($fx_l -join ' ')",
2433
2439
  ].join('\n');
2434
2440
  const dirs = () => {
2435
2441
  return [DIRS_STACK_PS, DIRS_PRINT_PS].join('\n');
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { FauxnixParseError, wordToString } from '../ast.js';
5
5
  import { parseWords, psStr } from '../registry.js';
6
+ import { PS_WRITE_FN, fxTermLine } from './text-output.js';
6
7
  import { argListExpr, exprOfWord, literalOfWord, operandExpr, PURE_SED_FILE_MESSAGE, } from '../translator.js';
7
8
  /* ------------------------------------------------------------------ */
8
9
  /* Shared PS snippets (same shape as files.ts) */
@@ -81,105 +82,6 @@ function textExpr(w) {
81
82
  return psStr(lit);
82
83
  return exprOfWord(w);
83
84
  }
84
- /** Collect EVERY value of a short option (-kN, -k N) — parseWords keeps only the last. */
85
- function collectShortValues(args, letter) {
86
- const out = [];
87
- let onlyOps = false;
88
- for (let i = 0; i < args.length; i++) {
89
- const t = wordToString(args[i]);
90
- if (t === '--') {
91
- onlyOps = true;
92
- continue;
93
- }
94
- if (onlyOps)
95
- continue;
96
- if (t === '-' + letter) {
97
- if (i + 1 < args.length) {
98
- out.push(wordToString(args[i + 1]));
99
- i++;
100
- }
101
- }
102
- else if (t.startsWith('-' + letter) && t.length > 2 && !t.startsWith('--')) {
103
- out.push(t.slice(2));
104
- }
105
- }
106
- return out;
107
- }
108
- /** Collect repeated value-taking long options without mistaking short bundles for values. */
109
- function collectLongValues(args, names) {
110
- const out = [];
111
- let onlyOps = false;
112
- for (let i = 0; i < args.length; i++) {
113
- const t = wordToString(args[i]);
114
- if (t === '--') {
115
- onlyOps = true;
116
- continue;
117
- }
118
- if (onlyOps || !t.startsWith('--'))
119
- continue;
120
- const eq = t.indexOf('=');
121
- const name = eq >= 0 ? t.slice(0, eq) : t;
122
- if (!names.includes(name))
123
- continue;
124
- if (eq >= 0) {
125
- out.push({ name, value: t.slice(eq + 1) });
126
- }
127
- else if (i + 1 < args.length) {
128
- out.push({ name, value: wordToString(args[i + 1]) });
129
- i++;
130
- }
131
- }
132
- return out;
133
- }
134
- /**
135
- * Collect EVERY value of a short option and its long aliases, in argv order.
136
- * parseWords keeps only the last; grep -e/--regexp must OR-accumulate.
137
- * Handles -e PAT, -ePAT, -ie PAT (bundled), --regexp PAT, --regexp=PAT.
138
- */
139
- function collectRepeatOptionValues(args, short, longs) {
140
- const out = [];
141
- let onlyOps = false;
142
- for (let i = 0; i < args.length; i++) {
143
- const t = wordToString(args[i]);
144
- if (t === '--') {
145
- onlyOps = true;
146
- continue;
147
- }
148
- if (onlyOps)
149
- continue;
150
- if (t.startsWith('--')) {
151
- const eq = t.indexOf('=');
152
- const name = eq >= 0 ? t.slice(0, eq) : t;
153
- if (!longs.includes(name))
154
- continue;
155
- if (eq >= 0) {
156
- out.push(t.slice(eq + 1));
157
- }
158
- else if (i + 1 < args.length) {
159
- out.push(wordToString(args[i + 1]));
160
- i++;
161
- }
162
- continue;
163
- }
164
- if (!(t.startsWith('-') && t.length > 1 && !/^-?\d/.test(t.slice(1, 2))))
165
- continue;
166
- const body = t.slice(1);
167
- for (let c = 0; c < body.length; c++) {
168
- if (body[c] !== short)
169
- continue;
170
- const rest = body.slice(c + 1);
171
- if (rest) {
172
- out.push(rest);
173
- }
174
- else if (i + 1 < args.length) {
175
- out.push(wordToString(args[i + 1]));
176
- i++;
177
- }
178
- break;
179
- }
180
- }
181
- return out;
182
- }
183
85
  /** Build the "collect file operands through fx-glob" PS prologue. */
184
86
  function psCollectSources(filesExpr, cmdErr, leafOnly) {
185
87
  const test = leafOnly
@@ -317,12 +219,14 @@ function ereToDotNet(re) {
317
219
  /* ------------------------------------------------------------------ */
318
220
  const grep = (args) => {
319
221
  const filterOptionNames = ['--include', '--exclude', '--exclude-dir'];
320
- const filterOptions = collectLongValues(args, filterOptionNames);
222
+ const { flags, operandWords, values, valueEntries, missingValue } = parseWords(args, ['A', 'B', 'C', 'm', 'e'], [...filterOptionNames, '--max-count', '--regexp']);
223
+ // Reuse the argv walk so another option's value is never mistaken for
224
+ // a filter or repeated pattern, even when that value starts with a dash.
225
+ const filterOptions = valueEntries.filter((o) => filterOptionNames.includes(o.name));
321
226
  const fileFilterOptions = filterOptions.filter((o) => o.name !== '--exclude-dir');
322
227
  const excludeDirGlobs = filterOptions
323
228
  .filter((o) => o.name === '--exclude-dir')
324
229
  .map((o) => o.value.replace(/[\\/]+$/, ''));
325
- const { flags, operandWords, values, missingValue } = parseWords(args, ['A', 'B', 'C', 'm', 'e'], [...filterOptionNames, '--max-count', '--regexp']);
326
230
  const missingFilterOption = missingValue.find((o) => [...filterOptionNames, '-m', '--max-count', '-e', '--regexp'].includes(o));
327
231
  if (missingFilterOption) {
328
232
  return ('[Console]::Error.WriteLine(' +
@@ -358,7 +262,9 @@ const grep = (args) => {
358
262
  };
359
263
  const ctxA = Math.max(toInt(values.get('-A')), toInt(values.get('-C')));
360
264
  const ctxB = Math.max(toInt(values.get('-B')), toInt(values.get('-C')));
361
- const regexpPats = collectRepeatOptionValues(args, 'e', ['--regexp']);
265
+ const regexpPats = valueEntries
266
+ .filter((o) => o.name === '-e' || o.name === '--regexp')
267
+ .map((o) => o.value);
362
268
  if (regexpPats.length === 0 && operandWords.length === 0) {
363
269
  return ("[Console]::Error.WriteLine('usage: grep [OPTION]... PATTERN [FILE]...'); $script:fx_exit = 2");
364
270
  }
@@ -1782,7 +1688,7 @@ function awkFmtToPs(fmt) {
1782
1688
  const ps = chunks.length === 0 ? "''" : '(' + chunks.join(' + ') + ')';
1783
1689
  return { ps, kinds };
1784
1690
  }
1785
- const awk = (args) => {
1691
+ const awk = (args, ctx) => {
1786
1692
  const { values, operandWords } = parseWords(args, ['F', 'v']);
1787
1693
  // -v may repeat; collect all of them
1788
1694
  const vvars = [];
@@ -1834,6 +1740,11 @@ const awk = (args) => {
1834
1740
  }
1835
1741
  const fileWords = operandWords.slice(1);
1836
1742
  const prog = new AwkParser(progLit).parse();
1743
+ // A printf program produces one text stream, not one line per statement.
1744
+ // Pipeline/substitution consumers require one object to avoid synthetic
1745
+ // separators. Direct terminal/file-spool output can stream each fragment.
1746
+ const exactOutput = [...prog.begin, ...prog.items.flatMap((item) => item.act ?? []), ...prog.end]
1747
+ .some((statement) => statement.k === 'printf');
1837
1748
  // FS mode
1838
1749
  const fsRaw = values.get('-F') ?? ' ';
1839
1750
  let fsMode = 'ws';
@@ -1959,12 +1870,12 @@ const awk = (args) => {
1959
1870
  const out = [];
1960
1871
  for (const st of stmts) {
1961
1872
  if (st.k === 'print') {
1962
- if (st.args.length === 0) {
1963
- out.push('$fx_line');
1964
- }
1965
- else {
1966
- out.push('(' + st.args.map((a) => '(fx-str ' + gen(a).ps + ')').join(' + (fx-str $fxv_OFS) + ') + ')');
1967
- }
1873
+ const text = st.args.length === 0
1874
+ ? '$fx_line'
1875
+ : '(' + st.args.map((a) => '(fx-str ' + gen(a).ps + ')').join(' + (fx-str $fxv_OFS) + ') + ')';
1876
+ out.push(exactOutput
1877
+ ? 'fx-awk-write (' + text + ' + [string][char]10)'
1878
+ : text);
1968
1879
  }
1969
1880
  else if (st.k === 'printf') {
1970
1881
  const f = awkFmtToPs(st.fmt);
@@ -1983,8 +1894,8 @@ const awk = (args) => {
1983
1894
  }
1984
1895
  return '(fx-str ' + raw + ')';
1985
1896
  });
1986
- const argList = argExprs.length ? ' ' + argExprs.join(', ') : '';
1987
- out.push('(' + f.ps + ' -f' + argList + ')');
1897
+ const argList = argExprs.length ? ' ' + argExprs.join(', ') : ' @()';
1898
+ out.push('fx-awk-write (' + f.ps + ' -f' + argList + ')');
1988
1899
  }
1989
1900
  else if (st.k === 'fieldassign') {
1990
1901
  out.push('$fx_fieldValue = (fx-str ' + gen(st.e).ps + ')');
@@ -2014,6 +1925,13 @@ const awk = (args) => {
2014
1925
  return out;
2015
1926
  };
2016
1927
  const lines = [PS_READTEXT_FN, PS_SPLITLINES_FN];
1928
+ if (exactOutput) {
1929
+ lines.push(PS_WRITE_FN, fxTermLine(ctx.position), '$fx_awk_buffered = $script:fx_csub -or -not $fx_term', 'if ($fx_awk_buffered) { $fx_awk_out = New-Object System.Text.StringBuilder }', 'function fx-awk-write($s) {', ' if ($fx_awk_buffered) { [void]$fx_awk_out.Append([string]$s) }',
1930
+ // Console writes are immediate; emitted line objects may be collected
1931
+ // later by the host. Use one write path for every direct fragment so
1932
+ // printf tails cannot overtake newline-terminated printf/print output.
1933
+ ' else { [Console]::Out.Write([string]$s) }', '}');
1934
+ }
2017
1935
  if (fileWords.length > 0)
2018
1936
  lines.push(PS_GLOB_FN);
2019
1937
  lines.push('function fx-num($v) {', ' if ($v -is [double]) { return $v }', ' if ($v -is [int] -or $v -is [long]) { return [double]$v }', ' if ($null -eq $v) { return [double]0 }', ' $s = [string]$v', " if ($s -match '^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$') { return [double]$s }", ' return [double]0', '}', 'function fx-fnum($v) {', ' if ($v -eq [math]::Floor($v) -and [math]::Abs($v) -lt 1e15) { return ([string][long]$v) }', " return ('{0:G6}' -f $v)", '}', 'function fx-str($v) {', ' if ($v -is [double]) { return (fx-fnum $v) }', " if ($null -eq $v) { return '' }", ' return [string]$v', '}', 'function fx-true($v) {', ' if ($v -is [double] -or $v -is [int]) { return ($v -ne 0) }', ' if ($null -eq $v) { return $false }', ' $s = [string]$v', " if ($s -eq '' -or $s -eq '0') { return $false }", ' return $true', '}', 'function fx-cmp($a, $b, $op) {', ' $ad = $null', ' $bd = $null', ' if ($a -is [double] -or $a -is [int]) { $ad = [double]$a }', " elseif ($a -match '^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$') { $ad = [double]$a }", ' if ($b -is [double] -or $b -is [int]) { $bd = [double]$b }', " elseif ($b -match '^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$') { $bd = [double]$b }", ' $r = 0', ' if ($null -ne $ad -and $null -ne $bd) {', ' if ($ad -lt $bd) { $r = -1 } elseif ($ad -gt $bd) { $r = 1 }', ' } else {', ' $r = [string]::CompareOrdinal((fx-str $a), (fx-str $b))', ' }', " if ($op -eq 'lt') { return ($r -lt 0) }", " if ($op -eq 'le') { return ($r -le 0) }", " if ($op -eq 'gt') { return ($r -gt 0) }", " if ($op -eq 'ge') { return ($r -ge 0) }", " if ($op -eq 'eq') { return ($r -eq 0) }", ' return ($r -ne 0)', '}', 'function fx-fld($n) {', ' if ($n -ge 1 -and $n -le $fx_flds.Count) { return [string]$fx_flds[$n - 1] }', " return ''", '}', 'function fx-substr($s, $a, $b) {', ' $t = [string]$s', ' $st = [int]$a - 1', ' if ($st -lt 0) { $b = $b + $st; $st = 0 }', " if ($b -lt 1 -or $st -ge $t.Length) { return '' }", ' $len = [math]::Min([int]$b, $t.Length - $st)', ' return $t.Substring($st, $len)', '}', 'function fx-firstchar($v) {', ' $t = [string]$v', ' if ($t.Length -ge 1) { return ([string]$t[0]) }', " return ''", '}');
@@ -2079,6 +1997,8 @@ const awk = (args) => {
2079
1997
  lines.push('}');
2080
1998
  if (prog.end.length > 0)
2081
1999
  lines.push(...genStmts(prog.end, false));
2000
+ if (exactOutput)
2001
+ lines.push('if ($fx_awk_buffered) { fx-write ($fx_awk_out.ToString()) $fx_term }');
2082
2002
  lines.push('if ($fx_err) { $script:fx_exit = 2 }');
2083
2003
  return lines.join('\n');
2084
2004
  };
@@ -2111,7 +2031,7 @@ function parseSortKeySpec(spec, g) {
2111
2031
  };
2112
2032
  }
2113
2033
  const sort = (args) => {
2114
- const { flags, longs, values, operandWords } = parseWords(args, ['t', 'k'], []);
2034
+ const { flags, longs, values, valueEntries, operandWords } = parseWords(args, ['t', 'k'], []);
2115
2035
  const globalR = flags.has('r') || longs.has('--reverse');
2116
2036
  const globalN = flags.has('n') || longs.has('--numeric-sort');
2117
2037
  const uniqMode = flags.has('u') || longs.has('--unique');
@@ -2129,8 +2049,10 @@ const sort = (args) => {
2129
2049
  sepChar = tv.charCodeAt(0);
2130
2050
  }
2131
2051
  const specs = [];
2132
- for (const k of collectShortValues(args, 'k')) {
2133
- specs.push(parseSortKeySpec(k, { n: globalN, b: globalB, f: globalF }));
2052
+ for (const option of valueEntries) {
2053
+ if (option.name === '-k') {
2054
+ specs.push(parseSortKeySpec(option.value, { n: globalN, b: globalB, f: globalF }));
2055
+ }
2134
2056
  }
2135
2057
  const lines = [PS_READTEXT_FN, PS_SPLITLINES_FN, PS_GLOB_FN];
2136
2058
  lines.push(...psCollectSources(psArray(operandWords), (v) => "[Console]::Error.WriteLine('sort: cannot read: ' + " + v + " + ': No such file or directory')", false));
@@ -2145,11 +2067,23 @@ const sort = (args) => {
2145
2067
  const fastPath = specs.length === 0 && !globalN && !globalB;
2146
2068
  if (fastPath) {
2147
2069
  const comparer = globalF ? 'OrdinalIgnoreCase' : 'Ordinal';
2148
- lines.push('$fx_arr = [string[]]$fx_lines');
2070
+ if (globalF && uniqMode) {
2071
+ // Native Array.Sort is unstable. Select the first input representative
2072
+ // before sorting, as GNU -u disables the case-sensitive last resort.
2073
+ lines.push('$fx_seen = New-Object System.Collections.Generic.HashSet[string] ([System.StringComparer]::OrdinalIgnoreCase)', '$fx_res = New-Object System.Collections.Generic.List[string]', 'foreach ($fx_l in $fx_lines) { if ($fx_seen.Add([string]$fx_l)) { $fx_res.Add([string]$fx_l) } }', '$fx_arr = $fx_res.ToArray()');
2074
+ }
2075
+ else {
2076
+ lines.push('$fx_arr = [string[]]$fx_lines');
2077
+ }
2149
2078
  lines.push('[array]::Sort($fx_arr, [System.StringComparer]::' + comparer + ')');
2079
+ if (globalF && !uniqMode) {
2080
+ // Retain native sorting, then order each equal-fold run by the original
2081
+ // line. GNU's last-resort comparison ignores -f but still honors -r.
2082
+ lines.push('$fx_start = 0', 'while ($fx_start -lt $fx_arr.Count) {', ' $fx_end = $fx_start + 1', ' while ($fx_end -lt $fx_arr.Count -and [System.StringComparer]::OrdinalIgnoreCase.Equals($fx_arr[$fx_start], $fx_arr[$fx_end])) { $fx_end++ }', ' if (($fx_end - $fx_start) -gt 1) { [array]::Sort($fx_arr, $fx_start, ($fx_end - $fx_start), [System.StringComparer]::Ordinal) }', ' $fx_start = $fx_end', '}');
2083
+ }
2150
2084
  if (globalR)
2151
2085
  lines.push('[array]::Reverse($fx_arr)');
2152
- if (uniqMode) {
2086
+ if (uniqMode && !globalF) {
2153
2087
  lines.push('$fx_res = New-Object System.Collections.Generic.List[string]');
2154
2088
  lines.push('if ($fx_arr.Count -gt 0) { $fx_res.Add($fx_arr[0]) }');
2155
2089
  lines.push('for ($fx_i = 1; $fx_i -lt $fx_arr.Count; $fx_i++) {');