fauxnix-cli 2.1.1 → 2.2.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,4 +1,4 @@
1
- globalThis.__FAUXNIX_VERSION__="2.1.1";globalThis.__FAUXNIX_ENGINES_NODE__=">=22.20.0";
1
+ globalThis.__FAUXNIX_VERSION__="2.2.0";globalThis.__FAUXNIX_ENGINES_NODE__=">=22.20.0";
2
2
  "use strict";
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -5384,7 +5384,7 @@ function varExpr(name, index, param, length = false, extra) {
5384
5384
  }
5385
5385
  switch (name) {
5386
5386
  case "HOME":
5387
- return "$HOME";
5387
+ return "(fx-scalar0 'HOME')";
5388
5388
  case "PWD":
5389
5389
  return "fx-posix([string]$PWD.Path)";
5390
5390
  case "USER":
@@ -5547,6 +5547,41 @@ function operandExpr(w) {
5547
5547
  if (lit !== null) return pathExpr(normalizeLiteralPath(lit));
5548
5548
  return exprOfWord(w);
5549
5549
  }
5550
+ function wcEscapeLiteral(s) {
5551
+ return s.replace(/[*?[]/g, "`$&");
5552
+ }
5553
+ function globOperandExpr(w) {
5554
+ const lit = literalOfWord(w);
5555
+ if (lit !== null && !/[*?[]/.test(lit)) return pathExpr(normalizeLiteralPath(lit));
5556
+ const chunks = [];
5557
+ const mergeable = (s) => typeof s === "string" && s.startsWith("'") && s.endsWith("'") && s.length >= 2;
5558
+ const pushChunk = (s) => {
5559
+ const prev = chunks.length ? chunks[chunks.length - 1] : void 0;
5560
+ if (mergeable(prev) && mergeable(s)) {
5561
+ chunks[chunks.length - 1] = "'" + prev.slice(1, -1) + s.slice(1, -1) + "'";
5562
+ return;
5563
+ }
5564
+ chunks.push(s);
5565
+ };
5566
+ const walk = (parts, quoted) => {
5567
+ for (const p of parts) {
5568
+ if (p.kind === "DoubleQuoted") {
5569
+ walk(p.parts, true);
5570
+ continue;
5571
+ }
5572
+ if (p.kind === "Text" || p.kind === "SingleQuoted") {
5573
+ const literal = quoted || p.kind === "SingleQuoted" || p.kind === "Text" && p.escaped === true;
5574
+ pushChunk(psStr(literal ? wcEscapeLiteral(p.text) : p.text));
5575
+ continue;
5576
+ }
5577
+ const expr = exprOfWord([p]);
5578
+ chunks.push(quoted ? "[WildcardPattern]::Escape([string](" + expr + "))" : "([string](" + expr + "))");
5579
+ }
5580
+ };
5581
+ walk(w, false);
5582
+ if (chunks.length === 1) return chunks[0];
5583
+ return "(" + chunks.join(" + ") + ")";
5584
+ }
5550
5585
  function wordPartsForSplat(w) {
5551
5586
  const out = [];
5552
5587
  const walk = (parts, quoted) => {
@@ -6412,7 +6447,9 @@ function wrapScript(body, opts = {}) {
6412
6447
  " if ($fx_eq -lt 1) { continue }",
6413
6448
  " if ($fx_pair.Substring(0, $fx_eq) -ceq $n) { return (fx-svdec $fx_pair.Substring($fx_eq + 1)) }",
6414
6449
  " }",
6415
- " if ($n -ceq 'HOME') { return [string]$HOME }",
6450
+ // Inherited HOME (Git Bash hosts) first; bare-Windows fallback is the
6451
+ // profile, like a bash login shell seeding HOME from passwd (#255).
6452
+ " if ($n -ceq 'HOME') { return $(if ($env:HOME) { [string]$env:HOME } else { [string]$HOME }) }",
6416
6453
  " if ($n -ceq 'PWD') { return fx-posix([string]$PWD.Path) }",
6417
6454
  " if ($n -ceq 'USER' -or $n -ceq 'LOGNAME') { return [string]$env:USERNAME }",
6418
6455
  " if ($n -ceq 'PATH') { return [string]$env:PATH }",
@@ -6938,6 +6975,14 @@ function fx-capture-bytes($stream) {
6938
6975
  if ($stream -is [System.IO.MemoryStream]) { return $stream.ToArray() }
6939
6976
  return (New-Object byte[] 0)
6940
6977
  }
6978
+ # Captured at startup, from the script's own location (never from the
6979
+ # user-mutable environment).
6980
+ $fx_sd = $null
6981
+ if ($PSCommandPath) {
6982
+ $fx_sd = [IO.Path]::GetDirectoryName($PSCommandPath)
6983
+ if ([IO.Path]::GetFileName($fx_sd) -cnotmatch '^fauxnix-[0-9]+-[0-9a-f]{24}$') { $fx_sd = $null }
6984
+ }
6985
+ Set-Variable -Name fx_hostStateDir -Value $fx_sd -Option Constant
6941
6986
  while ($true) {
6942
6987
  $fx_line = $fx_reader.ReadLine()
6943
6988
  if ($null -eq $fx_line) { break }
@@ -7050,6 +7095,9 @@ while ($true) {
7050
7095
  $fx_proto.WriteLine($fx_json)
7051
7096
  }
7052
7097
  }
7098
+ # stdin EOF: the owner is gone or disposed us. Remove our private state
7099
+ # directory (#256) - only if it is a genuine per-session directory.
7100
+ if ($fx_hostStateDir) { Remove-Item -LiteralPath $fx_hostStateDir -Recurse -Force -ErrorAction SilentlyContinue }
7053
7101
  `.trim();
7054
7102
 
7055
7103
  // src/commands/text-output.ts
@@ -7154,9 +7202,12 @@ var PS_GLOB_FN = [
7154
7202
  "function fx-glob($p) {",
7155
7203
  " if ($p -notlike '*[*?]*') { return @($p) }",
7156
7204
  " $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)",
7157
- " if ($m.Count -eq 0) { return @($p) }",
7205
+ " if ($m.Count -eq 0) { return @(fx-wclit $p) }",
7158
7206
  " return @($m | ForEach-Object { $_.FullName })",
7159
- "}"
7207
+ "}",
7208
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
7209
+ // matched nothing keep their shell spelling as the literal operand.
7210
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }"
7160
7211
  ].join("\n");
7161
7212
  var PS_READTEXT_FN = [
7162
7213
  "function fx-read($p) {",
@@ -7198,7 +7249,7 @@ var ls = (args) => {
7198
7249
  const sortByTime = flags.has("t");
7199
7250
  const sortBySize = flags.has("S");
7200
7251
  const reverse = flags.has("r");
7201
- const targets = operandWords.length ? argListExpr(operandWords) : "@('.')";
7252
+ const targets = operandWords.length ? argListExpr(operandWords, globOperandExpr) : "@('.')";
7202
7253
  return [
7203
7254
  PS_GLOB_FN,
7204
7255
  PS_FTIME_FN,
@@ -7276,7 +7327,7 @@ var cp = (args) => {
7276
7327
  const noclobber = flags.has("n") || longs.has("--no-clobber");
7277
7328
  return [
7278
7329
  PS_GLOB_FN,
7279
- "$fx_all = " + argListExpr(operandWords),
7330
+ "$fx_all = " + argListExpr(operandWords, globOperandExpr),
7280
7331
  "if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
7281
7332
  "$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })",
7282
7333
  "if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('cp: missing file operand'); $script:fx_exit = 1 }",
@@ -7305,7 +7356,7 @@ var mv = (args) => {
7305
7356
  return [
7306
7357
  PS_GLOB_FN,
7307
7358
  PS_MOVE_REPLACE_FN,
7308
- "$fx_all = " + argListExpr(operandWords),
7359
+ "$fx_all = " + argListExpr(operandWords, globOperandExpr),
7309
7360
  "if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
7310
7361
  "$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })",
7311
7362
  "if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('mv: missing file operand'); $script:fx_exit = 1 }",
@@ -7350,27 +7401,104 @@ var mv = (args) => {
7350
7401
  "}"
7351
7402
  ].join("\n");
7352
7403
  };
7404
+ var PS_IOERR_FN = [
7405
+ "function fx-ioerr1($x) {",
7406
+ " if ($x -is [UnauthorizedAccessException] -or $x -is [Security.SecurityException]) { return 'Permission denied' }",
7407
+ " if ($x -is [IO.PathTooLongException]) { return 'File name too long' }",
7408
+ " if ($x -is [IO.DirectoryNotFoundException] -or $x -is [IO.FileNotFoundException] -or $x -is [IO.DriveNotFoundException] -or $x -is [System.Management.Automation.ItemNotFoundException] -or $x -is [System.Management.Automation.DriveNotFoundException]) { return 'No such file or directory' }",
7409
+ " if ((($x.HResult -shr 16) -band 0xFFFF) -ne 0x8007) { return $null }",
7410
+ " switch ($x.HResult -band 0xFFFF) {",
7411
+ " { $_ -in 2, 3 } { return 'No such file or directory' }",
7412
+ " 5 { return 'Permission denied' }",
7413
+ " 19 { return 'Read-only file system' }",
7414
+ " { $_ -in 32, 33 } { return 'Device or resource busy' }",
7415
+ " { $_ -in 80, 183 } { return 'File exists' }",
7416
+ " 112 { return 'No space left on device' }",
7417
+ " 123 { return 'Invalid argument' }",
7418
+ " 145 { return 'Directory not empty' }",
7419
+ " 206 { return 'File name too long' }",
7420
+ " 267 { return 'Not a directory' }",
7421
+ " }",
7422
+ " return $null",
7423
+ "}",
7424
+ "function fx-ioerr($e, [string]$fallback) {",
7425
+ " $x = $e",
7426
+ " if ($x -is [System.Management.Automation.ErrorRecord]) { $x = $x.Exception }",
7427
+ " $fx_depth = 0",
7428
+ " while ($null -ne $x -and $fx_depth -lt 16) {",
7429
+ " $fx_r = fx-ioerr1 $x",
7430
+ " if ($null -ne $fx_r) { return $fx_r }",
7431
+ " $x = $x.InnerException",
7432
+ " $fx_depth++",
7433
+ " }",
7434
+ " return $fallback",
7435
+ "}"
7436
+ ].join("\n");
7437
+ function rmPreservesRoot(args) {
7438
+ let preserve = true;
7439
+ for (const w of args) {
7440
+ const t = wordToString(w);
7441
+ if (t === "--") break;
7442
+ if (t === "--preserve-root") preserve = true;
7443
+ else if (t === "--no-preserve-root") preserve = false;
7444
+ }
7445
+ return preserve;
7446
+ }
7353
7447
  var rm = (args) => {
7354
7448
  const { flags, longs, operandWords } = parseWords(args);
7355
7449
  const recurse = flags.has("r") || flags.has("R") || longs.has("--recursive");
7356
7450
  const force = flags.has("f") || longs.has("--force");
7357
7451
  const verbose = flags.has("v") || longs.has("--verbose");
7452
+ const guardRoot = recurse && rmPreservesRoot(args);
7453
+ const b = (v) => v ? "$true" : "$false";
7454
+ const danger = (operand) => "if (" + operand + ` -eq '/') { [Console]::Error.WriteLine("rm: it is dangerous to operate recursively on '/'") } else { [Console]::Error.WriteLine("rm: it is dangerous to operate recursively on '" + ` + operand + ` + "' (same as '/')") }; [Console]::Error.WriteLine('rm: use --no-preserve-root to override this failsafe'); $script:fx_exit = 1; continue`;
7358
7455
  return [
7359
7456
  PS_GLOB_FN,
7360
- "$fx_files = " + psArray(operandWords),
7361
- "if ($fx_files.Count -eq 0 -and " + (force ? "$false" : "$true") + ") { [Console]::Error.WriteLine('rm: missing operand'); $script:fx_exit = 1 }",
7457
+ PS_IOERR_FN,
7458
+ "$fx_files = " + psArray(operandWords, globOperandExpr),
7459
+ "if ($fx_files.Count -eq 0 -and " + b(!force) + ") { [Console]::Error.WriteLine('rm: missing operand'); $script:fx_exit = 1 }",
7460
+ "$fx_guardroot = " + b(guardRoot),
7362
7461
  "foreach ($fx_f in $fx_files) {",
7462
+ " $fx_s = [string]$fx_f",
7463
+ // GNU always refuses a last component of "." or ".."; on Windows a drive
7464
+ // prefix ("C:..", drive-relative) is also a component boundary.
7465
+ " $fx_leaf = ($fx_s -replace '^[A-Za-z]:', '').TrimEnd([char[]]@('/', '\\'))",
7466
+ " $fx_leaf = $fx_leaf.Substring($fx_leaf.LastIndexOfAny([char[]]@('/', '\\')) + 1)",
7467
+ ` if ($fx_leaf -eq '.' -or $fx_leaf -eq '..') { [Console]::Error.WriteLine("rm: refusing to remove '.' or '..' directory: skipping '" + $fx_s + "'"); $script:fx_exit = 1; continue }`,
7468
+ // "/", "//", "///" all name the root; refuse before Test-Path, which may
7469
+ // treat "//"-prefixed text as a (malformed) UNC path and report it absent.
7470
+ " if ($fx_guardroot -and $fx_s -match '^[/\\\\]+$') { " + danger("$fx_s") + " }",
7363
7471
  " foreach ($fx_g in (fx-glob $fx_f)) {",
7364
7472
  " if (-not (Test-Path -LiteralPath $fx_g)) {",
7365
- " if (" + (force ? "$false" : "$true") + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': No such file or directory"); $script:fx_exit = 1 }`,
7473
+ " if (" + b(!force) + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': No such file or directory"); $script:fx_exit = 1 }`,
7366
7474
  " continue",
7367
7475
  " }",
7368
7476
  " $fx_isdir = (Test-Path -LiteralPath $fx_g -PathType Container)",
7369
- " if ($fx_isdir -and " + (recurse ? "$false" : "$true") + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': Is a directory"); $script:fx_exit = 1; continue }`,
7477
+ " if ($fx_isdir -and " + b(!recurse) + `) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': Is a directory"); $script:fx_exit = 1; continue }`,
7478
+ " if ($fx_isdir -and $fx_guardroot) {",
7479
+ // Fail closed: if the path cannot be canonicalized, do not delete it.
7480
+ " $fx_rp = $null",
7481
+ " try { $fx_rp = [IO.Path]::GetFullPath((Resolve-Path -LiteralPath $fx_g -ErrorAction Stop).ProviderPath) } catch {}",
7482
+ ` if ($null -eq $fx_rp) { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': cannot resolve path for the --preserve-root check"); $script:fx_exit = 1; continue }`,
7483
+ " $fx_root = [IO.Path]::GetPathRoot($fx_rp)",
7484
+ " if ([string]::IsNullOrEmpty($fx_root) -or $fx_rp.TrimEnd([char[]]@('/', '\\')) -ieq ([string]$fx_root).TrimEnd([char[]]@('/', '\\'))) { " + danger("$fx_g") + " }",
7485
+ " }",
7486
+ // A directory symlink/junction is removed as a link; never traverse into
7487
+ // its target (Windows PowerShell 5.1 Remove-Item -Recurse can follow it).
7488
+ " if ($fx_isdir -and " + b(recurse) + ") {",
7489
+ " $fx_item = Get-Item -LiteralPath $fx_g -Force -ErrorAction SilentlyContinue",
7490
+ " if ($null -ne $fx_item -and ($fx_item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {",
7491
+ " try {",
7492
+ " [IO.Directory]::Delete($fx_item.FullName, $false)",
7493
+ " if (" + b(verbose) + `) { [Console]::Error.WriteLine("removed '" + $fx_g + "'") }`,
7494
+ ` } catch { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': " + (fx-ioerr $_ 'Permission denied')); $script:fx_exit = 1 }`,
7495
+ " continue",
7496
+ " }",
7497
+ " }",
7370
7498
  " try {",
7371
- " Remove-Item -LiteralPath $fx_g -Recurse:" + (recurse ? "$true" : "$false") + " -Force -ErrorAction Stop",
7372
- " if (" + (verbose ? "$true" : "$false") + `) { [Console]::Error.WriteLine("removed '" + $fx_g + "'") }`,
7373
- ` } catch { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': Permission denied"); $script:fx_exit = 1 }`,
7499
+ " Remove-Item -LiteralPath $fx_g -Recurse:" + b(recurse) + " -Force -ErrorAction Stop",
7500
+ " if (" + b(verbose) + `) { [Console]::Error.WriteLine("removed '" + $fx_g + "'") }`,
7501
+ ` } catch { [Console]::Error.WriteLine("rm: cannot remove '" + $fx_g + "': " + (fx-ioerr $_ 'Permission denied')); $script:fx_exit = 1 }`,
7374
7502
  " }",
7375
7503
  "}"
7376
7504
  ].join("\n");
@@ -7380,6 +7508,7 @@ var mkdir = (args) => {
7380
7508
  const parents = flags.has("p") || longs.has("--parents");
7381
7509
  const verbose = flags.has("v") || longs.has("--verbose");
7382
7510
  return [
7511
+ PS_IOERR_FN,
7383
7512
  "$fx_dirs = " + psArray(operandWords),
7384
7513
  "if ($fx_dirs.Count -eq 0) { [Console]::Error.WriteLine('mkdir: missing operand'); $script:fx_exit = 1 }",
7385
7514
  "foreach ($fx_d in $fx_dirs) {",
@@ -7388,9 +7517,16 @@ var mkdir = (args) => {
7388
7517
  " continue",
7389
7518
  " }",
7390
7519
  " try {",
7391
- " New-Item -ItemType Directory -Path $fx_d -Force:" + (parents ? "$true" : "$false") + " -ErrorAction Stop | Out-Null",
7520
+ // Literal creation (#255): [IO.Directory] never interprets wildcard
7521
+ // characters or PS provider prefixes (Env:, Function:) the way
7522
+ // New-Item -Path does.
7523
+ ...parents ? [" [void][IO.Directory]::CreateDirectory($fx_d)"] : [
7524
+ " $fx_par = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($fx_d))",
7525
+ " if ($null -ne $fx_par -and -not (Test-Path -LiteralPath $fx_par -PathType Container)) { throw [IO.DirectoryNotFoundException]::new() }",
7526
+ " [void][IO.Directory]::CreateDirectory($fx_d)"
7527
+ ],
7392
7528
  " if (" + (verbose ? "$true" : "$false") + `) { [Console]::Error.WriteLine("mkdir: created directory '" + $fx_d + "'") }`,
7393
- ` } catch { [Console]::Error.WriteLine("mkdir: cannot create directory '" + $fx_d + "': " + $_.Exception.Message); $script:fx_exit = 1 }`,
7529
+ ` } catch { [Console]::Error.WriteLine("mkdir: cannot create directory '" + $fx_d + "': " + (fx-ioerr $_ 'No such file or directory')); $script:fx_exit = 1 }`,
7394
7530
  "}"
7395
7531
  ].join("\n");
7396
7532
  };
@@ -7410,15 +7546,18 @@ var touch = (args) => {
7410
7546
  const { flags, longs, operandWords } = parseWords(args);
7411
7547
  const noCreate = flags.has("c") || longs.has("--no-create");
7412
7548
  return [
7549
+ PS_IOERR_FN,
7413
7550
  "$fx_files = " + psArray(operandWords),
7414
7551
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('touch: missing file operand'); $script:fx_exit = 1 }",
7415
7552
  "foreach ($fx_f in $fx_files) {",
7416
7553
  " if (Test-Path -LiteralPath $fx_f) {",
7417
- ` try { (Get-Item -LiteralPath $fx_f).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': Permission denied"); $script:fx_exit = 1 }`,
7554
+ ` try { (Get-Item -LiteralPath $fx_f -Force -ErrorAction Stop).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': " + (fx-ioerr $_ 'Permission denied')); $script:fx_exit = 1 }`,
7418
7555
  " } else {",
7419
7556
  " if (" + (noCreate ? "$true" : "$false") + ") { continue }",
7420
- " try { New-Item -ItemType File -Path $fx_f -ErrorAction Stop | Out-Null }",
7421
- ` catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': No such file or directory"); $script:fx_exit = 1 }`,
7557
+ // Literal creation (#255): .NET File.Create never reads wildcard
7558
+ // characters or PS provider prefixes into the name.
7559
+ " try { $fx_nfs = [IO.File]::Create($fx_f); $fx_nfs.Close() }",
7560
+ ` catch { [Console]::Error.WriteLine("touch: cannot touch '" + $fx_f + "': " + (fx-ioerr $_ 'No such file or directory')); $script:fx_exit = 1 }`,
7422
7561
  " }",
7423
7562
  "}"
7424
7563
  ].join("\n");
@@ -7568,7 +7707,7 @@ var stat = (args, ctx) => {
7568
7707
  PS_FTIME_FN,
7569
7708
  PS_GLOB_FN,
7570
7709
  ...printfMode ? [PS_WRITE_FN, fxTermLine(ctx.position), "$fx_stat_out = New-Object System.Text.StringBuilder"] : [],
7571
- "$fx_files = " + psArray(operandWords),
7710
+ "$fx_files = " + psArray(operandWords, globOperandExpr),
7572
7711
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('stat: missing operand'); $script:fx_exit = 1 }",
7573
7712
  "foreach ($fx_f in $fx_files) {",
7574
7713
  " foreach ($fx_g in (fx-glob $fx_f)) {",
@@ -7600,7 +7739,7 @@ var file = (args) => {
7600
7739
  return [
7601
7740
  PS_GLOB_FN,
7602
7741
  PS_READTEXT_FN,
7603
- "$fx_files = " + psArray(operandWords),
7742
+ "$fx_files = " + psArray(operandWords, globOperandExpr),
7604
7743
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('file: missing operand'); $script:fx_exit = 1 }",
7605
7744
  "foreach ($fx_f in $fx_files) {",
7606
7745
  " foreach ($fx_g in (fx-glob $fx_f)) {",
@@ -8080,6 +8219,8 @@ var specs2 = [
8080
8219
  opt("R", "--recursive"),
8081
8220
  opt("f", "--force"),
8082
8221
  opt("v", "--verbose"),
8222
+ opt(void 0, "--preserve-root"),
8223
+ opt(void 0, "--no-preserve-root"),
8083
8224
  opt("i", "--interactive", "unsupported", INTERACTIVE)
8084
8225
  ],
8085
8226
  rm
@@ -8182,9 +8323,12 @@ var PS_GLOB_FN2 = [
8182
8323
  "function fx-glob($p) {",
8183
8324
  " if ($p -notlike '*[*?]*') { return @($p) }",
8184
8325
  " $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)",
8185
- " if ($m.Count -eq 0) { return @($p) }",
8326
+ " if ($m.Count -eq 0) { return @(fx-wclit $p) }",
8186
8327
  " return @($m | ForEach-Object { $_.FullName })",
8187
- "}"
8328
+ "}",
8329
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
8330
+ // matched nothing keep their shell spelling as the literal operand.
8331
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }"
8188
8332
  ].join("\n");
8189
8333
  var PS_READTEXT_FN2 = [
8190
8334
  "function fx-read($p) {",
@@ -8552,7 +8696,7 @@ var grep = (args) => {
8552
8696
  lines.push(" }");
8553
8697
  lines.push("}");
8554
8698
  }
8555
- lines.push("foreach ($fx_o in " + psArray2(fileWords) + ") {");
8699
+ lines.push("foreach ($fx_o in " + psArray2(fileWords, globOperandExpr) + ") {");
8556
8700
  lines.push(" foreach ($fx_g in (fx-glob $fx_o)) {");
8557
8701
  lines.push(
8558
8702
  " if (-not (Test-Path -LiteralPath $fx_g)) { [Console]::Error.WriteLine('grep: ' + $fx_g + ': No such file or directory'); $fx_err = $true; continue }"
@@ -8724,8 +8868,12 @@ function sedReplToNet(repl, delim) {
8724
8868
  else if (n === "n") out += "\n";
8725
8869
  else if (n === "t") out += " ";
8726
8870
  else if (n === "&") out += "&";
8727
- else if (/[1-9]/.test(n)) out += "$" + n;
8728
- else out += "\\" + n;
8871
+ else if (n === "0") out += "$&";
8872
+ else if (/[1-9]/.test(n)) {
8873
+ const next = repl[i + 2];
8874
+ if (next !== void 0 && /[0-9]/.test(next)) out += "${" + n + "}";
8875
+ else out += "$" + n;
8876
+ } else out += "\\" + n;
8729
8877
  i += 2;
8730
8878
  continue;
8731
8879
  }
@@ -9213,7 +9361,7 @@ var sed = (args, ctx) => {
9213
9361
  if (operandWords.length > 0) {
9214
9362
  lines.push(
9215
9363
  ...psCollectSources(
9216
- psArray2(operandWords),
9364
+ psArray2(operandWords, globOperandExpr),
9217
9365
  (v) => "[Console]::Error.WriteLine('sed: can''t read ' + " + v + " + ': No such file or directory')",
9218
9366
  true
9219
9367
  )
@@ -9689,6 +9837,46 @@ var AwkParser = class {
9689
9837
  throw new FauxnixParseError("fauxnix: awk unexpected character '" + c + "' in expression");
9690
9838
  }
9691
9839
  };
9840
+ var PS_AWK_IFMT_FN = [
9841
+ "function fx-awk-ifmt($v, $conv, $flags, $width, $prec) {",
9842
+ " $n = [long][math]::Truncate((fx-num $v))",
9843
+ " $prefix = ''",
9844
+ " $digits = ''",
9845
+ " if ($conv -ceq 'd') {",
9846
+ " if ($n -lt 0) {",
9847
+ " $prefix = '-'",
9848
+ " if ($n -eq [long]::MinValue) { $digits = '9223372036854775808' }",
9849
+ " else { $digits = [string]([math]::Abs([long]$n)) }",
9850
+ " } else {",
9851
+ " if ($flags.Contains('+')) { $prefix = '+' }",
9852
+ " elseif ($flags.Contains(' ')) { $prefix = ' ' }",
9853
+ " $digits = [string]$n",
9854
+ " }",
9855
+ " } elseif ($conv -ceq 'o') {",
9856
+ " $digits = [Convert]::ToString([long]$n, 8)",
9857
+ " } elseif ($conv -ceq 'X') {",
9858
+ " $digits = [Convert]::ToString([long]$n, 16).ToUpperInvariant()",
9859
+ " } else {",
9860
+ " $digits = [Convert]::ToString([long]$n, 16)",
9861
+ " }",
9862
+ " if ($null -ne $prec) {",
9863
+ " $p = [int]$prec",
9864
+ " if ($p -eq 0 -and $digits -eq '0') { $digits = '' }",
9865
+ " elseif ($digits.Length -lt $p) { $digits = $digits.PadLeft($p, [char]48) }",
9866
+ " }",
9867
+ " $body = $prefix + $digits",
9868
+ " if ($null -eq $width) { return $body }",
9869
+ " $w = [int]$width",
9870
+ " if ($body.Length -ge $w) { return $body }",
9871
+ " if ($flags.Contains('-')) { return $body.PadRight($w) }",
9872
+ " if ($flags.Contains('0') -and $null -eq $prec) {",
9873
+ " $digits = $digits.PadLeft($w - $prefix.Length, [char]48)",
9874
+ " return $prefix + $digits",
9875
+ " }",
9876
+ " return $body.PadLeft($w)",
9877
+ "}"
9878
+ ].join("\n");
9879
+ var AWK_INT_CONVS = /* @__PURE__ */ new Set(["d", "o", "x", "X"]);
9692
9880
  function awkFmtToPs(fmt) {
9693
9881
  const chunks = [];
9694
9882
  const kinds = [];
@@ -9704,23 +9892,25 @@ function awkFmtToPs(fmt) {
9704
9892
  while (i < fmt.length) {
9705
9893
  const c = fmt[i];
9706
9894
  if (c === "%") {
9707
- const m = fmt.slice(i).match(/^%([-+0 ]*)(\d+)?(?:\.(\d+))?([sdfc])/);
9895
+ const m = fmt.slice(i).match(/^%([-+0 ]*)(\d+)?(?:\.(\d+))?([sdfcioxX])/);
9708
9896
  if (m) {
9709
9897
  const flags = m[1];
9710
9898
  const width = m[2];
9711
9899
  const prec = m[3];
9712
- const conv = m[4];
9900
+ let conv = m[4];
9901
+ if (conv === "i") conv = "d";
9713
9902
  flushLit();
9714
9903
  const idx = kinds.length;
9715
9904
  let spec = "";
9905
+ let align = "";
9716
9906
  if (conv === "f") {
9717
9907
  spec = "F" + (prec === void 0 ? "6" : prec);
9718
- } else if (conv === "d" && prec !== void 0) {
9719
- spec = "D" + prec;
9720
9908
  }
9721
- const align = width === void 0 ? "" : "," + (flags.includes("-") ? "-" : "") + width;
9909
+ if (!AWK_INT_CONVS.has(conv) && width !== void 0) {
9910
+ align = "," + (flags.includes("-") ? "-" : "") + width;
9911
+ }
9722
9912
  chunks.push("'{" + idx + align + (spec === "" ? "" : ":" + spec) + "}'");
9723
- kinds.push({ conv, align, spec });
9913
+ kinds.push({ conv, align, spec, flags, width, prec });
9724
9914
  i += m[0].length;
9725
9915
  continue;
9726
9916
  }
@@ -9758,6 +9948,19 @@ function awkFmtToPs(fmt) {
9758
9948
  const ps2 = chunks.length === 0 ? "''" : "(" + chunks.join(" + ") + ")";
9759
9949
  return { ps: ps2, kinds };
9760
9950
  }
9951
+ function awkUsesIntPrintf(prog) {
9952
+ const stmts = [
9953
+ ...prog.begin,
9954
+ ...prog.items.flatMap((item) => item.act ?? []),
9955
+ ...prog.end
9956
+ ];
9957
+ for (const st of stmts) {
9958
+ if (st.k === "printf" && awkFmtToPs(st.fmt).kinds.some((k) => AWK_INT_CONVS.has(k.conv))) {
9959
+ return true;
9960
+ }
9961
+ }
9962
+ return false;
9963
+ }
9761
9964
  var awk = (args, ctx) => {
9762
9965
  const { values, operandWords } = parseWords(args, ["F", "v"]);
9763
9966
  const vvars = [];
@@ -9930,7 +10133,11 @@ var awk = (args, ctx) => {
9930
10133
  const argExprs = f.kinds.map((kind, idx) => {
9931
10134
  const arg = st.args[idx];
9932
10135
  const raw = gen(arg ?? { k: "num", v: 0 }).ps;
9933
- if (kind.conv === "d") return "([string][math]::Truncate((fx-num " + raw + ")))";
10136
+ if (AWK_INT_CONVS.has(kind.conv)) {
10137
+ const w = kind.width === void 0 ? "$null" : kind.width;
10138
+ const p = kind.prec === void 0 ? "$null" : kind.prec;
10139
+ return "(fx-awk-ifmt " + raw + " " + psStr(kind.conv) + " " + psStr(kind.flags) + " " + w + " " + p + ")";
10140
+ }
9934
10141
  if (kind.conv === "f") return "(fx-num " + raw + ")";
9935
10142
  if (kind.conv === "c") {
9936
10143
  if (arg !== void 0 && arg.k === "num") return "[string][char]" + Math.trunc(arg.v);
@@ -10045,6 +10252,7 @@ var awk = (args, ctx) => {
10045
10252
  " return ''",
10046
10253
  "}"
10047
10254
  );
10255
+ if (awkUsesIntPrintf(prog)) lines.push(PS_AWK_IFMT_FN);
10048
10256
  lines.push(...hoistedRegex);
10049
10257
  for (const v of prog.vars) lines.push("$fxv_" + v + " = $null");
10050
10258
  lines.push("$fxv_OFS = ' '", "$fx_line = ''", "$fx_flds = @()", "$fx_nf = 0");
@@ -10059,7 +10267,7 @@ var awk = (args, ctx) => {
10059
10267
  if (fileWords.length > 0) {
10060
10268
  lines.push(
10061
10269
  ...psCollectSources(
10062
- psArray2(fileWords),
10270
+ psArray2(fileWords, globOperandExpr),
10063
10271
  (v) => "[Console]::Error.WriteLine('awk: fatal: cannot open file ' + [string][char]96 + " + v + " + [string][char]39 + ' for reading (No such file or directory)')",
10064
10272
  true
10065
10273
  )
@@ -10164,7 +10372,7 @@ var sort = (args) => {
10164
10372
  const lines = [PS_READTEXT_FN2, PS_SPLITLINES_FN, PS_GLOB_FN2];
10165
10373
  lines.push(
10166
10374
  ...psCollectSources(
10167
- psArray2(operandWords),
10375
+ psArray2(operandWords, globOperandExpr),
10168
10376
  (v) => "[Console]::Error.WriteLine('sort: cannot read: ' + " + v + " + ': No such file or directory')",
10169
10377
  false
10170
10378
  )
@@ -10338,7 +10546,7 @@ var uniq = (args) => {
10338
10546
  lines.push(PS_GLOB_FN2);
10339
10547
  lines.push(
10340
10548
  ...psCollectSources(
10341
- "@(" + operandExpr(inFile) + ")",
10549
+ "@(" + globOperandExpr(inFile) + ")",
10342
10550
  (v) => "[Console]::Error.WriteLine('uniq: ' + " + v + " + ': No such file or directory')",
10343
10551
  false
10344
10552
  )
@@ -10440,7 +10648,7 @@ var cut = (args) => {
10440
10648
  const lines = [PS_READTEXT_FN2, PS_SPLITLINES_FN, PS_GLOB_FN2];
10441
10649
  lines.push(
10442
10650
  ...psCollectSources(
10443
- psArray2(operandWords),
10651
+ psArray2(operandWords, globOperandExpr),
10444
10652
  (v) => "[Console]::Error.WriteLine('cut: ' + " + v + " + ': No such file or directory')",
10445
10653
  false
10446
10654
  )
@@ -10725,9 +10933,12 @@ var PS_GLOB_FN3 = [
10725
10933
  "function fx-glob($p) {",
10726
10934
  " if ($p -notlike '*[*?]*') { return @($p) }",
10727
10935
  " $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)",
10728
- " if ($m.Count -eq 0) { return @($p) }",
10936
+ " if ($m.Count -eq 0) { return @(fx-wclit $p) }",
10729
10937
  " return @($m | ForEach-Object { $_.FullName })",
10730
- "}"
10938
+ "}",
10939
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
10940
+ // matched nothing keep their shell spelling as the literal operand.
10941
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }"
10731
10942
  ].join("\n");
10732
10943
  var PS_READTEXT_FN3 = [
10733
10944
  "function fx-read($p) {",
@@ -10800,7 +11011,7 @@ function psCollectFiles(operandWords, missErr, dirErr, stdinDefault = true) {
10800
11011
  continue;
10801
11012
  }
10802
11013
  const lit = w.every((p) => p.kind === "Text" || p.kind === "SingleQuoted") ? w.map((p) => p.text).join("") : null;
10803
- out.push("foreach ($fx_d in " + argListExpr([w], lit !== null ? operandExpr : exprOfWord) + ") {");
11014
+ out.push("foreach ($fx_d in " + argListExpr([w], globOperandExpr) + ") {");
10804
11015
  out.push("foreach ($fx_g in (fx-glob $fx_d)) {");
10805
11016
  if (dirErr) {
10806
11017
  const dis = lit !== null && /[*?]/.test(lit) ? "$fx_g" : "$fx_d";
@@ -10809,7 +11020,9 @@ function psCollectFiles(operandWords, missErr, dirErr, stdinDefault = true) {
10809
11020
  );
10810
11021
  }
10811
11022
  out.push(
10812
- " if (-not (Test-Path -LiteralPath $fx_g -PathType Leaf)) { " + psErrExpr(missErr("$fx_d")) + "; continue }"
11023
+ " if (-not (Test-Path -LiteralPath $fx_g -PathType Leaf)) { " + // $fx_g: unmatched literals come back unescaped by fx-wclit, keeping
11024
+ // the shell spelling in the message (matched globs resolve anyway).
11025
+ psErrExpr(missErr("$fx_g")) + "; continue }"
10813
11026
  );
10814
11027
  out.push(" $fx_srcs += $fx_g");
10815
11028
  out.push(
@@ -15380,13 +15593,12 @@ var handlers5 = {
15380
15593
 
15381
15594
  // src/runtime-support.ts
15382
15595
  var import_node_fs2 = require("node:fs");
15383
- var import_meta = {};
15384
15596
  var bundledRange = globalThis.__FAUXNIX_ENGINES_NODE__;
15385
15597
  var nodeEngineRange;
15386
15598
  if (typeof bundledRange === "string") {
15387
15599
  nodeEngineRange = bundledRange;
15388
15600
  } else {
15389
- const metadata = JSON.parse((0, import_node_fs2.readFileSync)(new URL("../package.json", import_meta.url), "utf8"));
15601
+ const metadata = JSON.parse((0, import_node_fs2.readFileSync)(new URL("../package.json", "file://fauxnix-sea/"), "utf8"));
15390
15602
  nodeEngineRange = metadata.engines?.node;
15391
15603
  }
15392
15604
  var minimum = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(nodeEngineRange);
@@ -15416,6 +15628,10 @@ const { pipeline } = require('node:stream/promises');
15416
15628
  if (leased) {
15417
15629
  process.stdin.on('end', stopDecoder);
15418
15630
  process.stdin.on('error', stopDecoder);
15631
+ // #240 hardening: 'close' fires when the stream is torn down without a
15632
+ // clean 'end' - exactly the intermittent CI-hang shape. Listening for
15633
+ // both costs nothing and stops the decoder either way.
15634
+ process.stdin.on('close', stopDecoder);
15419
15635
  process.stdin.resume();
15420
15636
  }
15421
15637
  const parent = Number(process.argv[3]);
@@ -15916,6 +16132,7 @@ var unzip = (args) => {
15916
16132
  const arc = operandExpr(rest[0]);
15917
16133
  const dirExpr = dir ? operandExpr(dir) : "'.'";
15918
16134
  return [
16135
+ "Add-Type -AssemblyName System.IO.Compression",
15919
16136
  "Add-Type -AssemblyName System.IO.Compression.FileSystem",
15920
16137
  "$fx_arc = " + arc,
15921
16138
  "if (-not (Test-Path -LiteralPath $fx_arc -PathType Leaf)) {",
@@ -15942,10 +16159,105 @@ var unzip = (args) => {
15942
16159
  " ((([string]$fx_tot).PadLeft(9)) + ' ' + $fx_cnt + ' file' + $fx_pl)",
15943
16160
  " } finally { $fx_z.Dispose() }"
15944
16161
  ].join("\n") : [
16162
+ // Extract entry by entry so every target is proven to stay inside
16163
+ // the destination (zip-slip, #257) regardless of which Archive
16164
+ // module / .NET version the host has. Nothing is written unless
16165
+ // every entry passes validation.
16166
+ // Known limitations: names without the UTF-8 flag are decoded by
16167
+ // .NET (OEM code page on Windows PowerShell 5.1, UTF-8 on pwsh 7);
16168
+ // targets beyond MAX_PATH fail per entry on 5.1 unless long paths
16169
+ // are enabled. Duplicate/case-colliding names: first wins without
16170
+ // -o (warning), last wins with -o.
15945
16171
  " $fx_dir = " + dirExpr,
16172
+ " $fx_z = $null",
15946
16173
  " try {",
15947
- " Expand-Archive -LiteralPath $fx_arc -DestinationPath $fx_dir -Force:" + (over ? "$true" : "$false") + " -ErrorAction Stop",
15948
- " } catch { [Console]::Error.WriteLine('unzip: fauxnix: ' + $_.Exception.Message + ' (use -o to overwrite)'); $script:fx_exit = 1 }"
16174
+ " $fx_root = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath([string]$fx_dir))",
16175
+ // root with exactly one trailing separator ("C:\" stays "C:\")
16176
+ " $fx_rootT = $fx_root.TrimEnd([char[]]@('\\', '/')) + [IO.Path]::DirectorySeparatorChar",
16177
+ " $fx_z = [IO.Compression.ZipFile]::OpenRead((Resolve-Path -LiteralPath $fx_arc).ProviderPath)",
16178
+ " $fx_bad = @()",
16179
+ " $fx_plan = @()",
16180
+ " foreach ($fx_e in $fx_z.Entries) {",
16181
+ " $fx_n = [string]$fx_e.FullName",
16182
+ " $fx_t = $null",
16183
+ " $fx_why = 'outside destination'",
16184
+ " $fx_dev = @($fx_n -split '[\\\\/]' | Where-Object { (($_ -split '\\.')[0]).TrimEnd(' ') -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$' })",
16185
+ // rooted, drive-qualified (or NTFS stream) names are never relative
16186
+ // Directory entries end in a separator; some writers instead set the
16187
+ // MS-DOS directory attribute (0x10) on a zero-length entry.
16188
+ " $fx_isDir = $fx_n.EndsWith('/') -or $fx_n.EndsWith('\\') -or ($fx_e.Length -eq 0 -and ($fx_e.ExternalAttributes -band 0x10) -ne 0)",
16189
+ " if ($fx_n -match '^[\\\\/]') { $fx_why = 'absolute path' }",
16190
+ " elseif ($fx_n.IndexOf(':') -ge 0) { $fx_why = 'drive or stream name' }",
16191
+ " elseif ($fx_dev.Count -gt 0) { $fx_why = 'reserved device name' }",
16192
+ " else {",
16193
+ " try { $fx_t = [IO.Path]::GetFullPath([IO.Path]::Combine($fx_rootT, $fx_n)) } catch { $fx_why = 'invalid name' }",
16194
+ // "./" or "a/.." resolve to the root itself: inside, not an escape
16195
+ " if ($null -ne $fx_t) {",
16196
+ " $fx_tT = $fx_t.TrimEnd([char[]]@('\\', '/')) + [IO.Path]::DirectorySeparatorChar",
16197
+ " if (-not $fx_tT.StartsWith($fx_rootT, [StringComparison]::OrdinalIgnoreCase)) { $fx_t = $null }",
16198
+ // only a directory entry may name the destination itself
16199
+ " elseif ($fx_tT.Length -eq $fx_rootT.Length -and -not $fx_isDir) { $fx_t = $null; $fx_why = 'names the destination itself' }",
16200
+ " }",
16201
+ " }",
16202
+ " if ($null -eq $fx_t) { $fx_bad += ,@($fx_n, $fx_why) } else { $fx_plan += ,@($fx_e, $fx_t, $fx_isDir) }",
16203
+ " }",
16204
+ " if ($fx_bad.Count -gt 0) {",
16205
+ ` foreach ($fx_b in $fx_bad) { [Console]::Error.WriteLine("unzip: fauxnix: refusing unsafe entry '" + $fx_b[0] + "' (" + $fx_b[1] + ")") }`,
16206
+ " $script:fx_exit = 1",
16207
+ " } else {",
16208
+ // targets written by this run (case-insensitive, like NTFS)
16209
+ " $fx_done = @{}",
16210
+ " foreach ($fx_p in $fx_plan) {",
16211
+ " $fx_e = $fx_p[0]",
16212
+ " $fx_t = $fx_p[1]",
16213
+ " try {",
16214
+ // An existing symlink/junction below the root (or at the target)
16215
+ // would redirect the write outside the destination.
16216
+ " $fx_linked = $false",
16217
+ " $fx_cur = $fx_t.TrimEnd([char[]]@('\\', '/'))",
16218
+ " while ($null -ne $fx_cur -and $fx_cur.Length -ge $fx_rootT.Length) {",
16219
+ " $fx_attr = $null",
16220
+ " try { $fx_attr = [IO.File]::GetAttributes($fx_cur) } catch {}",
16221
+ " if ($null -ne $fx_attr -and ($fx_attr -band [IO.FileAttributes]::ReparsePoint)) { $fx_linked = $true; break }",
16222
+ " $fx_cur = [IO.Path]::GetDirectoryName($fx_cur)",
16223
+ " }",
16224
+ " if ($fx_linked) {",
16225
+ ` [Console]::Error.WriteLine("unzip: fauxnix: refusing entry '" + $fx_e.FullName + "' (path goes through a symbolic link or junction)")`,
16226
+ " $script:fx_exit = 1",
16227
+ " continue",
16228
+ " }",
16229
+ " if ($fx_p[2]) {",
16230
+ " [void][IO.Directory]::CreateDirectory($fx_t)",
16231
+ " continue",
16232
+ " }",
16233
+ // Duplicate or case-colliding names inside the archive: without -o
16234
+ // the first one wins (warning only, like declining unzip's
16235
+ // overwrite prompt); with -o the later one replaces it.
16236
+ over ? " if ($false) {" : " if ($fx_done.ContainsKey($fx_t)) {",
16237
+ " [Console]::Error.WriteLine('unzip: fauxnix: skipping ' + $fx_e.FullName + ': same name as an entry already extracted (' + $fx_done[$fx_t] + ')')",
16238
+ " continue",
16239
+ " }",
16240
+ " if (Test-Path -LiteralPath $fx_t -PathType Container) {",
16241
+ " [Console]::Error.WriteLine('unzip: fauxnix: cannot extract ' + $fx_e.FullName + ': a directory with that name exists')",
16242
+ " $script:fx_exit = 1",
16243
+ " continue",
16244
+ " }",
16245
+ " if ((Test-Path -LiteralPath $fx_t) -and " + (over ? "$false" : "$true") + ") {",
16246
+ " [Console]::Error.WriteLine('unzip: fauxnix: ' + $fx_e.FullName + ' already exists (use -o to overwrite)')",
16247
+ " $script:fx_exit = 1",
16248
+ " continue",
16249
+ " }",
16250
+ " [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($fx_t))",
16251
+ ...over ? [
16252
+ // -o: a ReadOnly file would make ExtractToFile throw
16253
+ " if ([IO.File]::Exists($fx_t)) { $fx_a = [IO.File]::GetAttributes($fx_t); if ($fx_a -band [IO.FileAttributes]::ReadOnly) { [IO.File]::SetAttributes($fx_t, $fx_a -band (-bnot [IO.FileAttributes]::ReadOnly)) } }"
16254
+ ] : [],
16255
+ " [IO.Compression.ZipFileExtensions]::ExtractToFile($fx_e, $fx_t, $true)",
16256
+ " $fx_done[$fx_t] = $fx_e.FullName",
16257
+ " } catch { [Console]::Error.WriteLine('unzip: fauxnix: cannot extract ' + $fx_e.FullName + ': ' + $_.Exception.Message); $script:fx_exit = 1 }",
16258
+ " }",
16259
+ " }",
16260
+ " } catch { [Console]::Error.WriteLine('unzip: fauxnix: ' + $_.Exception.Message); $script:fx_exit = 1 } finally { if ($null -ne $fx_z) { $fx_z.Dispose() } }"
15949
16261
  ].join("\n"),
15950
16262
  "}"
15951
16263
  ].join("\n");
@@ -16054,7 +16366,7 @@ installAll();
16054
16366
  var import_node_fs7 = require("node:fs");
16055
16367
 
16056
16368
  // src/executor.ts
16057
- var import_node_crypto = require("node:crypto");
16369
+ var import_node_crypto2 = require("node:crypto");
16058
16370
  var import_node_fs5 = require("node:fs");
16059
16371
  var import_node_os2 = __toESM(require("node:os"), 1);
16060
16372
  var import_node_path3 = __toESM(require("node:path"), 1);
@@ -16116,6 +16428,7 @@ function clipUtf8(text, limit) {
16116
16428
  }
16117
16429
 
16118
16430
  // src/ps-host.ts
16431
+ var import_node_crypto = require("node:crypto");
16119
16432
  var import_node_child_process = require("node:child_process");
16120
16433
  var import_node_fs4 = require("node:fs");
16121
16434
 
@@ -16330,6 +16643,26 @@ var PowerShellHost = class {
16330
16643
  this.stderrChunks = [];
16331
16644
  return b;
16332
16645
  }
16646
+ /**
16647
+ * Synchronous best-effort termination for process-exit paths, where the
16648
+ * async stop() cannot be awaited. Fails pending waiters like stop().
16649
+ */
16650
+ killSync() {
16651
+ this.cancelNativeCapture();
16652
+ const proc = this.proc;
16653
+ this.proc = null;
16654
+ this.closed = true;
16655
+ this.failWaiters(new Error("fauxnix: PowerShell host stopped"));
16656
+ if (!proc) return;
16657
+ try {
16658
+ proc.stdin?.destroy();
16659
+ } catch {
16660
+ }
16661
+ try {
16662
+ proc.kill();
16663
+ } catch {
16664
+ }
16665
+ }
16333
16666
  async stop() {
16334
16667
  this.cancelNativeCapture();
16335
16668
  const proc = this.proc;
@@ -16400,7 +16733,7 @@ var PowerShellHost = class {
16400
16733
  };
16401
16734
  }
16402
16735
  if (started) return { ...started, cancelled: false, truncated: false };
16403
- const id2 = "f" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
16736
+ const id2 = "f" + Date.now().toString(36) + (0, import_node_crypto.randomBytes)(6).toString("hex");
16404
16737
  const resolvedLimits = { ...limits };
16405
16738
  if (resolvedLimits.stdoutMode === "spool") {
16406
16739
  resolvedLimits.stdoutSpoolPath = this.hostFile + "." + id2 + ".stdout";
@@ -17099,15 +17432,73 @@ function planRedirects(redirects) {
17099
17432
  }
17100
17433
  return r;
17101
17434
  }
17435
+ var STATE_DIR_RE = /^fauxnix-(\d+)-[0-9a-f]{24}$/;
17436
+ var STALE_MIN_AGE_MS = 6e4;
17437
+ var liveSessions = /* @__PURE__ */ new Set();
17438
+ function isProcessAlive(pid) {
17439
+ try {
17440
+ process.kill(pid, 0);
17441
+ return true;
17442
+ } catch (error) {
17443
+ return error.code !== "ESRCH";
17444
+ }
17445
+ }
17446
+ var staleSweepDone = false;
17447
+ function sweepStaleStateDirs(root = import_node_os2.default.tmpdir(), now = Date.now()) {
17448
+ const removed = [];
17449
+ let names;
17450
+ try {
17451
+ names = (0, import_node_fs5.readdirSync)(root);
17452
+ } catch {
17453
+ return removed;
17454
+ }
17455
+ for (const name of names) {
17456
+ const m = STATE_DIR_RE.exec(name);
17457
+ if (!m) continue;
17458
+ const pid = Number(m[1]);
17459
+ if (pid === process.pid || isProcessAlive(pid)) continue;
17460
+ const dir = import_node_path3.default.join(root, name);
17461
+ try {
17462
+ const st = (0, import_node_fs5.lstatSync)(dir);
17463
+ if (!st.isDirectory() || now - st.mtimeMs < STALE_MIN_AGE_MS) continue;
17464
+ (0, import_node_fs5.rmSync)(dir, { recursive: true, force: true });
17465
+ removed.push(dir);
17466
+ } catch {
17467
+ }
17468
+ }
17469
+ return removed;
17470
+ }
17471
+ function cleanupSessionStateSync() {
17472
+ for (const session of [...liveSessions]) session.releaseStateSync();
17473
+ }
17474
+ var exitCleanupInstalled = false;
17475
+ function installSessionExitCleanup() {
17476
+ if (exitCleanupInstalled) return;
17477
+ exitCleanupInstalled = true;
17478
+ process.once("exit", cleanupSessionStateSync);
17479
+ const signals = [
17480
+ ["SIGINT", 130],
17481
+ ["SIGTERM", 143],
17482
+ ["SIGHUP", 129]
17483
+ ];
17484
+ for (const [signal, code] of signals) {
17485
+ process.once(signal, () => {
17486
+ cleanupSessionStateSync();
17487
+ if (process.listenerCount(signal) === 0) process.exit(code);
17488
+ });
17489
+ }
17490
+ }
17102
17491
  var FauxnixSession = class {
17103
17492
  id;
17104
17493
  cwd = null;
17105
17494
  env = {};
17106
17495
  /** Exit code of the previous segment — powers bash's `$?`. */
17107
17496
  prevExit = null;
17497
+ /** Per-session private directory holding every state/spool file (#256). */
17498
+ stateDir;
17499
+ stateDirCreated = false;
17108
17500
  cwdFile;
17109
17501
  envFile;
17110
- scriptFile;
17111
17502
  hostFile;
17112
17503
  host = null;
17113
17504
  lifecycleLock = Promise.resolve();
@@ -17115,16 +17506,55 @@ var FauxnixSession = class {
17115
17506
  hasEnvSnapshot = false;
17116
17507
  powerShell;
17117
17508
  constructor() {
17118
- this.id = (0, import_node_crypto.randomUUID)().slice(0, 8);
17509
+ this.id = (0, import_node_crypto2.randomUUID)().slice(0, 8);
17119
17510
  this.powerShell = resolvePowerShell();
17120
17511
  this.bindFiles(this.id);
17121
17512
  }
17122
17513
  bindFiles(id2) {
17123
17514
  this.id = id2;
17124
- this.cwdFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-cwd.txt");
17125
- this.envFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-env.json");
17126
- this.scriptFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-script.ps1");
17127
- this.hostFile = import_node_path3.default.join(import_node_os2.default.tmpdir(), "fauxnix-" + id2 + "-host.ps1");
17515
+ this.stateDir = import_node_path3.default.join(
17516
+ import_node_os2.default.tmpdir(),
17517
+ "fauxnix-" + process.pid + "-" + (0, import_node_crypto2.randomBytes)(12).toString("hex")
17518
+ );
17519
+ this.stateDirCreated = false;
17520
+ this.cwdFile = import_node_path3.default.join(this.stateDir, "cwd.txt");
17521
+ this.envFile = import_node_path3.default.join(this.stateDir, "env.json");
17522
+ this.hostFile = import_node_path3.default.join(this.stateDir, "host.ps1");
17523
+ }
17524
+ /** Paths of this session's private state (diagnostics and tests). */
17525
+ get statePaths() {
17526
+ return { dir: this.stateDir, cwd: this.cwdFile, env: this.envFile, host: this.hostFile };
17527
+ }
17528
+ /** Lazily create the private state directory (owner-only where POSIX modes apply). */
17529
+ ensureStateDir() {
17530
+ if (this.stateDirCreated) return;
17531
+ if (!staleSweepDone) {
17532
+ staleSweepDone = true;
17533
+ sweepStaleStateDirs();
17534
+ }
17535
+ (0, import_node_fs5.mkdirSync)(this.stateDir, { mode: 448 });
17536
+ this.stateDirCreated = true;
17537
+ liveSessions.add(this);
17538
+ }
17539
+ /**
17540
+ * Synchronous, best-effort release for process-exit paths: terminate the
17541
+ * host first (on Windows its open spool/checkpoint handles would make the
17542
+ * delete fail), then remove the directory with retries. The session stays
17543
+ * usable: the next run recreates a directory and a host.
17544
+ */
17545
+ releaseStateSync() {
17546
+ if (this.host) {
17547
+ this.host.killSync();
17548
+ this.host = null;
17549
+ }
17550
+ if (this.stateDirCreated) {
17551
+ try {
17552
+ (0, import_node_fs5.rmSync)(this.stateDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
17553
+ } catch {
17554
+ }
17555
+ this.stateDirCreated = false;
17556
+ }
17557
+ liveSessions.delete(this);
17128
17558
  }
17129
17559
  withLock(fn) {
17130
17560
  const done = this.lifecycleLock.then(fn, fn);
@@ -17155,6 +17585,7 @@ var FauxnixSession = class {
17155
17585
  }
17156
17586
  ensureHost() {
17157
17587
  if (!this.host) {
17588
+ this.ensureStateDir();
17158
17589
  this.host = new PowerShellHost(this.hostFile, () => this.childEnv(), this.powerShell);
17159
17590
  }
17160
17591
  return this.host;
@@ -17184,13 +17615,12 @@ var FauxnixSession = class {
17184
17615
  this.env = {};
17185
17616
  this.hasEnvSnapshot = false;
17186
17617
  this.prevExit = null;
17187
- await Promise.allSettled([
17188
- import_node_fs5.promises.rm(this.cwdFile, { force: true }),
17189
- import_node_fs5.promises.rm(this.envFile, { force: true }),
17190
- import_node_fs5.promises.rm(this.scriptFile, { force: true }),
17191
- import_node_fs5.promises.rm(this.hostFile, { force: true })
17192
- ]);
17193
- this.bindFiles((0, import_node_crypto.randomUUID)().slice(0, 8));
17618
+ if (this.stateDirCreated) {
17619
+ await import_node_fs5.promises.rm(this.stateDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }).catch(() => void 0);
17620
+ this.stateDirCreated = false;
17621
+ }
17622
+ liveSessions.delete(this);
17623
+ this.bindFiles((0, import_node_crypto2.randomUUID)().slice(0, 8));
17194
17624
  }
17195
17625
  /** env for the child powershell process. */
17196
17626
  childEnv(cwdOverride, stdinFile) {
@@ -17604,12 +18034,11 @@ function writeSpoolToPrepFd(fds, file2, target) {
17604
18034
 
17605
18035
  // src/version.ts
17606
18036
  var import_node_fs6 = require("node:fs");
17607
- var import_meta2 = {};
17608
18037
  var bundled = globalThis.__FAUXNIX_VERSION__;
17609
18038
  var version = bundled;
17610
18039
  if (typeof version !== "string") {
17611
18040
  const metadata = JSON.parse(
17612
- (0, import_node_fs6.readFileSync)(new URL("../package.json", import_meta2.url), "utf8")
18041
+ (0, import_node_fs6.readFileSync)(new URL("../package.json", "file://fauxnix-sea/"), "utf8")
17613
18042
  );
17614
18043
  version = metadata.version;
17615
18044
  }
@@ -17767,9 +18196,10 @@ function parseDashC(argv) {
17767
18196
  }
17768
18197
  async function runFacade(argv) {
17769
18198
  trace("argv", argv.join(" "));
18199
+ installSessionExitCleanup();
17770
18200
  const session = new FauxnixSession();
17771
18201
  try {
17772
- if (argv[0] === "--version") {
18202
+ if (argv.some((a) => a === "--version")) {
17773
18203
  process.stdout.write(VERSION_LINE);
17774
18204
  return 0;
17775
18205
  }