@poe-platform/safe-bash 0.1.756 → 0.1.757

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/image-ast/index.browser.js +4 -4
  2. package/dist/image-ast/index.js +4 -4
  3. package/dist/safe-bash/chunks/{chunk-LESPJ3OG.js → chunk-WNWIBBJZ.js} +15 -2
  4. package/dist/safe-bash/command-chunks/{chunk-S4J6MSLY.js → chunk-444OTXM7.js} +3 -3
  5. package/dist/safe-bash/command-chunks/{chunk-6AIOGLZO.js → chunk-CE6Z2ULX.js} +2 -2
  6. package/dist/safe-bash/command-chunks/{chunk-5VSGEE6J.js → chunk-F4IQCXZG.js} +5 -5
  7. package/dist/safe-bash/command-chunks/{chunk-F5MORDSU.js → chunk-FDNCPZQS.js} +32 -1
  8. package/dist/safe-bash/command-chunks/{chunk-SG3ZDZCX.js → chunk-FLMLM7Y4.js} +2 -2
  9. package/dist/safe-bash/command-chunks/{chunk-CT3FB722.js → chunk-J7UMKBRK.js} +1 -1
  10. package/dist/safe-bash/command-chunks/{chunk-QQOAK7JQ.js → chunk-KKJCKPTA.js} +1 -1
  11. package/dist/safe-bash/command-chunks/{chunk-7KS6PX4U.js → chunk-KSIGF4AG.js} +3 -3
  12. package/dist/safe-bash/command-chunks/{chunk-4HQ7WYSI.js → chunk-MED2BOOW.js} +30 -5
  13. package/dist/safe-bash/command-chunks/{chunk-JRNLDPLI.js → chunk-OZSWW23M.js} +1 -1
  14. package/dist/safe-bash/command-chunks/{chunk-DKQ5REXF.js → chunk-QDPRSPHQ.js} +1 -1
  15. package/dist/safe-bash/command-chunks/{chunk-WOPU2VWF.js → chunk-RID3B5RE.js} +1 -1
  16. package/dist/safe-bash/command-chunks/{chunk-DVZCHNB5.js → chunk-S4MLIYSN.js} +7 -7
  17. package/dist/safe-bash/command-chunks/{chunk-REYTQLLB.js → chunk-TT2DMDBY.js} +1 -1
  18. package/dist/safe-bash/command-chunks/{chunk-UGX6MXDD.js → chunk-UIIT4ULR.js} +3 -3
  19. package/dist/safe-bash/command-chunks/{chunk-A6NFLWZI.js → chunk-WKPOGTZY.js} +22 -6
  20. package/dist/safe-bash/command-chunks/{chunk-3DOHQQJR.js → chunk-Y64PA6IA.js} +8 -8
  21. package/dist/safe-bash/command-chunks/{chunk-6Z7OS3TZ.js → chunk-ZP5KDHB4.js} +7 -7
  22. package/dist/safe-bash/commands/pandoc/index.d.ts +1 -1
  23. package/dist/safe-bash/commands/pandoc/index.js +5 -3
  24. package/dist/safe-bash/commands/python/index.browser.js +1 -1
  25. package/dist/safe-bash/commands/python/index.js +6 -0
  26. package/dist/safe-bash/commands/python/jspi.js +11 -2
  27. package/dist/safe-bash/core.browser.js +6 -4
  28. package/dist/safe-bash-command-csvkit/index.js +8 -8
  29. package/dist/safe-bash-command-soffice/index.js +16 -16
  30. package/dist/safe-bash-command-ssconvert/core.js +8 -8
  31. package/dist/safe-bash-command-ssconvert/formats/csv.js +9 -9
  32. package/dist/safe-bash-command-ssconvert/formats/ods.js +8 -8
  33. package/dist/safe-bash-command-ssconvert/formats/spreadsheetml.js +1 -1
  34. package/dist/safe-bash-command-ssconvert/formats/xls.js +9 -8
  35. package/dist/safe-bash-command-ssconvert/formats/xlsx.js +8 -8
  36. package/dist/safe-bash-command-ssconvert/index.js +107 -27
  37. package/dist/safe-bash-contracts/filesystem-descriptor.js +1 -1
  38. package/dist/safe-bash-contracts/filesystem-output.js +1 -1
  39. package/dist/safe-bash-mcp/index.js +4 -4
  40. package/dist/spreadsheet-engine/formulas/ast.d.ts +13 -0
  41. package/dist/spreadsheet-engine/formulas/conventions.js +1 -1
  42. package/dist/spreadsheet-engine/formulas/dependencies.js +2 -2
  43. package/dist/spreadsheet-engine/formulas/evaluator.js +2 -2
  44. package/dist/spreadsheet-engine/formulas/named-expressions.d.ts +2 -2
  45. package/dist/spreadsheet-engine/formulas/named-expressions.js +31 -5
  46. package/dist/spreadsheet-engine/formulas/parser.js +34 -0
  47. package/dist/spreadsheet-engine/formulas/rewriting.js +19 -1
  48. package/dist/spreadsheet-engine/formulas/serialization.js +6 -0
  49. package/dist/spreadsheet-format-xls/biff-write-formulas.js +2 -0
  50. package/dist/xlsx-ast/formula-semantics.js +2 -0
  51. package/package.json +2 -2
  52. package/dist/safe-bash/chunks/browser-ECQX6GMK.js +0 -6766
  53. package/dist/safe-bash/chunks/bz2-4OP3OWW3.js +0 -8
  54. package/dist/safe-bash/chunks/chunk-22XPAAOI.js +0 -173
  55. package/dist/safe-bash/chunks/chunk-44WUNUPV.js +0 -649
  56. package/dist/safe-bash/chunks/chunk-4E3SGG37.js +0 -876
  57. package/dist/safe-bash/chunks/chunk-4QTSSQKP.js +0 -898
  58. package/dist/safe-bash/chunks/chunk-5UVGPVXP.js +0 -410
  59. package/dist/safe-bash/chunks/chunk-64OE6Q6X.js +0 -3487
  60. package/dist/safe-bash/chunks/chunk-6IIFUPN2.js +0 -1526
  61. package/dist/safe-bash/chunks/chunk-BENDLTQD.js +0 -7065
  62. package/dist/safe-bash/chunks/chunk-BMO5LWEX.js +0 -534
  63. package/dist/safe-bash/chunks/chunk-BPMCPTNP.js +0 -1920
  64. package/dist/safe-bash/chunks/chunk-BRJTAWP5.js +0 -2955
  65. package/dist/safe-bash/chunks/chunk-C3GEIN7Q.js +0 -20054
  66. package/dist/safe-bash/chunks/chunk-CBVANNKK.js +0 -174814
  67. package/dist/safe-bash/chunks/chunk-CEWCRI6H.js +0 -2813
  68. package/dist/safe-bash/chunks/chunk-CGL53DQQ.js +0 -37
  69. package/dist/safe-bash/chunks/chunk-CTYJJD4O.js +0 -869
  70. package/dist/safe-bash/chunks/chunk-CWSS4MQA.js +0 -7
  71. package/dist/safe-bash/chunks/chunk-DLIGMTCP.js +0 -3266
  72. package/dist/safe-bash/chunks/chunk-EMAJ7WUW.js +0 -1031
  73. package/dist/safe-bash/chunks/chunk-FDKIZ2IJ.js +0 -1950
  74. package/dist/safe-bash/chunks/chunk-FZWJ2A7V.js +0 -3093
  75. package/dist/safe-bash/chunks/chunk-G2VCIF2J.js +0 -22
  76. package/dist/safe-bash/chunks/chunk-GVKBUQDX.js +0 -2649
  77. package/dist/safe-bash/chunks/chunk-IO2OGW3E.js +0 -28051
  78. package/dist/safe-bash/chunks/chunk-ISCZG7WA.js +0 -2648
  79. package/dist/safe-bash/chunks/chunk-JCN3FXLP.js +0 -38983
  80. package/dist/safe-bash/chunks/chunk-KJHDD4A2.js +0 -759
  81. package/dist/safe-bash/chunks/chunk-LB6HVRXS.js +0 -857
  82. package/dist/safe-bash/chunks/chunk-LLWAJOZH.js +0 -15
  83. package/dist/safe-bash/chunks/chunk-LMUKYZIJ.js +0 -708
  84. package/dist/safe-bash/chunks/chunk-M5SCNKIK.js +0 -2012
  85. package/dist/safe-bash/chunks/chunk-MJPFHANT.js +0 -3350
  86. package/dist/safe-bash/chunks/chunk-MZQW2DOL.js +0 -82
  87. package/dist/safe-bash/chunks/chunk-NB2V7EOY.js +0 -1348
  88. package/dist/safe-bash/chunks/chunk-NJVGOIYN.js +0 -17
  89. package/dist/safe-bash/chunks/chunk-OLNZHDIQ.js +0 -5141
  90. package/dist/safe-bash/chunks/chunk-OSUXMC43.js +0 -2317
  91. package/dist/safe-bash/chunks/chunk-OUUVROTM.js +0 -38
  92. package/dist/safe-bash/chunks/chunk-PA6GYKBQ.js +0 -151
  93. package/dist/safe-bash/chunks/chunk-PEFHZ226.js +0 -6957
  94. package/dist/safe-bash/chunks/chunk-QBB5P5KW.js +0 -4839
  95. package/dist/safe-bash/chunks/chunk-RSAWYAEH.js +0 -973
  96. package/dist/safe-bash/chunks/chunk-UWLYRWT4.js +0 -739
  97. package/dist/safe-bash/chunks/chunk-V463NBQH.js +0 -13
  98. package/dist/safe-bash/chunks/chunk-WPUALYUS.js +0 -843
  99. package/dist/safe-bash/chunks/chunk-XHKFSRGU.js +0 -5747
  100. package/dist/safe-bash/chunks/chunk-XHRCLZ3N.js +0 -13391
  101. package/dist/safe-bash/chunks/chunk-XPF5XHLY.js +0 -15
  102. package/dist/safe-bash/chunks/chunk-ZBFOWARG.js +0 -305
  103. package/dist/safe-bash/chunks/chunk-ZG7GWQ5P.js +0 -1859
  104. package/dist/safe-bash/chunks/model-store-EIY3ZQLZ.js +0 -10
  105. package/dist/safe-bash/chunks/pdf-renderer-CMF3CSVU.js +0 -22
  106. package/dist/safe-bash/chunks/pptx-ZL6L7KP2-O425BFIU.js +0 -30658
  107. package/dist/safe-bash/chunks/src-HHEPGR7U.js +0 -18969
  108. package/dist/safe-bash/chunks/src-MXIKQCIC.js +0 -187
  109. package/dist/safe-bash/chunks/usage-6TGVA2OM.js +0 -35
  110. package/dist/safe-bash/chunks/xz-EGQGQUEI.js +0 -8
  111. package/dist/safe-bash/chunks/xz-K2E2WLM6.js +0 -9
  112. package/dist/safe-bash/chunks/zstd-6JBLP5EF.js +0 -8
  113. package/dist/safe-bash/git_rust-C3QYOAZL.wasm +0 -0
@@ -1,2648 +0,0 @@
1
- import {
2
- __reExport,
3
- init_platform
4
- } from "./chunk-ZG7GWQ5P.js";
5
-
6
- // packages/safe-bash-io-engine/src/internal.ts
7
- init_platform();
8
- import { builtInDirectContextExecutors } from "../../safe-bash-contracts/runtime-control.js";
9
-
10
- // packages/safe-bash-query-engine/src/path.ts
11
- var path_exports = {};
12
- init_platform();
13
- __reExport(path_exports, path_star);
14
- import * as path_star from "../../safe-bash-contracts/path.js";
15
-
16
- // packages/safe-bash-io-engine/src/internal.ts
17
- import { UsageError, publicDiagnosticMessage } from "../../safe-bash-contracts/diagnostics.js";
18
- import { assertCommandRequirements } from "../../safe-bash-contracts/command-requirements.js";
19
- import { writeDiagnostic as writeDiagnostic2 } from "../../safe-bash-contracts/escaping.js";
20
-
21
- // packages/safe-bash-io-engine/src/portable-requirements.ts
22
- init_platform();
23
- var inputRequirements = [
24
- { id: "stdin", description: "Read standard input", capabilities: [] },
25
- { id: "file", description: "Read file operands", capabilities: [], anyOf: [["streamingRead"], ["read"]] }
26
- ];
27
- var textOutputRequirements = [
28
- ...inputRequirements,
29
- { id: "output", description: "Write or truncate an output file", capabilities: [], anyOf: [["streamingWrite"], ["write"]], mutates: true }
30
- ];
31
- var pwdRequirements = [
32
- { id: "logical", description: "Print the logical working directory", capabilities: [] },
33
- { id: "physical", description: "Resolve the physical working directory (-P)", capabilities: ["realpath"] }
34
- ];
35
- var predicateRequirements = [
36
- { id: "expression", description: "Evaluate strings and integers", capabilities: [] },
37
- { id: "metadata", description: "Inspect file metadata", capabilities: ["stat"] },
38
- { id: "access", description: "Inspect path access permissions", capabilities: ["access"] }
39
- ];
40
-
41
- // packages/safe-bash-io-engine/src/record-buffer.ts
42
- init_platform();
43
- import { FsError } from "../../safe-bash-contracts/index.js";
44
- var segmentSize = 4096;
45
- var RecordBuffer = class {
46
- constructor(capacity, finalizationCapacity = capacity * 2) {
47
- this.capacity = capacity;
48
- this.finalizationCapacity = finalizationCapacity;
49
- }
50
- capacity;
51
- finalizationCapacity;
52
- #segments = [];
53
- #size = 0;
54
- #allocated = 0;
55
- get size() {
56
- return this.#size;
57
- }
58
- #admit(length) {
59
- if (length > this.capacity - this.#size) {
60
- throw new FsError("EFBIG", { message: "line buffer limit exceeded" });
61
- }
62
- }
63
- append(bytes, start = 0, end = bytes.length) {
64
- this.#admit(end - start);
65
- let offset = start;
66
- while (offset < end) {
67
- let segment = this.#segments.at(-1);
68
- const used = this.#size % segmentSize;
69
- if (!segment || used === 0) {
70
- segment = new Uint8Array(Math.min(segmentSize, this.capacity - this.#allocated));
71
- this.#segments.push(segment);
72
- this.#allocated += segment.length;
73
- }
74
- const length = Math.min(end - offset, segment.length - used);
75
- segment.set(bytes.subarray(offset, offset + length), used);
76
- this.#size += length;
77
- offset += length;
78
- }
79
- }
80
- finish(admit, bytes, start = 0, end = bytes?.length ?? 0) {
81
- const tailLength = end - start;
82
- this.#admit(tailLength);
83
- const size = this.#size + tailLength;
84
- admit?.(size);
85
- if (size > this.finalizationCapacity - this.#allocated) {
86
- throw new FsError("EFBIG", { message: "line finalization buffer limit exceeded" });
87
- }
88
- if (this.#size === 0) {
89
- const result2 = new Uint8Array(tailLength);
90
- if (bytes && tailLength > 0) result2.set(bytes.subarray(start, end));
91
- return result2;
92
- }
93
- const result = new Uint8Array(size);
94
- let offset = 0;
95
- for (const segment of this.#segments) {
96
- const length = Math.min(segment.length, this.#size - offset);
97
- result.set(segment.subarray(0, length), offset);
98
- offset += length;
99
- }
100
- if (bytes && tailLength > 0) result.set(bytes.subarray(start, end), offset);
101
- this.clear();
102
- return result;
103
- }
104
- clear() {
105
- if (this.#segments.length) this.#segments.length = 0;
106
- this.#size = 0;
107
- this.#allocated = 0;
108
- }
109
- };
110
-
111
- // packages/safe-bash-io-engine/src/gnu-information.ts
112
- init_platform();
113
- import { writeBytes } from "../../safe-bash-contracts/index.js";
114
- var information = {
115
- cat: { usage: "[OPTION]... [FILE]...", description: "Concatenate input files.", options: ["-n, --number", "-b, --number-nonblank", "-s, --squeeze-blank", "-E, --show-ends", "-T, --show-tabs", "-v, --show-nonprinting", "-A, --show-all"], versionOnly: true },
116
- du: { usage: "[OPTION]... [FILE]...", description: "Report virtual file allocation.", options: ["-a, --all", "-s, --summarize", "-c, --total", "-h, --human-readable", "-B, --block-size=SIZE", "-b, --bytes", "--apparent-size", "-d, --max-depth=NUM", "-X, --exclude-from=FILE", "--exclude=PATTERN", "-t, --threshold=SIZE"], versionOnly: true },
117
- base32: { usage: "[OPTION]... [FILE]", description: "Encode or decode Base32 data.", options: ["-d, --decode", "-i, --ignore-garbage", "-w, --wrap=COLS"] },
118
- base64: { usage: "[OPTION]... [FILE]", description: "Encode or decode Base64 data.", options: ["-d, --decode", "-i, --ignore-garbage", "-w, --wrap=COLS"] },
119
- basename: { usage: "[OPTION]... NAME... [SUFFIX]", description: "Remove directory components and an optional suffix from names.", options: ["-a, --multiple", "-s, --suffix=SUFFIX", "-z, --zero"] },
120
- dirname: { usage: "[OPTION]... NAME...", description: "Print the directory component of each name.", options: ["-z, --zero"] },
121
- chmod: { usage: "[OPTION]... MODE FILE...", description: "Change virtual file permissions, subject to filesystem capabilities.", options: ["-R, --recursive", "-v, --verbose", "-c, --changes", "-f, --silent, --quiet", "--reference=FILE"] },
122
- cksum: { usage: "[OPTION]... [FILE]...", description: "Compute checksums of files or standard input.", options: ["-a, --algorithm=TYPE", "-b, --binary", "-z, --zero", "--tag", "--untagged", "--raw", "--base64"] },
123
- comm: { usage: "[OPTION]... FILE1 FILE2", description: "Compare sorted files in the C/POSIX byte locale.", options: ["-1", "-2", "-3", "--output-delimiter=STR", "--check-order", "--nocheck-order"] },
124
- cp: { usage: "[OPTION]... SOURCE... DEST", description: "Copy virtual files, subject to filesystem capabilities.", options: ["-a, --archive", "-r, -R, --recursive", "-f, --force", "-i, --interactive", "-n, --no-clobber", "-v, --verbose", "-t, --target-directory=DIR", "-T, --no-target-directory", "-S, --suffix=SUFFIX"] },
125
- cut: { usage: "[OPTION]... [FILE]...", description: "Select bytes, characters or fields from each input line.", options: ["-b, --bytes=LIST", "-c, --characters=LIST", "-f, --fields=LIST", "-d, --delimiter=CHAR", "-s, --only-delimited", "-z, --zero-terminated", "--output-delimiter=STR", "--complement"] },
126
- env: { usage: "[OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]", description: "Print the environment or run a registered command with a modified environment.", options: ["-i, --ignore-environment", "-u, --unset=NAME", "-C, --chdir=DIR", "-S, --split-string=STR", "-0, --null"], stopAtOperand: true },
127
- expand: { usage: "[OPTION]... [FILE]...", description: "Convert tabs to spaces.", options: ["-i, --initial", "-t, --tabs=LIST"] },
128
- fold: { usage: "[OPTION]... [FILE]...", description: "Wrap input lines to a selected width.", options: ["-b, --bytes", "-s, --spaces", "-w, --width=COLS"] },
129
- head: { usage: "[OPTION]... [FILE]...", description: "Print the first ten lines by default, or a selected line/byte count.", options: ["-n, --lines=NUM", "-c, --bytes=NUM", "-q, --quiet, --silent", "-v, --verbose", "-z, --zero-terminated"] },
130
- tail: { usage: "[OPTION]... [FILE]...", description: "Print the last ten lines by default, or a selected line/byte count.", options: ["-n, --lines=NUM", "-c, --bytes=NUM", "-q, --quiet, --silent", "-v, --verbose", "-z, --zero-terminated"] },
131
- join: { usage: "[OPTION]... FILE1 FILE2", description: "Join sorted files on a common field in the C/POSIX byte locale.", options: ["-1=FIELD", "-2=FIELD", "-j=FIELD", "-t=CHAR", "-a=FILENUM", "-v=FILENUM", "-e=STR", "-o=FORMAT", "-i", "--check-order", "--nocheck-order"] },
132
- ln: { usage: "[OPTION]... TARGET... LINK_NAME", description: "Create virtual hard or symbolic links when supported by the filesystem.", options: ["-s, --symbolic", "-r, --relative", "-f, --force", "-i, --interactive", "-n, --no-dereference", "-v, --verbose", "-t, --target-directory=DIR", "-T, --no-target-directory", "-S, --suffix=SUFFIX"] },
133
- ls: { usage: "[OPTION]... [FILE]...", description: "List virtual directory entries.", options: ["-a, --all", "-A, --almost-all", "-l", "-1", "-d, --directory", "-F, --classify", "-r, --reverse", "-R, --recursive", "-L, --dereference", "-h, --human-readable"] },
134
- mkdir: { usage: "[OPTION]... DIRECTORY...", description: "Create virtual directories.", options: ["-p, --parents", "-m, --mode=MODE", "-v, --verbose"] },
135
- mktemp: { usage: "[OPTION]... [TEMPLATE]", description: "Create a temporary virtual file or directory.", options: ["-d, --directory", "-q, --quiet", "-u, --dry-run", "-p=DIR", "--tmpdir[=DIR]", "--suffix=SUFFIX"] },
136
- mv: { usage: "[OPTION]... SOURCE... DEST", description: "Move virtual files, subject to filesystem capabilities.", options: ["-f, --force", "-i, --interactive", "-n, --no-clobber", "-u, --update", "-v, --verbose", "-t, --target-directory=DIR", "-T, --no-target-directory", "-S, --suffix=SUFFIX"] },
137
- nl: { usage: "[OPTION]... [FILE]...", description: "Number input lines by section and numbering style.", options: ["-b, --body-numbering=STYLE", "-h, --header-numbering=STYLE", "-f, --footer-numbering=STYLE", "-v, --starting-line-number=NUM", "-i, --line-increment=NUM", "-s, --number-separator=STR", "-w, --number-width=NUM", "-n, --number-format=FORMAT", "-d, --section-delimiter=STR", "-l, --join-blank-lines=NUM", "-p, --no-renumber"] },
138
- od: { usage: "[OPTION]... [FILE]...", description: "Print input bytes in selected numeric formats.", options: ["-A, --address-radix=RADIX", "-j, --skip-bytes=NUM", "-N, --read-bytes=NUM", "-t, --format=TYPE, --type=TYPE", "-w, --width=NUM", "--endian=ORDER", "-v, --output-duplicates"] },
139
- paste: { usage: "[OPTION]... [FILE]...", description: "Merge corresponding or serial input lines.", options: ["-s, --serial", "-d, --delimiters=LIST", "-z, --zero-terminated"] },
140
- readlink: { usage: "[OPTION]... FILE...", description: "Print symbolic link targets or canonical virtual paths.", options: ["-f, --canonicalize", "-e, --canonicalize-existing", "-m, --canonicalize-missing", "-n, --no-newline", "-z, --zero"] },
141
- realpath: { usage: "[OPTION]... FILE...", description: "Print canonical virtual paths.", options: ["-e, --canonicalize-existing", "-m, --canonicalize-missing", "-s, --strip, --no-symlinks", "-z, --zero"] },
142
- rm: { usage: "[OPTION]... FILE...", description: "Remove virtual files and directories.", options: ["-r, -R, --recursive", "-f, --force", "-d, --dir", "-v, --verbose", "-i", "-I"] },
143
- rmdir: { usage: "[OPTION]... DIRECTORY...", description: "Remove empty virtual directories.", options: ["-p, --parents", "-v, --verbose", "--ignore-fail-on-non-empty"] },
144
- seq: { usage: "[OPTION]... [FIRST [INCREMENT]] LAST", description: "Print a numeric sequence.", options: ["-s, --separator=STR", "-f, --format=FORMAT", "-w, --equal-width"] },
145
- sort: { usage: "[OPTION]... [FILE]...", description: "Sort input records using the supported byte-oriented ordering modes.", options: ["-n, --numeric-sort", "-g, --general-numeric-sort", "-h, --human-numeric-sort", "-V, --version-sort", "-r, --reverse", "-f, --ignore-case", "-u, --unique", "-s, --stable", "-m, --merge", "-k, --key=KEY", "-t, --field-separator=CHAR", "-o, --output=FILE", "--sort=MODE", "-z, --zero-terminated"] },
146
- split: { usage: "[OPTION]... [FILE [PREFIX]]", description: "Split input into virtual output files.", options: ["-l, --lines=NUM", "-b, --bytes=SIZE", "-C, --line-bytes=SIZE", "-a, --suffix-length=NUM", "--additional-suffix=SUFFIX"] },
147
- stat: { usage: "[OPTION]... FILE...", description: "Display virtual file metadata supplied by the filesystem.", options: ["-L, --dereference", "-c, --format=FORMAT", "--printf=FORMAT", "-t, --terse"] },
148
- tac: { usage: "[OPTION]... [FILE]...", description: "Print input records in reverse order.", options: ["-b, --before", "-r, --regex", "-s, --separator=STR"] },
149
- tee: { usage: "[OPTION]... [FILE]...", description: "Copy standard input to standard output and virtual files.", options: ["-a, --append", "-i, --ignore-interrupts", "--output-error=MODE"] },
150
- touch: { usage: "[OPTION]... FILE...", description: "Update virtual file timestamps, creating missing files by default.", options: ["-a", "-m", "-c, --no-create", "-h, --no-dereference", "-r, --reference=FILE", "-d, --date=STR", "-t=STAMP"] },
151
- tr: { usage: "[OPTION]... STRING1 [STRING2]", description: "Translate, delete or squeeze input bytes.", options: ["-d, --delete", "-s, --squeeze-repeats", "-c, -C, --complement", "-t, --truncate-set1"] },
152
- unexpand: { usage: "[OPTION]... [FILE]...", description: "Convert spaces to tabs.", options: ["-a, --all", "-t, --tabs=LIST", "--first-only"] },
153
- uniq: { usage: "[OPTION]... [INPUT [OUTPUT]]", description: "Filter adjacent repeated input records.", options: ["-c, --count", "-d, --repeated", "-u, --unique", "-i, --ignore-case", "-f, --skip-fields=NUM", "-s, --skip-chars=NUM", "-w, --check-chars=NUM", "-z, --zero-terminated"] },
154
- wc: { usage: "[OPTION]... [FILE]...", description: "Count input lines, words, bytes, characters or display width.", options: ["-l, --lines", "-w, --words", "-c, --bytes", "-m, --chars", "-L, --max-line-length"] },
155
- pwd: { usage: "[OPTION]...", description: "Print the full filename of the current working directory.", options: ["-L, --logical", "-P, --physical"] },
156
- true: { usage: "[ignored command line arguments]", description: "Exit with a status code indicating success.", options: [] },
157
- false: { usage: "[ignored command line arguments]", description: "Exit with a status code indicating failure.", options: [] },
158
- echo: { usage: "[SHORT-OPTION]... [STRING]...", description: "Echo the STRING(s) to standard output.", options: ["-n", "-e", "-E"] },
159
- "[": { usage: "EXPRESSION ]", description: "Evaluate conditional expression.", options: [] }
160
- };
161
- var checksumInformation = {
162
- usage: "[OPTION]... [FILE]...",
163
- description: "Compute or verify file digests.",
164
- options: ["-b, --binary", "-c, --check", "-t, --text", "-z, --zero", "--tag", "--quiet", "--status", "--strict", "--warn", "--ignore-missing"]
165
- };
166
- function gnuInformationSync(name, args, externalInvocation = false) {
167
- if (!args.includes("--help") && !args.includes("--version")) return void 0;
168
- if ((name === "true" || name === "false" || name === "echo" || name === "[" || name === "pwd") && (args.length !== 1 || !externalInvocation)) return void 0;
169
- const info = information[name] ?? (["md5sum", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum"].includes(name) ? checksumInformation : void 0);
170
- if (!info) return void 0;
171
- const flags = /* @__PURE__ */ new Map();
172
- for (const option of info.options) {
173
- const takesValue = option.includes("[=") ? "optional" : option.includes("=") ? "required" : "none";
174
- for (const spelling of option.split(", ")) flags.set(spelling.split("=")[0].split("[")[0], takesValue);
175
- }
176
- for (let index = 0; index < args.length; index++) {
177
- const arg = args[index];
178
- if (arg === "--") break;
179
- if (arg === "--help" || arg === "--version") {
180
- if (arg === "--help" && info.versionOnly) return void 0;
181
- return arg === "--version" ? `${name} (safe-bash virtual implementation)
182
- ` : `Usage: ${name} ${info.usage}
183
- ${info.description}
184
-
185
- Common supported options (additional behavior is documented in the package):
186
- ${info.options.map((option) => ` ${option.split(", ").map((spelling) => spelling.startsWith("--") ? spelling : spelling.replace("=", " ")).join(", ")}`).join("\n")}
187
- --help display this help and exit
188
- --version display implementation information and exit
189
-
190
- This is the safe-bash virtual implementation; filesystem operations require backend capabilities.
191
- `;
192
- }
193
- if (!arg.startsWith("-") || arg === "-") {
194
- if (info.stopAtOperand) break;
195
- continue;
196
- }
197
- if (arg.startsWith("--")) {
198
- const equal = arg.indexOf("=");
199
- const spelling = equal < 0 ? arg : arg.slice(0, equal);
200
- if (!flags.has(spelling)) return void 0;
201
- if (flags.get(spelling) === "required" && equal < 0) index++;
202
- else if (flags.get(spelling) === "none" && equal >= 0) return void 0;
203
- } else {
204
- for (let offset = 1; offset < arg.length; offset++) {
205
- const spelling = `-${arg[offset]}`;
206
- if (!flags.has(spelling)) return void 0;
207
- if (flags.get(spelling) === "required") {
208
- if (offset + 1 === arg.length) index++;
209
- break;
210
- }
211
- }
212
- }
213
- }
214
- return void 0;
215
- }
216
- function gnuInformation(name, context) {
217
- if (!context.args.includes("--help") && !context.args.includes("--version")) return void 0;
218
- return gnuInformationSlow(name, context);
219
- }
220
- async function gnuInformationSlow(name, context) {
221
- if ((name === "true" || name === "false" || name === "echo" || name === "[") && (context.args.length !== 1 || !context.externalInvocation)) return void 0;
222
- const info = information[name] ?? (["md5sum", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum"].includes(name) ? checksumInformation : void 0);
223
- if (!info) return void 0;
224
- const flags = /* @__PURE__ */ new Map();
225
- for (const option of info.options) {
226
- const takesValue = option.includes("[=") ? "optional" : option.includes("=") ? "required" : "none";
227
- for (const spelling of option.split(", ")) flags.set(spelling.split("=")[0].split("[")[0], takesValue);
228
- }
229
- for (let index = 0; index < context.args.length; index++) {
230
- const arg = context.args[index];
231
- if (arg === "--") break;
232
- if (arg === "--help" || arg === "--version") {
233
- if (arg === "--help" && info.versionOnly) return void 0;
234
- const text = arg === "--version" ? `${name} (safe-bash virtual implementation)
235
- ` : `Usage: ${name} ${info.usage}
236
- ${info.description}
237
-
238
- Common supported options (additional behavior is documented in the package):
239
- ${info.options.map((option) => ` ${option.split(", ").map((spelling) => spelling.startsWith("--") ? spelling : spelling.replace("=", " ")).join(", ")}`).join("\n")}
240
- --help display this help and exit
241
- --version display implementation information and exit
242
-
243
- This is the safe-bash virtual implementation; filesystem operations require backend capabilities.
244
- `;
245
- await writeBytes(context.stdout, new TextEncoder().encode(text), context.signal);
246
- return { exitCode: 0 };
247
- }
248
- if (!arg.startsWith("-") || arg === "-") {
249
- if (info.stopAtOperand) break;
250
- continue;
251
- }
252
- if (arg.startsWith("--")) {
253
- const equal = arg.indexOf("=");
254
- const spelling = equal < 0 ? arg : arg.slice(0, equal);
255
- if (!flags.has(spelling)) return void 0;
256
- if (flags.get(spelling) === "required" && equal < 0) index++;
257
- else if (flags.get(spelling) === "none" && equal >= 0) return void 0;
258
- } else {
259
- for (let offset = 1; offset < arg.length; offset++) {
260
- const spelling = `-${arg[offset]}`;
261
- if (!flags.has(spelling)) return void 0;
262
- if (flags.get(spelling) === "required") {
263
- if (offset + 1 === arg.length) index++;
264
- break;
265
- }
266
- }
267
- }
268
- }
269
- return void 0;
270
- }
271
-
272
- // packages/safe-bash-io-engine/src/internal.ts
273
- import { getRuntimeBackingFileSystem } from "../../safe-bash-contracts/runtime-control.js";
274
- import {
275
- FsError as FsError3,
276
- readBytes,
277
- toByteSource,
278
- writeBytes as writeBytes3
279
- } from "../../safe-bash-contracts/index.js";
280
- import { builtInDirectContextExecutors as builtInDirectContextExecutors2 } from "../../safe-bash-contracts/runtime-control.js";
281
- import { isDefaultCommandOptions, registerDefaultExecutor, registerDefaultExecutors } from "../../safe-bash-contracts/command.js";
282
- import { UsageError as UsageError2 } from "../../safe-bash-contracts/diagnostics.js";
283
-
284
- // packages/safe-bash-io-engine/src/commands/touch-times.ts
285
- init_platform();
286
- import { PublicDiagnostic } from "../../safe-bash-contracts/diagnostics.js";
287
-
288
- // packages/safe-bash-calendar-engine/src/time-env/calendar.ts
289
- init_platform();
290
-
291
- // packages/safe-bash-calendar-engine/src/time-env/shared.ts
292
- init_platform();
293
-
294
- // packages/safe-bash-byte-engine/src/index.ts
295
- init_platform();
296
- var encoder = new TextEncoder();
297
- function utf8ByteLength(value2) {
298
- let size = 0;
299
- for (let i = 0; i < value2.length; i++) {
300
- const code = value2.charCodeAt(i);
301
- if (code < 128) size++;
302
- else if (code < 2048) size += 2;
303
- else if (code >= 55296 && code <= 56319 && i + 1 < value2.length && value2.charCodeAt(i + 1) >= 56320 && value2.charCodeAt(i + 1) <= 57343) {
304
- size += 4;
305
- i++;
306
- } else size += 3;
307
- }
308
- return size;
309
- }
310
- function bytesFrom(value2, offset, length) {
311
- if (typeof value2 === "string") {
312
- if (offset === "latin1") {
313
- const bytes = new Uint8Array(value2.length);
314
- for (let i = 0; i < value2.length; i++) bytes[i] = value2.charCodeAt(i) & 255;
315
- return bytes;
316
- }
317
- if (offset === "utf16le") {
318
- const bytes = new Uint8Array(value2.length * 2);
319
- for (let i = 0; i < value2.length; i++) {
320
- const unit = value2.charCodeAt(i);
321
- bytes[i * 2] = unit & 255;
322
- bytes[i * 2 + 1] = unit >>> 8;
323
- }
324
- return bytes;
325
- }
326
- return encoder.encode(value2);
327
- }
328
- if (Array.isArray(value2)) return Uint8Array.from(value2);
329
- if (value2 instanceof Uint8Array) return new Uint8Array(value2);
330
- return new Uint8Array(value2, typeof offset === "number" ? offset : void 0, length);
331
- }
332
- function concatBytes(parts, size = parts.reduce((sum, part) => sum + part.length, 0)) {
333
- const out = new Uint8Array(size);
334
- let offset = 0;
335
- for (const part of parts) {
336
- const length = Math.min(part.length, size - offset);
337
- out.set(part.subarray(0, length), offset);
338
- offset += length;
339
- if (offset === size) break;
340
- }
341
- return out;
342
- }
343
- function compareBytes(left, right) {
344
- for (let i = 0; i < Math.min(left.length, right.length); i++) if (left[i] !== right[i]) return left[i] < right[i] ? -1 : 1;
345
- return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;
346
- }
347
- function filledBytes(size, value2 = 0) {
348
- return new Uint8Array(size).fill(value2);
349
- }
350
- function latin1Text(bytes) {
351
- let result = "";
352
- for (const byte of bytes) result += String.fromCharCode(byte);
353
- return result;
354
- }
355
- function equalBytes(left, right) {
356
- if (left.length !== right.length) return false;
357
- for (let i = 0; i < left.length; i++) if (left[i] !== right[i]) return false;
358
- return true;
359
- }
360
- function base64Text(bytes) {
361
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
362
- let out = "";
363
- for (let i = 0; i < bytes.length; i += 3) {
364
- const a = bytes[i], b = bytes[i + 1] ?? 0, c = bytes[i + 2] ?? 0;
365
- out += alphabet[a >>> 2] + alphabet[(a & 3) << 4 | b >>> 4] + (i + 1 < bytes.length ? alphabet[(b & 15) << 2 | c >>> 6] : "=") + (i + 2 < bytes.length ? alphabet[c & 63] : "=");
366
- }
367
- return out;
368
- }
369
-
370
- // packages/safe-bash-calendar-engine/src/time-env/shared.ts
371
- import { writeDiagnostic } from "../../safe-bash-contracts/escaping.js";
372
- import { FsError as FsError2, writeBytes as writeBytes2 } from "../../safe-bash-contracts/index.js";
373
- var defaultSleepScheduler = {
374
- now: () => performance.now(),
375
- setTimeout: (callback, milliseconds) => setTimeout(callback, milliseconds),
376
- clearTimeout: (handle) => clearTimeout(handle)
377
- };
378
- function settings(options2) {
379
- const limits = {
380
- maxArguments: Infinity,
381
- maxArgumentBytes: Infinity,
382
- maxOutputBytes: Infinity,
383
- maxEnvironmentEntries: Infinity,
384
- maxFormatWidth: Infinity,
385
- ...options2.limits
386
- };
387
- for (const [name, value2] of Object.entries(limits)) {
388
- if (value2 !== Infinity && (!Number.isSafeInteger(value2) || value2 < 1)) throw new RangeError(`Invalid time-env limit: ${name}`);
389
- }
390
- const maxTimerMilliseconds = options2.maxTimerMilliseconds ?? 2147483647;
391
- if (maxTimerMilliseconds !== Infinity && (!Number.isInteger(maxTimerMilliseconds) || maxTimerMilliseconds < 1 || maxTimerMilliseconds > 2147483647)) {
392
- throw new RangeError("maxTimerMilliseconds must be between 1 and 2147483647 or Infinity");
393
- }
394
- const scheduler = options2.scheduler ?? defaultSleepScheduler;
395
- if (typeof scheduler.now !== "function" || typeof scheduler.setTimeout !== "function" || typeof scheduler.clearTimeout !== "function") {
396
- throw new TypeError("Invalid sleep scheduler");
397
- }
398
- if (options2.clock !== void 0 && typeof options2.clock !== "function") throw new TypeError("Invalid date clock");
399
- return {
400
- clock: options2.clock ?? Date.now,
401
- defaultTimeZone: options2.defaultTimeZone ?? "UTC",
402
- scheduler,
403
- maxTimerMilliseconds,
404
- limits
405
- };
406
- }
407
- var CommandFailure = class extends Error {
408
- constructor(message, exitCode = 1) {
409
- super(message);
410
- this.exitCode = exitCode;
411
- }
412
- exitCode;
413
- };
414
- function checkSize(size, maximum, label) {
415
- if (size > maximum) throw new FsError2("EFBIG", { message: `time-env ${label} limit exceeded` });
416
- }
417
- async function emit(context, value2, limits) {
418
- checkSize(utf8ByteLength(value2), limits.maxOutputBytes, "output");
419
- const bytes = new TextEncoder().encode(value2);
420
- for (let offset = 0; offset < bytes.length; offset += 16384) {
421
- await writeBytes2(context.stdout, bytes.slice(offset, offset + 16384), context.signal);
422
- }
423
- }
424
- var timeEnvExecutorSettings = /* @__PURE__ */ new WeakMap();
425
- function command(name, configuration, execute) {
426
- const def = { name, async execute(context) {
427
- context.signal.throwIfAborted();
428
- checkSize(context.args.length, configuration.limits.maxArguments, "argument count");
429
- let size = 0;
430
- for (const argument of context.args) {
431
- size += utf8ByteLength(argument);
432
- checkSize(size, configuration.limits.maxArgumentBytes, "argument");
433
- }
434
- try {
435
- return { exitCode: await execute(context) };
436
- } catch (error) {
437
- context.signal.throwIfAborted();
438
- if (!(error instanceof CommandFailure)) throw error;
439
- await writeDiagnostic(context.stderr, `${name}: ${error.message}
440
- `, context.signal);
441
- return { exitCode: error.exitCode };
442
- }
443
- } };
444
- timeEnvExecutorSettings.set(def.execute, configuration);
445
- return def;
446
- }
447
- function ownEnvironment(context, name) {
448
- return Object.hasOwn(context.env, name) ? context.env[name] : void 0;
449
- }
450
-
451
- // packages/safe-bash-calendar-engine/src/time-env/calendar.ts
452
- var nanosecondsPerSecond = 1000000000n;
453
- var maximumNanoseconds = 8640000000000000000000n;
454
- var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
455
- var weekdayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
456
- function floorDivide(value2, divisor) {
457
- const quotient = value2 / divisor;
458
- return value2 < 0n && value2 % divisor !== 0n ? quotient - 1n : quotient;
459
- }
460
- function boundedInstant(value2) {
461
- if (value2 < -maximumNanoseconds || value2 > maximumNanoseconds) throw new CommandFailure("date is outside the supported range");
462
- return value2;
463
- }
464
- function millisecondsInstant(value2) {
465
- if (!Number.isFinite(value2) || Math.abs(value2) > 864e13) throw new CommandFailure("invalid clock or modification time");
466
- const match = /^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(value2.toString());
467
- const fraction = match[3] ?? "";
468
- const coefficient = BigInt(`${match[2]}${fraction}`) * (match[1] ? -1n : 1n);
469
- const scale = Number(match[4] ?? 0) - fraction.length + 6;
470
- return boundedInstant(scale >= 0 ? coefficient * 10n ** BigInt(scale) : floorDivide(coefficient, 10n ** BigInt(-scale)));
471
- }
472
- function utcMilliseconds(fields) {
473
- const date = /* @__PURE__ */ new Date(0);
474
- date.setUTCFullYear(fields.year, fields.month - 1, fields.day);
475
- date.setUTCHours(fields.hour, fields.minute, fields.second, 0);
476
- const value2 = date.getTime();
477
- if (!Number.isFinite(value2)) throw new CommandFailure("date is outside the supported range");
478
- return value2;
479
- }
480
- function utcFields(milliseconds) {
481
- const date = new Date(milliseconds);
482
- return {
483
- year: date.getUTCFullYear(),
484
- month: date.getUTCMonth() + 1,
485
- day: date.getUTCDate(),
486
- hour: date.getUTCHours(),
487
- minute: date.getUTCMinutes(),
488
- second: date.getUTCSeconds()
489
- };
490
- }
491
- function sameFields(left, right) {
492
- return left.year === right.year && left.month === right.month && left.day === right.day && left.hour === right.hour && left.minute === right.minute && left.second === right.second;
493
- }
494
- function checkCalendar(fields, restrictYear = true) {
495
- if (restrictYear && (fields.year < -9999 || fields.year > 9999) || fields.month < 1 || fields.month > 12 || fields.day < 1 || fields.day > 31 || fields.hour < 0 || fields.hour > 23 || fields.minute < 0 || fields.minute > 59 || fields.second < 0 || fields.second > 59 || !sameFields(fields, utcFields(utcMilliseconds(fields)))) throw new CommandFailure("invalid calendar date or time");
496
- }
497
- function signedOffset(text) {
498
- const match = /^([+-])(\d{2})(?::?(\d{2}))?(?::(\d{2}))?$/.exec(text);
499
- if (!match) throw new CommandFailure(`unsupported UTC offset: ${text}`);
500
- const hours = Number(match[2]), minutes = Number(match[3] ?? 0), seconds = Number(match[4] ?? 0);
501
- if (hours > 23 || minutes > 59 || seconds > 59) throw new CommandFailure(`invalid UTC offset: ${text}`);
502
- return (match[1] === "-" ? -1 : 1) * (hours * 3600 + minutes * 60 + seconds);
503
- }
504
- var TimeZone = class {
505
- fixedOffset;
506
- formatter;
507
- label;
508
- constructor(input2, numericOffset = false) {
509
- const name = input2.startsWith(":") ? input2.slice(1) : input2;
510
- this.label = name.startsWith("GMT") || name === "Etc/GMT" ? "GMT" : "UTC";
511
- if (numericOffset) this.fixedOffset = signedOffset(name);
512
- else if (["", "UTC", "UTC0", "GMT", "GMT0", "Etc/UTC", "Etc/GMT", "Z"].includes(name)) this.fixedOffset = 0;
513
- else {
514
- const fixed = /^(UTC|GMT)([+-])(\d{1,2})(?::(\d{2}))?(?::(\d{2}))?$/.exec(name);
515
- if (fixed) this.fixedOffset = -signedOffset(`${fixed[2]}${fixed[3].padStart(2, "0")}:${fixed[4] ?? "00"}:${fixed[5] ?? "00"}`);
516
- else {
517
- if (!/^[A-Za-z_+-][A-Za-z0-9_+.-]*(?:\/[A-Za-z0-9_+.-]+)*$/.test(name)) throw new CommandFailure(`unsupported virtual TZ: ${input2}`);
518
- try {
519
- this.formatter = new Intl.DateTimeFormat("en-US-u-ca-gregory-nu-latn", {
520
- timeZone: name,
521
- year: "numeric",
522
- month: "2-digit",
523
- day: "2-digit",
524
- hour: "2-digit",
525
- minute: "2-digit",
526
- second: "2-digit",
527
- era: "short",
528
- hourCycle: "h23",
529
- timeZoneName: "short"
530
- });
531
- } catch {
532
- throw new CommandFailure(`unsupported virtual TZ: ${input2}`);
533
- }
534
- }
535
- }
536
- }
537
- fields(instant) {
538
- return this.observedFields(instant, true);
539
- }
540
- observedFields(instant, restrictYear) {
541
- boundedInstant(instant);
542
- const seconds = floorDivide(instant, nanosecondsPerSecond);
543
- const milliseconds = Number(seconds * 1000n);
544
- let fields, offset, zone;
545
- if (this.fixedOffset !== void 0) {
546
- fields = utcFields(milliseconds + this.fixedOffset * 1e3);
547
- offset = this.fixedOffset;
548
- zone = this.label;
549
- } else {
550
- const parts = Object.fromEntries(this.formatter.formatToParts(new Date(milliseconds)).map((part) => [part.type, part.value]));
551
- const year = Number(parts.year);
552
- fields = {
553
- year: parts.era === "BC" ? 1 - year : year,
554
- month: Number(parts.month),
555
- day: Number(parts.day),
556
- hour: Number(parts.hour),
557
- minute: Number(parts.minute),
558
- second: Number(parts.second)
559
- };
560
- offset = (utcMilliseconds(fields) - milliseconds) / 1e3;
561
- zone = parts.timeZoneName;
562
- }
563
- checkCalendar(fields, restrictYear);
564
- return { ...fields, offset, zone };
565
- }
566
- instant(fields, fraction = 0n) {
567
- checkCalendar(fields);
568
- const wall = utcMilliseconds(fields);
569
- if (this.fixedOffset !== void 0) return boundedInstant(BigInt(wall) * 1000000n - BigInt(this.fixedOffset) * nanosecondsPerSecond + fraction);
570
- const offsets = /* @__PURE__ */ new Set();
571
- for (const days of [-2, -1, 0, 1, 2]) offsets.add(this.observedFields(BigInt(wall + days * 864e5) * 1000000n, false).offset);
572
- const candidates = [];
573
- for (const offset of offsets) {
574
- const candidate = BigInt(wall) * 1000000n - BigInt(offset) * nanosecondsPerSecond + fraction;
575
- if (sameFields(this.observedFields(candidate, false), fields)) candidates.push(candidate);
576
- }
577
- if (candidates.length === 0) throw new CommandFailure("nonexistent local time in virtual TZ");
578
- if (candidates.length !== 1) throw new CommandFailure("ambiguous local time; specify an explicit UTC offset");
579
- return boundedInstant(candidates[0]);
580
- }
581
- };
582
- function decimalEpoch(text) {
583
- const match = /^@([+-]?)(\d+)(?:[.,](\d+))?$/.exec(text);
584
- if (!match) return void 0;
585
- if (match[2].replace(/^0+/, "").length > 13) throw new CommandFailure("date is outside the supported range");
586
- const magnitude = BigInt(match[2]) * nanosecondsPerSecond + BigInt((match[3] ?? "").slice(0, 9).padEnd(9, "0"));
587
- return boundedInstant(match[1] === "-" ? -magnitude : magnitude);
588
- }
589
- function parsedZone(text, fallback) {
590
- if (text === void 0) return fallback;
591
- return /^[+-]/.test(text) ? new TimeZone(text, true) : new TimeZone(text.toUpperCase());
592
- }
593
- function parseDate(text, zone, now) {
594
- const value2 = text.trim();
595
- if (value2 === "") {
596
- const fields = zone.fields(now());
597
- return zone.instant({ ...fields, hour: 0, minute: 0, second: 0 }, 0n);
598
- }
599
- const epoch = decimalEpoch(value2);
600
- if (epoch !== void 0) return epoch;
601
- if (value2 === "now") return now();
602
- if (["today", "yesterday", "tomorrow"].includes(value2)) {
603
- const current = now();
604
- if (value2 === "today") return current;
605
- const fields = zone.fields(current);
606
- const changed = utcFields(utcMilliseconds(fields) + (value2 === "yesterday" ? -864e5 : 864e5));
607
- return zone.instant(changed, current - floorDivide(current, nanosecondsPerSecond) * nanosecondsPerSecond);
608
- }
609
- const relative = /^(?:(.*?)\s+)?([+-]?\s*\d+)\s+(seconds?|minutes?|hours?|days?|weeks?|months?|years?)(?:\s+(ago))?$/.exec(value2);
610
- if (relative) {
611
- const rawAmount = relative[2].replace(/\s+/g, "");
612
- if (rawAmount.replace(/^[+-]?0*/, "").length > 13) throw new CommandFailure("relative date is outside the supported range");
613
- const base = relative[1] === void 0 || relative[1] === "now" ? { instant: now(), zone } : parseAbsoluteDate(relative[1], zone);
614
- const amount = BigInt(rawAmount) * (relative[4] ? -1n : 1n);
615
- const unit = relative[3];
616
- if (["second", "minute", "hour"].some((name) => unit.startsWith(name))) {
617
- const scale = unit.startsWith("hour") ? 3600n : unit.startsWith("minute") ? 60n : 1n;
618
- return boundedInstant(base.instant + amount * scale * nanosecondsPerSecond);
619
- }
620
- const fields = base.zone.fields(base.instant);
621
- const changed = unit.startsWith("year") ? { ...fields, year: fields.year + Number(amount) } : unit.startsWith("month") ? { ...fields, month: fields.month + Number(amount) } : { ...fields, day: fields.day + Number(amount) * (unit.startsWith("week") ? 7 : 1) };
622
- const normalized = utcFields(utcMilliseconds(changed));
623
- return base.zone.instant(normalized, base.instant - floorDivide(base.instant, nanosecondsPerSecond) * nanosecondsPerSecond);
624
- }
625
- return parseAbsoluteDate(value2, zone).instant;
626
- }
627
- function parseAbsoluteDate(value2, zone) {
628
- const epoch = decimalEpoch(value2);
629
- if (epoch !== void 0) return { instant: epoch, zone };
630
- const iso = /^(?:(\d{4})-(\d{1,2})-(\d{1,2})|(\d{4})(\d{2})(\d{2}))(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d+))?)?)?(?:\s*(Z|UTC|GMT|[+-]\d{2}(?::?\d{2})?(?::\d{2})?))?$/i.exec(value2);
631
- if (iso) {
632
- const fields = {
633
- year: Number(iso[1] ?? iso[4]),
634
- month: Number(iso[2] ?? iso[5]),
635
- day: Number(iso[3] ?? iso[6]),
636
- hour: Number(iso[7] ?? 0),
637
- minute: Number(iso[8] ?? 0),
638
- second: Number(iso[9] ?? 0)
639
- };
640
- const sourceZone = parsedZone(iso[11], zone);
641
- return { instant: sourceZone.instant(fields, BigInt((iso[10] ?? "").slice(0, 9).padEnd(9, "0"))), zone: sourceZone };
642
- }
643
- const rfc = /^(?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s+)?(\d{1,2})\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+(GMT|UTC|[+-]\d{4})$/.exec(value2);
644
- if (rfc) {
645
- const fields = {
646
- year: Number(rfc[4]),
647
- month: monthNames.findIndex((name) => name.startsWith(rfc[3])) + 1,
648
- day: Number(rfc[2]),
649
- hour: Number(rfc[5]),
650
- minute: Number(rfc[6]),
651
- second: Number(rfc[7])
652
- };
653
- if (rfc[1] && !weekdayNames[new Date(utcMilliseconds(fields)).getUTCDay()].startsWith(rfc[1])) throw new CommandFailure("weekday does not match calendar date");
654
- const sourceZone = parsedZone(rfc[8], zone);
655
- return { instant: sourceZone.instant(fields), zone: sourceZone };
656
- }
657
- throw new CommandFailure(`unsupported or invalid date: ${value2}`);
658
- }
659
-
660
- // packages/safe-bash-io-engine/src/commands/touch-times.ts
661
- function touchTimes(date, timestamp, timezone, base) {
662
- try {
663
- const zone = new TimeZone(timezone);
664
- if (timestamp !== void 0) {
665
- const parts = timestamp.split(".");
666
- const digits = parts[0];
667
- if (parts.length > 2 || ![8, 10, 12].includes(digits.length) || [...digits].some((character) => character < "0" || character > "9") || parts[1] !== void 0 && (parts[1].length !== 2 || [...parts[1]].some((character) => character < "0" || character > "9"))) {
668
- throw new CommandFailure(`invalid date format '${timestamp}'`);
669
- }
670
- const prefix = digits.slice(0, -8);
671
- const year = prefix.length === 4 ? Number(prefix) : prefix.length === 2 ? Number(prefix) + (Number(prefix) >= 69 ? 1900 : 2e3) : zone.fields(millisecondsInstant(base.mtimeMs)).year;
672
- const fields = digits.slice(-8);
673
- const second = Number(parts[1] ?? 0);
674
- const instant = zone.instant({
675
- year,
676
- month: Number(fields.slice(0, 2)),
677
- day: Number(fields.slice(2, 4)),
678
- hour: Number(fields.slice(4, 6)),
679
- minute: Number(fields.slice(6, 8)),
680
- second: second === 60 ? 59 : second
681
- });
682
- const milliseconds = Number(instant / 1000000n) + (second === 60 ? 1e3 : 0);
683
- return { atimeMs: milliseconds, mtimeMs: milliseconds };
684
- }
685
- if (date === void 0) return base;
686
- const access = parseDate(date, zone, () => millisecondsInstant(base.atimeMs));
687
- const modify = parseDate(date, zone, () => millisecondsInstant(base.mtimeMs));
688
- return {
689
- atimeMs: Number(access / 1000000n) + Number(access % 1000000n) / 1e6,
690
- mtimeMs: Number(modify / 1000000n) + Number(modify % 1000000n) / 1e6
691
- };
692
- } catch (error) {
693
- if (error instanceof CommandFailure) throw new PublicDiagnostic(error.message);
694
- throw error;
695
- }
696
- }
697
-
698
- // packages/safe-bash-io-engine/src/internal.ts
699
- var syncResolved = /* @__PURE__ */ Symbol.for("safe-bash.syncResolved");
700
- var sharedSmallOutputBuf = new Uint8Array(64);
701
- var sharedSmallOutputViews = Array.from({ length: 65 }, (_, i) => sharedSmallOutputBuf.subarray(0, i));
702
- var resolvedVoid = Object.defineProperty(
703
- Promise.resolve(),
704
- syncResolved,
705
- { value: true }
706
- );
707
- var RESOLVED_EXIT_ZERO = Object.defineProperty(
708
- Promise.resolve({ exitCode: 0 }),
709
- syncResolved,
710
- { value: true }
711
- );
712
- var RESOLVED_EXIT_ONE = Object.defineProperty(
713
- Promise.resolve({ exitCode: 1 }),
714
- syncResolved,
715
- { value: true }
716
- );
717
- async function handleDefineError(context, error, failureCode, usageFailureCode) {
718
- context.signal.throwIfAborted();
719
- await diagnostic(context, error);
720
- return { exitCode: error instanceof UsageError ? usageFailureCode : failureCode };
721
- }
722
- var encoder2 = new TextEncoder();
723
- var decoder = new TextDecoder();
724
- var bufferLimit = Infinity;
725
- var syncCommandEvaluators = {};
726
- var specificationsCache = /* @__PURE__ */ new Map();
727
- function options(args, short, long = {}, stopAtOperand = false, onOperand, onValue, onOption) {
728
- const flags = /* @__PURE__ */ new Set();
729
- const values = /* @__PURE__ */ new Map();
730
- const operands = [];
731
- let specifications = specificationsCache.get(short);
732
- if (!specifications) {
733
- const built = /* @__PURE__ */ new Map();
734
- for (let index = 0; index < short.length; index++) {
735
- const key = short[index];
736
- built.set(key, short[index + 1] === ":");
737
- if (short[index + 1] === ":") index++;
738
- }
739
- specifications = built;
740
- specificationsCache.set(short, specifications);
741
- }
742
- let ended = false;
743
- for (let index = 0; index < args.length; index++) {
744
- const argument = args[index];
745
- if (ended || argument === "-" || !argument.startsWith("-")) {
746
- operands.push(argument);
747
- onOperand?.(index);
748
- if (stopAtOperand) ended = true;
749
- continue;
750
- }
751
- if (argument === "--") {
752
- ended = true;
753
- continue;
754
- }
755
- if (argument.startsWith("--")) {
756
- const equals = argument.indexOf("=");
757
- const name = argument.slice(2, equals < 0 ? void 0 : equals);
758
- const alias = long[name];
759
- const longValue = typeof alias === "string" && alias.endsWith(":");
760
- const key = alias === false ? name : longValue ? alias.slice(0, -1) : alias;
761
- if (!key || alias !== false && !longValue && !specifications.has(key)) throw new UsageError(`unrecognized option '${argument}'`);
762
- if (longValue || specifications.get(key)) {
763
- const value2 = equals >= 0 ? argument.slice(equals + 1) : args[++index];
764
- if (value2 === void 0) throw new UsageError(`option '--${name}' requires an argument`);
765
- onValue?.(key, index, equals >= 0 ? equals + 1 : 0);
766
- const list = values.get(key);
767
- if (list) list.push(value2);
768
- else values.set(key, [value2]);
769
- } else if (equals >= 0) throw new UsageError(`option '--${name}' does not take an argument`);
770
- flags.add(key);
771
- onOption?.(key, values.get(key)?.at(-1));
772
- continue;
773
- }
774
- for (let offset = 1; offset < argument.length; offset++) {
775
- const key = argument[offset];
776
- if (!specifications.has(key)) throw new UsageError(`invalid option -- '${key}'`);
777
- if (specifications.get(key)) {
778
- const value2 = argument.slice(offset + 1) || args[++index];
779
- if (value2 === void 0) throw new UsageError(`option requires an argument -- '${key}'`);
780
- onValue?.(key, index, offset + 1 < argument.length ? offset + 1 : 0);
781
- const list = values.get(key);
782
- if (list) list.push(value2);
783
- else values.set(key, [value2]);
784
- offset = argument.length;
785
- }
786
- flags.add(key);
787
- onOption?.(key, values.get(key)?.at(-1));
788
- }
789
- }
790
- return { flags, values, operands };
791
- }
792
- function value(parsed, key) {
793
- return parsed.values.get(key)?.at(-1);
794
- }
795
- function integer(text, minimum = 0) {
796
- if (!/^[+]?[0-9]+$/u.test(text)) throw new UsageError(`invalid number '${text}'`);
797
- const number = Number(text);
798
- if (!Number.isSafeInteger(number) || number < minimum) throw new UsageError(`invalid number '${text}'`);
799
- return number;
800
- }
801
- function requireOperands(operands, minimum = 1, maximum = Infinity) {
802
- if (operands.length < minimum) throw new UsageError("missing operand");
803
- if (operands.length > maximum) throw new UsageError(`extra operand '${operands[maximum]}'`);
804
- }
805
- function codeOf(error) {
806
- return error instanceof Error && "code" in error ? String(error.code) : void 0;
807
- }
808
- var EXIT_ZERO_RESULT = { exitCode: 0 };
809
- var EXIT_ONE_RESULT = { exitCode: 1 };
810
- var EXIT_TWO_RESULT = { exitCode: 2 };
811
- var RETURN_EXIT_ZERO = () => EXIT_ZERO_RESULT;
812
- var RETURN_EXIT_ONE = () => EXIT_ONE_RESULT;
813
- var RETURN_EXIT_TWO = () => EXIT_TWO_RESULT;
814
- function outputRange(context, src, len) {
815
- context.signal.throwIfAborted();
816
- const stdout = context.stdout;
817
- if (!stdout.isPipeStage) {
818
- if (typeof stdout.writeRangeSync === "function" && stdout.writeRangeSync(src, len) !== false) {
819
- return resolvedVoid;
820
- }
821
- if (typeof stdout.writeSync === "function" && stdout.writeSync(src.subarray(0, len)) !== false) {
822
- return resolvedVoid;
823
- }
824
- }
825
- return writeBytes3(context.stdout, stdout.isPipeStage ? src.subarray(0, len) : src.slice(0, len), context.signal);
826
- }
827
- function output(context, text) {
828
- context.signal.throwIfAborted();
829
- const stdout = context.stdout;
830
- if (typeof text === "string" && !stdout.isPipeStage) {
831
- const len = text.length;
832
- if (len <= 64 && (typeof stdout.writeRangeSync === "function" || typeof stdout.writeSync === "function")) {
833
- let ascii = true;
834
- for (let i = 0; i < len; i++) {
835
- const code = text.charCodeAt(i);
836
- if (code >= 128) {
837
- ascii = false;
838
- break;
839
- }
840
- sharedSmallOutputBuf[i] = code;
841
- }
842
- if (ascii) {
843
- const ok = typeof stdout.writeRangeSync === "function" ? stdout.writeRangeSync(sharedSmallOutputBuf, len) : stdout.writeSync(sharedSmallOutputViews[len]);
844
- if (ok !== false) return resolvedVoid;
845
- }
846
- }
847
- }
848
- const bytes = typeof text === "string" ? encoder2.encode(text) : text;
849
- if (!stdout.isPipeStage && typeof stdout.writeSync === "function" && stdout.writeSync(bytes) !== false) {
850
- return resolvedVoid;
851
- }
852
- return writeBytes3(context.stdout, bytes, context.signal);
853
- }
854
- async function diagnostic(context, error) {
855
- context.signal.throwIfAborted();
856
- await writeDiagnostic2(context.stderr, `${context.command}: ${publicDiagnosticMessage(error, context.onInternalError)}
857
- `, context.signal);
858
- }
859
- function finishDefineInfoAsync(infoPromise, handler, context, failureCode, usageFailureCode) {
860
- return infoPromise.then(
861
- (info) => info ?? handler(context)
862
- ).catch((error) => handleDefineError(context, error, failureCode, usageFailureCode));
863
- }
864
- function finishDefineResAsync(res, context, failureCode, usageFailureCode) {
865
- return Promise.resolve(res).catch((error) => handleDefineError(context, error, failureCode, usageFailureCode));
866
- }
867
- function define(name, handler, failureCode = 1, usageFailureCode = 2) {
868
- const definition = {
869
- name,
870
- execute(context) {
871
- try {
872
- context.signal.throwIfAborted();
873
- const infoPromise = gnuInformation(name, context);
874
- if (infoPromise) {
875
- return finishDefineInfoAsync(infoPromise, handler, context, failureCode, usageFailureCode);
876
- }
877
- const res = handler(context);
878
- if (res === RESOLVED_EXIT_ZERO || res === RESOLVED_EXIT_ONE || Boolean(res && typeof res === "object" && res[syncResolved])) {
879
- return res;
880
- }
881
- return finishDefineResAsync(res, context, failureCode, usageFailureCode);
882
- } catch (error) {
883
- return handleDefineError(context, error, failureCode, usageFailureCode);
884
- }
885
- }
886
- };
887
- builtInDirectContextExecutors.add(definition.execute);
888
- return definition;
889
- }
890
- async function eachOperand(context, operands, operation) {
891
- let exitCode = 0;
892
- for (const operand of operands) {
893
- context.signal.throwIfAborted();
894
- try {
895
- await operation(operand);
896
- } catch (error) {
897
- await diagnostic(context, error);
898
- exitCode = 1;
899
- }
900
- }
901
- return { exitCode };
902
- }
903
- function input(context, name = "-") {
904
- if (name === "-") {
905
- if (!context.signal.aborted && context.stdin.abortSignal === context.signal) {
906
- return context.stdin;
907
- }
908
- return readBytes(context.stdin, context.signal);
909
- }
910
- const backing = getRuntimeBackingFileSystem(context.fs);
911
- if (!context.signal.aborted && backing !== void 0 && backing.capabilitiesFor === void 0 && context.fs.readStream && context.fs.capabilities.streamingRead !== false && context.fs.capabilities.read !== false && Object.getPrototypeOf(backing)?.constructor?.name === "MemoryFileSystem" && !Object.prototype.hasOwnProperty.call(backing, "readStream")) {
912
- const resolvedPath = (0, path_exports.pathOf)(context, name);
913
- if (resolvedPath !== "/dev" && !resolvedPath.startsWith("/dev/")) {
914
- return context.fs.readStream(resolvedPath, { signal: context.signal });
915
- }
916
- }
917
- return inputFileSlow(context, name);
918
- }
919
- function inputFileSlow(context, name) {
920
- return readBytes({ [Symbol.asyncIterator]() {
921
- context.signal.throwIfAborted();
922
- const resolvedPath = (0, path_exports.pathOf)(context, name);
923
- const backing = getRuntimeBackingFileSystem(context.fs);
924
- const skipCapsFor = !context.fs.capabilitiesFor || backing?.capabilitiesFor === void 0 && resolvedPath !== "/dev" && !resolvedPath.startsWith("/dev/");
925
- if (skipCapsFor && context.fs.readStream && context.fs.capabilities.streamingRead !== false) {
926
- assertCommandRequirements(context, inputRequirements, FILE_REQUIREMENT_MODES);
927
- if (backing !== void 0 && backing.capabilitiesFor === void 0 && Object.getPrototypeOf(backing)?.constructor?.name === "MemoryFileSystem" && !Object.prototype.hasOwnProperty.call(backing, "readStream")) {
928
- return context.fs.readStream(resolvedPath, { signal: context.signal })[Symbol.asyncIterator]();
929
- }
930
- let iterator;
931
- let closing;
932
- let finished = false;
933
- let readFailure;
934
- const close = () => closing ??= Promise.resolve().then(async () => {
935
- if (!finished) {
936
- finished = true;
937
- try {
938
- await iterator?.return?.();
939
- } catch (error) {
940
- if (context.signal.aborted && Object.is(error, context.signal.reason)) return;
941
- if (!readFailure || !Object.is(error, readFailure.reason)) throw error;
942
- }
943
- }
944
- });
945
- context.registerCleanup?.(close);
946
- try {
947
- context.signal.throwIfAborted();
948
- iterator = context.fs.readStream(resolvedPath, { signal: context.signal })[Symbol.asyncIterator]();
949
- if (context.signal.aborted) {
950
- void close().catch(() => {
951
- });
952
- context.signal.throwIfAborted();
953
- }
954
- } catch (error) {
955
- return fileInputSource(context, name, { [Symbol.asyncIterator]: () => ({ async next() {
956
- throw error;
957
- } }) });
958
- }
959
- const source = { [Symbol.asyncIterator]: () => ({
960
- tryNextSync() {
961
- if (finished || closing) return { done: true, value: void 0 };
962
- try {
963
- const result = iterator.tryNextSync?.();
964
- if (result?.done) finished = true;
965
- return result;
966
- } catch (reason) {
967
- readFailure = { reason };
968
- throw reason;
969
- }
970
- },
971
- async next() {
972
- if (finished || closing) return { done: true, value: void 0 };
973
- try {
974
- const result = await iterator.next();
975
- if (result.done) finished = true;
976
- return result;
977
- } catch (reason) {
978
- readFailure = { reason };
979
- throw reason;
980
- }
981
- },
982
- async return() {
983
- await close();
984
- return { done: true, value: void 0 };
985
- }
986
- }) };
987
- const reader = readBytes(source, context.signal);
988
- let fallback;
989
- let emitted = false;
990
- return {
991
- abortSignal: context.signal,
992
- tryNextSync() {
993
- if (fallback) return void 0;
994
- const result = reader.tryNextSync();
995
- if (result && !result.done && result.value.byteLength) emitted = true;
996
- return result;
997
- },
998
- async next() {
999
- if (fallback) return fallback.next();
1000
- try {
1001
- const result = await reader.next();
1002
- if (!result.done && result.value.byteLength) emitted = true;
1003
- return result;
1004
- } catch (error) {
1005
- context.signal.throwIfAborted();
1006
- if (emitted || !(error instanceof FsError3) || error.code !== "ENOTSUP") throw error;
1007
- fallback = fileInputSource(context, name, false);
1008
- return fallback.next();
1009
- }
1010
- },
1011
- return: (value2) => (fallback ?? reader).return(value2),
1012
- throw: (error) => (fallback ?? reader).throw(error)
1013
- };
1014
- }
1015
- return fileInputSource(context, name);
1016
- } }, context.signal);
1017
- }
1018
- async function* fileInputSource(context, name, stream) {
1019
- context.signal.throwIfAborted();
1020
- await assertInputRequirements(context, [name]);
1021
- const path = (0, path_exports.pathOf)(context, name);
1022
- const capabilities = await context.fs.capabilitiesFor?.(path, { signal: context.signal }) ?? context.fs.capabilities;
1023
- if (stream !== false && context.fs.readStream && capabilities.streamingRead !== false) {
1024
- let emitted = false;
1025
- let reading = true;
1026
- try {
1027
- for await (const chunk of readBytes(stream ?? context.fs.readStream(path, { signal: context.signal }), context.signal)) {
1028
- reading = false;
1029
- if (chunk.byteLength) emitted = true;
1030
- yield chunk;
1031
- reading = true;
1032
- }
1033
- return;
1034
- } catch (error) {
1035
- context.signal.throwIfAborted();
1036
- if (!reading || emitted || !(error instanceof FsError3) || error.code !== "ENOTSUP") throw error;
1037
- }
1038
- }
1039
- if (capabilities.read === false) throw new FsError3("ENOTSUP", { syscall: "readFile", path });
1040
- yield* readBytes({
1041
- async *[Symbol.asyncIterator]() {
1042
- const bytes = await context.fs.readFile(path, { signal: context.signal });
1043
- context.signal.throwIfAborted();
1044
- if (bytes.byteLength > bufferLimit) throw new FsError3("EFBIG", { syscall: "readFile", path });
1045
- yield bytes;
1046
- }
1047
- }, context.signal);
1048
- }
1049
- var FILE_REQUIREMENT_MODES = ["file"];
1050
- var STDIN_REQUIREMENT_MODES = ["stdin"];
1051
- function assertInputRequirements(context, names) {
1052
- let hasFile = false;
1053
- for (let i = 0; i < names.length; i++) {
1054
- if (names[i] !== "-") {
1055
- hasFile = true;
1056
- break;
1057
- }
1058
- }
1059
- assertCommandRequirements(context, inputRequirements, hasFile ? FILE_REQUIREMENT_MODES : STDIN_REQUIREMENT_MODES);
1060
- if (!hasFile || !context.fs.capabilitiesFor) return;
1061
- if (getRuntimeBackingFileSystem(context.fs)?.capabilitiesFor === void 0) {
1062
- let hasDev = false;
1063
- for (let i = 0; i < names.length; i++) {
1064
- const name = names[i];
1065
- if (name === "-") continue;
1066
- const p = (0, path_exports.pathOf)(context, name);
1067
- if (p === "/dev" || p.startsWith("/dev/")) {
1068
- hasDev = true;
1069
- break;
1070
- }
1071
- }
1072
- if (!hasDev) return;
1073
- }
1074
- return assertInputRequirementsAsync(context, names);
1075
- }
1076
- async function assertInputRequirementsAsync(context, names) {
1077
- if (!context.fs.capabilitiesFor) return;
1078
- for (const name of names) {
1079
- if (name === "-") continue;
1080
- try {
1081
- const capabilities = await context.fs.capabilitiesFor((0, path_exports.pathOf)(context, name), { signal: context.signal });
1082
- assertCommandRequirements(context, inputRequirements, ["file"], capabilities);
1083
- } catch (error) {
1084
- context.signal.throwIfAborted();
1085
- if (codeOf(error) === "ENOTSUP" || codeOf(error) === "EROFS") throw error;
1086
- }
1087
- }
1088
- }
1089
- function concatenate(chunks, size = chunks.reduce((sum, chunk) => sum + chunk.length, 0)) {
1090
- const result = new Uint8Array(size);
1091
- let offset = 0;
1092
- for (const chunk of chunks) {
1093
- result.set(chunk, offset);
1094
- offset += chunk.length;
1095
- }
1096
- return result;
1097
- }
1098
- async function* lines(source, separator = 10, admit) {
1099
- const pending = new RecordBuffer(bufferLimit);
1100
- try {
1101
- for await (const chunk of source) {
1102
- let start = 0;
1103
- while (start < chunk.length) {
1104
- const offset = chunk.indexOf(separator, start);
1105
- if (offset < 0) break;
1106
- yield { bytes: pending.finish(admit, chunk, start, offset), terminated: true };
1107
- start = offset + 1;
1108
- }
1109
- pending.append(chunk, start);
1110
- }
1111
- if (pending.size) yield { bytes: pending.finish(admit), terminated: false };
1112
- } finally {
1113
- pending.clear();
1114
- }
1115
- }
1116
- function emptyInput() {
1117
- return toByteSource("");
1118
- }
1119
- function replaceArgument(source, pattern, replacement) {
1120
- if (typeof source === "string") return source.split(pattern).join(replacement);
1121
- const needle = encoder2.encode(pattern);
1122
- if (!needle.length) throw new UsageError("replacement string cannot be empty");
1123
- const substituted = encoder2.encode(replacement);
1124
- const chunks = [];
1125
- let start = 0;
1126
- for (let offset = 0; offset <= source.length - needle.length; ) {
1127
- if (needle.every((byte, index) => source[offset + index] === byte)) {
1128
- chunks.push(source.subarray(start, offset), substituted);
1129
- offset += needle.length;
1130
- start = offset;
1131
- } else offset++;
1132
- }
1133
- chunks.push(source.subarray(start));
1134
- return concatenate(chunks);
1135
- }
1136
- function escapeBytes(text, zeroOctal = false, bareOctal = false, unicode) {
1137
- if (unicode && typeof text === "string") text = encoder2.encode(text);
1138
- if (typeof text === "string") {
1139
- const chunks = [];
1140
- const control2 = { a: 7, b: 8, e: 27, E: 27, f: 12, n: 10, r: 13, t: 9, v: 11, "\\": 92 };
1141
- for (let index = 0; index < text.length; ) {
1142
- if (text[index] !== "\\" || index + 1 === text.length) {
1143
- const character = String.fromCodePoint(text.codePointAt(index));
1144
- chunks.push(encoder2.encode(character));
1145
- index += character.length;
1146
- continue;
1147
- }
1148
- const next = text[index + 1];
1149
- if (next === "c") return { bytes: concatenate(chunks), stop: true };
1150
- if (control2[next] !== void 0) {
1151
- chunks.push(Uint8Array.of(control2[next]));
1152
- index += 2;
1153
- continue;
1154
- }
1155
- const rest = text.slice(index + 1);
1156
- const octal = zeroOctal ? (bareOctal ? /^(?:0([0-7]{0,3})|([1-7][0-7]{0,2}))/u : /^0([0-7]{0,3})/u).exec(rest) : /^([0-7]{1,3})/u.exec(rest);
1157
- if (octal) {
1158
- chunks.push(Uint8Array.of(parseInt(octal[1] || octal[2] || "0", 8) & 255));
1159
- index += 1 + octal[0].length;
1160
- continue;
1161
- }
1162
- const hexadecimal = /^x([0-9a-fA-F]{1,2})/u.exec(rest);
1163
- if (hexadecimal) {
1164
- chunks.push(Uint8Array.of(parseInt(hexadecimal[1], 16)));
1165
- index += 1 + hexadecimal[0].length;
1166
- continue;
1167
- }
1168
- chunks.push(encoder2.encode(`\\${next}`));
1169
- index += 2;
1170
- }
1171
- return { bytes: concatenate(chunks), stop: false };
1172
- }
1173
- const source = text;
1174
- const bytes = new Uint8Array(source.length * (unicode && !unicode.utf8 ? 3 : 1));
1175
- const control = { 97: 7, 98: 8, 101: 27, 69: 27, 102: 12, 110: 10, 114: 13, 116: 9, 118: 11, 92: 92 };
1176
- let size = 0;
1177
- for (let index = 0; index < source.length; ) {
1178
- if (source[index] !== 92 || index + 1 === source.length) {
1179
- bytes[size++] = source[index++];
1180
- continue;
1181
- }
1182
- const next = source[index + 1];
1183
- if (next === 99) return { bytes: bytes.subarray(0, size), stop: true };
1184
- if (control[next] !== void 0) {
1185
- bytes[size++] = control[next];
1186
- index += 2;
1187
- continue;
1188
- }
1189
- if (zeroOctal ? next === 48 || bareOctal && next >= 49 && next <= 55 : next >= 48 && next <= 55) {
1190
- let offset = index + (zeroOctal && next === 48 ? 2 : 1);
1191
- const end = Math.min(source.length, offset + 3);
1192
- let value2 = 0;
1193
- while (offset < end && source[offset] >= 48 && source[offset] <= 55) value2 = value2 * 8 + source[offset++] - 48;
1194
- bytes[size++] = value2 & 255;
1195
- index = offset;
1196
- continue;
1197
- }
1198
- if (unicode && (next === 117 || next === 85)) {
1199
- const digits = next === 117 ? 4 : 8;
1200
- let offset = index + 2;
1201
- const end = Math.min(source.length, offset + digits);
1202
- let value2 = 0;
1203
- while (offset < end) {
1204
- const digit = source[offset];
1205
- const number = digit >= 48 && digit <= 57 ? digit - 48 : digit >= 65 && digit <= 70 ? digit - 55 : digit >= 97 && digit <= 102 ? digit - 87 : -1;
1206
- if (number < 0) break;
1207
- value2 = value2 * 16 + number;
1208
- offset++;
1209
- }
1210
- if (offset === index + 2) unicode.missingDigit(String.fromCharCode(next));
1211
- else {
1212
- if (value2 < 2147483648) {
1213
- if (!unicode.utf8 && value2 > 127) {
1214
- const literal = encoder2.encode(`\\${value2 <= 65535 ? "u" : "U"}${value2.toString(16).toUpperCase().padStart(value2 <= 65535 ? 4 : 8, "0")}`);
1215
- bytes.set(literal, size);
1216
- size += literal.length;
1217
- } else if (value2 < 128) bytes[size++] = value2;
1218
- else {
1219
- const length = value2 < 2048 ? 2 : value2 < 65536 ? 3 : value2 < 2097152 ? 4 : value2 < 67108864 ? 5 : 6;
1220
- for (let position = length - 1; position > 0; position--) {
1221
- bytes[size + position] = 128 | value2 & 63;
1222
- value2 = Math.floor(value2 / 64);
1223
- }
1224
- bytes[size] = 255 << 8 - length & 255 | value2;
1225
- size += length;
1226
- }
1227
- }
1228
- index = offset;
1229
- continue;
1230
- }
1231
- }
1232
- if (next === 120) {
1233
- let offset = index + 2;
1234
- const end = Math.min(source.length, offset + 2);
1235
- let value2 = 0;
1236
- while (offset < end) {
1237
- const digit = source[offset];
1238
- const number = digit >= 48 && digit <= 57 ? digit - 48 : digit >= 65 && digit <= 70 ? digit - 55 : digit >= 97 && digit <= 102 ? digit - 87 : -1;
1239
- if (number < 0) break;
1240
- value2 = value2 * 16 + number;
1241
- offset++;
1242
- }
1243
- if (offset > index + 2) {
1244
- bytes[size++] = value2;
1245
- index = offset;
1246
- continue;
1247
- }
1248
- unicode?.missingDigit("x");
1249
- }
1250
- bytes[size++] = 92;
1251
- bytes[size++] = next;
1252
- index += 2;
1253
- }
1254
- return { bytes: bytes.subarray(0, size), stop: false };
1255
- }
1256
- function evalSyncTee(inBytes, opArgs, writeFileSync) {
1257
- const gnuInfo = gnuInformationSync("tee", opArgs);
1258
- if (gnuInfo !== void 0) return gnuInfo;
1259
- let append = false;
1260
- let ended = false;
1261
- const operands = [];
1262
- for (let i = 0; i < opArgs.length; i++) {
1263
- const a = opArgs[i];
1264
- if (ended || !a.startsWith("-") || a === "-") {
1265
- if (a === "-") return void 0;
1266
- operands.push(a);
1267
- continue;
1268
- }
1269
- if (a === "--") {
1270
- ended = true;
1271
- continue;
1272
- }
1273
- if (a === "-a" || a === "--append") {
1274
- append = true;
1275
- continue;
1276
- }
1277
- if (a === "-i" || a === "--ignore-interrupts" || a === "-p" || a === "--output-error" || a === "--output-error=warn" || a === "--output-error=warn-nopipe") continue;
1278
- if (a.startsWith("-") && !a.startsWith("--")) {
1279
- for (let j = 1; j < a.length; j++) {
1280
- const ch = a[j];
1281
- if (ch === "a") append = true;
1282
- else if (ch === "i" || ch === "p") continue;
1283
- else return void 0;
1284
- }
1285
- continue;
1286
- }
1287
- return void 0;
1288
- }
1289
- const data = inBytes ?? new Uint8Array(0);
1290
- if (data.includes(0)) return void 0;
1291
- for (const op of operands) {
1292
- if (!writeFileSync || !writeFileSync(op, data, append)) return void 0;
1293
- }
1294
- return decoder.decode(data);
1295
- }
1296
- function evalSyncTouch(opArgs, statTypeSync, readFileSync, writeFileSync, utimesNodeSync, tz = "UTC") {
1297
- const gnuInfo = gnuInformationSync("touch", opArgs);
1298
- if (gnuInfo !== void 0) return gnuInfo;
1299
- let noCreate = false;
1300
- let flagA = false;
1301
- let flagM = false;
1302
- let dateStr;
1303
- let stampStr;
1304
- let refPath;
1305
- let ended = false;
1306
- const operands = [];
1307
- for (let i = 0; i < opArgs.length; i++) {
1308
- const a = opArgs[i];
1309
- if (ended || !a.startsWith("-") || a === "-") {
1310
- if (a === "-") return void 0;
1311
- operands.push(a);
1312
- continue;
1313
- }
1314
- if (a === "--") {
1315
- ended = true;
1316
- continue;
1317
- }
1318
- if (a === "-c" || a === "--no-create") {
1319
- noCreate = true;
1320
- continue;
1321
- }
1322
- if (a === "-a") {
1323
- flagA = true;
1324
- continue;
1325
- }
1326
- if (a === "-m") {
1327
- flagM = true;
1328
- continue;
1329
- }
1330
- if (a === "-f" || a === "-h" || a === "--no-dereference") continue;
1331
- if (a === "-d" || a === "--date" || a.startsWith("--date=")) {
1332
- const val = a.startsWith("--date=") ? a.slice(7) : opArgs[++i];
1333
- if (val === void 0) return void 0;
1334
- dateStr = val;
1335
- continue;
1336
- }
1337
- if (a === "-t") {
1338
- const val = opArgs[++i];
1339
- if (!val) return void 0;
1340
- stampStr = val;
1341
- continue;
1342
- }
1343
- if (a === "-r" || a === "--reference" || a.startsWith("--reference=")) {
1344
- const val = a.startsWith("--reference=") ? a.slice(12) : opArgs[++i];
1345
- if (!val) return void 0;
1346
- refPath = val;
1347
- continue;
1348
- }
1349
- if (a === "--time" || a.startsWith("--time=")) {
1350
- const val = a.startsWith("--time=") ? a.slice(7) : opArgs[++i];
1351
- if (val === "atime" || val === "access" || val === "use") {
1352
- flagA = true;
1353
- continue;
1354
- }
1355
- if (val === "mtime" || val === "modify") {
1356
- flagM = true;
1357
- continue;
1358
- }
1359
- return void 0;
1360
- }
1361
- if (a.startsWith("-") && !a.startsWith("--")) {
1362
- for (let j = 1; j < a.length; j++) {
1363
- const ch = a[j];
1364
- if (ch === "c") noCreate = true;
1365
- else if (ch === "a") flagA = true;
1366
- else if (ch === "m") flagM = true;
1367
- else if (ch === "f" || ch === "h") continue;
1368
- else if (ch === "d" || ch === "t" || ch === "r") {
1369
- const rest = a.slice(j + 1) || opArgs[++i];
1370
- if (rest === void 0) return void 0;
1371
- if (ch === "d") dateStr = rest;
1372
- else if (ch === "t") stampStr = rest;
1373
- else refPath = rest;
1374
- break;
1375
- } else return void 0;
1376
- }
1377
- continue;
1378
- }
1379
- return void 0;
1380
- }
1381
- if (operands.length === 0 || !statTypeSync || !readFileSync || !writeFileSync) return void 0;
1382
- if ((stampStr !== void 0 ? 1 : 0) + (refPath !== void 0 ? 1 : 0) > 1) return void 0;
1383
- if (stampStr !== void 0 && dateStr !== void 0) return void 0;
1384
- let refTimes;
1385
- if (refPath !== void 0) {
1386
- if (!utimesNodeSync || !utimesNodeSync(refPath, (st) => {
1387
- refTimes = { atimeMs: st.atimeMs, mtimeMs: st.mtimeMs };
1388
- return {};
1389
- }) || !refTimes) {
1390
- return void 0;
1391
- }
1392
- }
1393
- const updateAccess = flagA || !flagM;
1394
- const updateModify = flagM || !flagA;
1395
- let parsedTimes;
1396
- try {
1397
- if (dateStr !== void 0 || stampStr !== void 0 || refTimes !== void 0) {
1398
- if (!utimesNodeSync) return void 0;
1399
- const base = refTimes ?? { atimeMs: Date.now(), mtimeMs: Date.now() };
1400
- parsedTimes = touchTimes(dateStr, stampStr, tz, base);
1401
- }
1402
- } catch {
1403
- return void 0;
1404
- }
1405
- for (const f of operands) {
1406
- const st = statTypeSync(f);
1407
- if (st === "missing") {
1408
- if (noCreate) continue;
1409
- if (!writeFileSync(f, new Uint8Array(0), false)) return void 0;
1410
- if (utimesNodeSync && parsedTimes) {
1411
- if (!utimesNodeSync(f, () => ({
1412
- ...updateAccess ? { atimeMs: parsedTimes.atimeMs } : {},
1413
- ...updateModify ? { mtimeMs: parsedTimes.mtimeMs } : {}
1414
- }))) return void 0;
1415
- }
1416
- } else if (st === "file" || st === "directory") {
1417
- if (utimesNodeSync) {
1418
- const now = Date.now();
1419
- const target = parsedTimes ?? { atimeMs: now, mtimeMs: now };
1420
- if (!utimesNodeSync(f, () => ({
1421
- ...updateAccess ? { atimeMs: target.atimeMs } : {},
1422
- ...updateModify ? { mtimeMs: target.mtimeMs } : {}
1423
- }))) return void 0;
1424
- } else if (st === "file") {
1425
- const cur = readFileSync(f);
1426
- if (!cur || !writeFileSync(f, cur, false)) return void 0;
1427
- } else {
1428
- return void 0;
1429
- }
1430
- } else {
1431
- return void 0;
1432
- }
1433
- }
1434
- return "";
1435
- }
1436
- function evalSyncCp(opArgs, statTypeSync, readFileSync, writeFileSync, statModeSync, umask = 18) {
1437
- const gnuInfo = gnuInformationSync("cp", opArgs);
1438
- if (gnuInfo !== void 0) return gnuInfo;
1439
- let verbose = false;
1440
- let noTargetDir = false;
1441
- let noClobber = false;
1442
- let preserve = false;
1443
- let targetDir;
1444
- let ended = false;
1445
- const operands = [];
1446
- for (let i = 0; i < opArgs.length; i++) {
1447
- const a = opArgs[i];
1448
- if (ended || !a.startsWith("-") || a === "-") {
1449
- operands.push(a);
1450
- continue;
1451
- }
1452
- if (a === "--") {
1453
- ended = true;
1454
- continue;
1455
- }
1456
- if (a === "-v" || a === "--verbose") {
1457
- verbose = true;
1458
- continue;
1459
- }
1460
- if (a === "-f" || a === "--force") continue;
1461
- if (a === "-n" || a === "--no-clobber") {
1462
- noClobber = true;
1463
- continue;
1464
- }
1465
- if (a === "-p" || a === "--preserve") {
1466
- preserve = true;
1467
- continue;
1468
- }
1469
- if (a === "-T" || a === "--no-target-directory") {
1470
- noTargetDir = true;
1471
- continue;
1472
- }
1473
- if (a === "-t" || a === "--target-directory" || a.startsWith("--target-directory=")) {
1474
- const td = a.startsWith("--target-directory=") ? a.slice(19) : opArgs[++i];
1475
- if (!td) return void 0;
1476
- targetDir = td;
1477
- continue;
1478
- }
1479
- if (a.startsWith("-") && !a.startsWith("--")) {
1480
- for (let j = 1; j < a.length; j++) {
1481
- const ch = a[j];
1482
- if (ch === "v") verbose = true;
1483
- else if (ch === "f") continue;
1484
- else if (ch === "n") noClobber = true;
1485
- else if (ch === "p") preserve = true;
1486
- else if (ch === "T") noTargetDir = true;
1487
- else if (ch === "t") {
1488
- const rest = a.slice(j + 1) || opArgs[++i];
1489
- if (!rest) return void 0;
1490
- targetDir = rest;
1491
- break;
1492
- } else return void 0;
1493
- }
1494
- continue;
1495
- }
1496
- return void 0;
1497
- }
1498
- if (!statTypeSync || !readFileSync || !writeFileSync || noTargetDir && targetDir !== void 0) return void 0;
1499
- let sources;
1500
- let destBase;
1501
- let intoDir = false;
1502
- if (targetDir !== void 0) {
1503
- if (operands.length === 0 || statTypeSync(targetDir) !== "directory") return void 0;
1504
- sources = operands;
1505
- destBase = targetDir;
1506
- intoDir = true;
1507
- } else {
1508
- if (operands.length < 2) return void 0;
1509
- destBase = operands[operands.length - 1];
1510
- sources = operands.slice(0, -1);
1511
- const dstSt = statTypeSync(destBase);
1512
- if (dstSt === "directory") {
1513
- if (noTargetDir) return void 0;
1514
- intoDir = true;
1515
- } else if (operands.length > 2) {
1516
- return void 0;
1517
- }
1518
- }
1519
- let out = "";
1520
- for (const src of sources) {
1521
- if (statTypeSync(src) !== "file") return void 0;
1522
- let dst = destBase;
1523
- if (intoDir) {
1524
- const base = src.replace(/\/+$/, "").split("/").pop() || "";
1525
- if (!base) return void 0;
1526
- dst = `${destBase.replace(/\/+$/, "")}/${base}`;
1527
- }
1528
- if (src === dst) return void 0;
1529
- const finalSt = statTypeSync(dst);
1530
- if (finalSt !== "missing" && finalSt !== "file") return void 0;
1531
- if (finalSt === "file" && noClobber) continue;
1532
- const srcMode = statModeSync ? statModeSync(src) : void 0;
1533
- const createMode = preserve ? (srcMode ?? 438) & 511 : (srcMode ?? 438) & 511 & ~umask;
1534
- const bytes = readFileSync(src);
1535
- if (!bytes || !writeFileSync(dst, bytes, false, createMode)) return void 0;
1536
- if (verbose) out += `'${src}' -> '${dst}'
1537
- `;
1538
- }
1539
- return out;
1540
- }
1541
- function evalSyncMv(opArgs, statTypeSync, readFileSync, writeFileSync, rmSync, statModeSync) {
1542
- const gnuInfo = gnuInformationSync("mv", opArgs);
1543
- if (gnuInfo !== void 0) return gnuInfo;
1544
- let verbose = false;
1545
- let noTargetDir = false;
1546
- let noClobber = false;
1547
- let targetDir;
1548
- let ended = false;
1549
- const operands = [];
1550
- for (let i = 0; i < opArgs.length; i++) {
1551
- const a = opArgs[i];
1552
- if (ended || !a.startsWith("-") || a === "-") {
1553
- operands.push(a);
1554
- continue;
1555
- }
1556
- if (a === "--") {
1557
- ended = true;
1558
- continue;
1559
- }
1560
- if (a === "-v" || a === "--verbose") {
1561
- verbose = true;
1562
- continue;
1563
- }
1564
- if (a === "-f" || a === "--force") continue;
1565
- if (a === "-n" || a === "--no-clobber") {
1566
- noClobber = true;
1567
- continue;
1568
- }
1569
- if (a === "-T" || a === "--no-target-directory") {
1570
- noTargetDir = true;
1571
- continue;
1572
- }
1573
- if (a === "-t" || a === "--target-directory" || a.startsWith("--target-directory=")) {
1574
- const td = a.startsWith("--target-directory=") ? a.slice(19) : opArgs[++i];
1575
- if (!td) return void 0;
1576
- targetDir = td;
1577
- continue;
1578
- }
1579
- if (a.startsWith("-") && !a.startsWith("--")) {
1580
- for (let j = 1; j < a.length; j++) {
1581
- const ch = a[j];
1582
- if (ch === "v") verbose = true;
1583
- else if (ch === "f") continue;
1584
- else if (ch === "n") noClobber = true;
1585
- else if (ch === "T") noTargetDir = true;
1586
- else if (ch === "t") {
1587
- const rest = a.slice(j + 1) || opArgs[++i];
1588
- if (!rest) return void 0;
1589
- targetDir = rest;
1590
- break;
1591
- } else return void 0;
1592
- }
1593
- continue;
1594
- }
1595
- return void 0;
1596
- }
1597
- if (!statTypeSync || !readFileSync || !writeFileSync || !rmSync || noTargetDir && targetDir !== void 0) return void 0;
1598
- let sources;
1599
- let destBase;
1600
- let intoDir = false;
1601
- if (targetDir !== void 0) {
1602
- if (operands.length === 0 || statTypeSync(targetDir) !== "directory") return void 0;
1603
- sources = operands;
1604
- destBase = targetDir;
1605
- intoDir = true;
1606
- } else {
1607
- if (operands.length < 2) return void 0;
1608
- destBase = operands[operands.length - 1];
1609
- sources = operands.slice(0, -1);
1610
- const dstSt = statTypeSync(destBase);
1611
- if (dstSt === "directory") {
1612
- if (noTargetDir) return void 0;
1613
- intoDir = true;
1614
- } else if (operands.length > 2) {
1615
- return void 0;
1616
- }
1617
- }
1618
- let out = "";
1619
- for (const src of sources) {
1620
- if (statTypeSync(src) !== "file") return void 0;
1621
- let dst = destBase;
1622
- if (intoDir) {
1623
- const base = src.replace(/\/+$/, "").split("/").pop() || "";
1624
- if (!base) return void 0;
1625
- dst = `${destBase.replace(/\/+$/, "")}/${base}`;
1626
- }
1627
- if (src === dst) return void 0;
1628
- const finalSt = statTypeSync(dst);
1629
- if (finalSt !== "missing" && finalSt !== "file") return void 0;
1630
- if (finalSt === "file" && noClobber) continue;
1631
- const srcMode = statModeSync ? statModeSync(src) : void 0;
1632
- const bytes = readFileSync(src);
1633
- if (!bytes) return void 0;
1634
- if (finalSt === "file" && !rmSync(dst)) return void 0;
1635
- if (!writeFileSync(dst, bytes, false, srcMode) || !rmSync(src)) return void 0;
1636
- if (verbose) out += `renamed '${src}' -> '${dst}'
1637
- `;
1638
- }
1639
- return out;
1640
- }
1641
- function evalSyncRmdir(opArgs, statTypeSync, listDirSync, rmSync) {
1642
- const gnuInfo = gnuInformationSync("rmdir", opArgs);
1643
- if (gnuInfo !== void 0) return gnuInfo;
1644
- let verbose = false;
1645
- let parents = false;
1646
- let ignoreNonEmpty = false;
1647
- let ended = false;
1648
- const operands = [];
1649
- for (let i = 0; i < opArgs.length; i++) {
1650
- const a = opArgs[i];
1651
- if (ended || !a.startsWith("-") || a === "-") {
1652
- operands.push(a);
1653
- continue;
1654
- }
1655
- if (a === "--") {
1656
- ended = true;
1657
- continue;
1658
- }
1659
- if (a === "-v" || a === "--verbose") {
1660
- verbose = true;
1661
- continue;
1662
- }
1663
- if (a === "-p" || a === "--parents") {
1664
- parents = true;
1665
- continue;
1666
- }
1667
- if (a === "--ignore-fail-on-non-empty") {
1668
- ignoreNonEmpty = true;
1669
- continue;
1670
- }
1671
- if (a.startsWith("-") && !a.startsWith("--")) {
1672
- for (let j = 1; j < a.length; j++) {
1673
- const ch = a[j];
1674
- if (ch === "v") verbose = true;
1675
- else if (ch === "p") parents = true;
1676
- else return void 0;
1677
- }
1678
- continue;
1679
- }
1680
- return void 0;
1681
- }
1682
- if (operands.length === 0 || !statTypeSync || !listDirSync || !rmSync) return void 0;
1683
- const plan = [];
1684
- for (const rawDir of operands) {
1685
- const chain = [];
1686
- let cur = rawDir;
1687
- while (true) {
1688
- if (cur === "/" || cur === "." || cur === ".." || cur.endsWith("/.") || cur.endsWith("/..")) return void 0;
1689
- if (statTypeSync(cur) !== "directory") return void 0;
1690
- const entries = listDirSync(cur);
1691
- if (!entries) return void 0;
1692
- const count = "size" in entries ? entries.size : entries.length;
1693
- const expectedCount = chain.length === 0 ? 0 : 1;
1694
- if (count !== expectedCount) {
1695
- if (ignoreNonEmpty) break;
1696
- return void 0;
1697
- }
1698
- chain.push(cur);
1699
- if (!parents) break;
1700
- const trimmed = cur.replace(/\/+$/, "");
1701
- const slash = trimmed.lastIndexOf("/");
1702
- if (slash <= 0) break;
1703
- cur = trimmed.slice(0, slash);
1704
- }
1705
- plan.push(chain);
1706
- }
1707
- let out = "";
1708
- for (const chain of plan) {
1709
- for (const cur of chain) {
1710
- if (!rmSync(cur)) return void 0;
1711
- if (verbose) out += `rmdir: removing directory, '${cur}'
1712
- `;
1713
- }
1714
- }
1715
- return out;
1716
- }
1717
- function evalSyncSleep(opArgs) {
1718
- const gnuInfo = gnuInformationSync("sleep", opArgs);
1719
- if (gnuInfo !== void 0) return gnuInfo;
1720
- if (opArgs.length === 0) return void 0;
1721
- let count = 0;
1722
- for (const a of opArgs) {
1723
- if (a === "--") continue;
1724
- if (!/^\+?0+(\.0+)?[smhd]?$/u.test(a)) return void 0;
1725
- count++;
1726
- }
1727
- return count > 0 ? "" : void 0;
1728
- }
1729
- syncCommandEvaluators.evalSyncTee = evalSyncTee;
1730
- syncCommandEvaluators.evalSyncTouch = evalSyncTouch;
1731
- syncCommandEvaluators.evalSyncCp = evalSyncCp;
1732
- syncCommandEvaluators.evalSyncMv = evalSyncMv;
1733
- syncCommandEvaluators.evalSyncRmdir = evalSyncRmdir;
1734
- syncCommandEvaluators.evalSyncSleep = evalSyncSleep;
1735
- function evalSyncMkdir(opArgs, umask, statTypeSync, mkdirSync) {
1736
- const gnuInfo = gnuInformationSync("mkdir", opArgs);
1737
- if (gnuInfo !== void 0) return gnuInfo;
1738
- if (!statTypeSync || !mkdirSync) return void 0;
1739
- let parents = false;
1740
- let verbose = false;
1741
- let modeSpec;
1742
- let ended = false;
1743
- const operands = [];
1744
- for (let i = 0; i < opArgs.length; i++) {
1745
- const a = opArgs[i];
1746
- if (ended || !a.startsWith("-") || a === "-") {
1747
- operands.push(a);
1748
- continue;
1749
- }
1750
- if (a === "--") {
1751
- ended = true;
1752
- continue;
1753
- }
1754
- if (a === "-p" || a === "--parents") {
1755
- parents = true;
1756
- continue;
1757
- }
1758
- if (a === "-v" || a === "--verbose") {
1759
- verbose = true;
1760
- continue;
1761
- }
1762
- if (a === "-m" || a === "--mode") {
1763
- modeSpec = opArgs[++i];
1764
- if (modeSpec === void 0) return void 0;
1765
- continue;
1766
- }
1767
- if (a.startsWith("--mode=")) {
1768
- modeSpec = a.slice(7);
1769
- continue;
1770
- }
1771
- if (a.startsWith("-m") && a.length > 2) {
1772
- modeSpec = a.slice(2);
1773
- continue;
1774
- }
1775
- if (a.startsWith("-") && !a.startsWith("--")) {
1776
- for (let j = 1; j < a.length; j++) {
1777
- const ch = a[j];
1778
- if (ch === "p") parents = true;
1779
- else if (ch === "v") verbose = true;
1780
- else if (ch === "m") {
1781
- const rest = a.slice(j + 1);
1782
- modeSpec = rest || opArgs[++i];
1783
- if (modeSpec === void 0) return void 0;
1784
- break;
1785
- } else return void 0;
1786
- }
1787
- continue;
1788
- }
1789
- return void 0;
1790
- }
1791
- if (operands.length === 0) return void 0;
1792
- let mode = 511 & ~umask;
1793
- if (modeSpec !== void 0) {
1794
- if (/^[0-7]{1,4}$/.test(modeSpec)) {
1795
- mode = Number.parseInt(modeSpec, 8);
1796
- } else {
1797
- let cur = mode;
1798
- for (const clause of modeSpec.split(",")) {
1799
- const m = /^([ugoa]*)((?:[+=-][rwxXstugo]*)+)$/.exec(clause);
1800
- if (!m) return void 0;
1801
- const who = m[1];
1802
- const all = !who || who.includes("a");
1803
- const uMask = (all || who.includes("u") ? 2496 : 0) | (all || who.includes("g") ? 1080 : 0) | (all || who.includes("o") ? 519 : 0);
1804
- for (const opMatch of m[2].matchAll(/([+=-])([rwxXstugo]*)/g)) {
1805
- const op = opMatch[1];
1806
- const perms = opMatch[2];
1807
- let bits = 0;
1808
- for (const ch of perms) {
1809
- if (ch === "r") bits |= 292;
1810
- else if (ch === "w") bits |= 146;
1811
- else if (ch === "x" || ch === "X") bits |= 73;
1812
- else if (ch === "s") bits |= 3072;
1813
- else if (ch === "t") bits |= 512;
1814
- else return void 0;
1815
- }
1816
- const masked = bits & (who ? uMask : 3584 | 511 & ~umask);
1817
- if (op === "+") cur |= masked;
1818
- else if (op === "-") cur &= ~masked;
1819
- else cur = cur & ~uMask | bits & uMask;
1820
- }
1821
- }
1822
- mode = cur & 4095;
1823
- }
1824
- }
1825
- for (const dir of operands) {
1826
- const st = statTypeSync(dir);
1827
- if (parents) {
1828
- if (st !== "missing" && st !== "directory") return void 0;
1829
- } else {
1830
- if (st !== "missing") return void 0;
1831
- }
1832
- }
1833
- let out = "";
1834
- for (const dir of operands) {
1835
- if (parents && verbose) {
1836
- const parts = dir.split("/").filter(Boolean);
1837
- let cur = dir.startsWith("/") ? "" : ".";
1838
- for (let idx = 0; idx < parts.length; idx++) {
1839
- const part = parts[idx];
1840
- cur = cur === "" ? "/" + part : cur === "." ? part : cur + "/" + part;
1841
- const st2 = statTypeSync(cur);
1842
- if (st2 === "directory") continue;
1843
- if (st2 !== "missing") return void 0;
1844
- const stepMode = idx === parts.length - 1 ? mode : 511 & ~umask;
1845
- if (!mkdirSync(cur, false, stepMode)) return void 0;
1846
- out += `mkdir: created directory '${cur}'
1847
- `;
1848
- }
1849
- continue;
1850
- }
1851
- const st = statTypeSync(dir);
1852
- if (parents && st === "directory") continue;
1853
- if (!mkdirSync(dir, parents, mode)) return void 0;
1854
- if (verbose) out += `mkdir: created directory '${dir}'
1855
- `;
1856
- }
1857
- return out;
1858
- }
1859
- function evalSyncRm(opArgs, statTypeSync, listDirSync, rmSync) {
1860
- const gnuInfo = gnuInformationSync("rm", opArgs);
1861
- if (gnuInfo !== void 0) return gnuInfo;
1862
- if (!statTypeSync || !listDirSync || !rmSync) return void 0;
1863
- let force = false;
1864
- let recursive = false;
1865
- let dirFlag = false;
1866
- let verbose = false;
1867
- let ended = false;
1868
- const operands = [];
1869
- for (let i = 0; i < opArgs.length; i++) {
1870
- const a = opArgs[i];
1871
- if (ended || !a.startsWith("-") || a === "-") {
1872
- operands.push(a);
1873
- continue;
1874
- }
1875
- if (a === "--") {
1876
- ended = true;
1877
- continue;
1878
- }
1879
- if (a === "-f" || a === "--force") {
1880
- force = true;
1881
- continue;
1882
- }
1883
- if (a === "-r" || a === "-R" || a === "--recursive") {
1884
- recursive = true;
1885
- continue;
1886
- }
1887
- if (a === "-d" || a === "--dir") {
1888
- dirFlag = true;
1889
- continue;
1890
- }
1891
- if (a === "-v" || a === "--verbose") {
1892
- verbose = true;
1893
- continue;
1894
- }
1895
- if (a.startsWith("-") && !a.startsWith("--")) {
1896
- for (let j = 1; j < a.length; j++) {
1897
- const ch = a[j];
1898
- if (ch === "f") force = true;
1899
- else if (ch === "r" || ch === "R") recursive = true;
1900
- else if (ch === "d") dirFlag = true;
1901
- else if (ch === "v") verbose = true;
1902
- else return void 0;
1903
- }
1904
- continue;
1905
- }
1906
- return void 0;
1907
- }
1908
- if (operands.length === 0) return force ? "" : void 0;
1909
- for (const f of operands) {
1910
- if (f === "/" || f === "." || f === ".." || f.endsWith("/.") || f.endsWith("/..")) return void 0;
1911
- const st = statTypeSync(f);
1912
- if (st === "missing") {
1913
- if (!force) return void 0;
1914
- } else if (st === "directory") {
1915
- const entries = listDirSync(f);
1916
- const count = entries ? "size" in entries ? entries.size : entries.length : 1;
1917
- if (!recursive) {
1918
- if (!dirFlag || count > 0) return void 0;
1919
- }
1920
- } else if (st !== "file" && st !== "symlink") {
1921
- return void 0;
1922
- }
1923
- }
1924
- const collectRmVerbose = (p) => {
1925
- let chunk = "";
1926
- const st = statTypeSync(p);
1927
- if (st === "directory" && recursive) {
1928
- const entries = listDirSync(p);
1929
- const names = entries ? Array.isArray(entries) ? entries : [...entries.keys()] : [];
1930
- for (const name of names) {
1931
- chunk += collectRmVerbose(p.endsWith("/") ? `${p}${name}` : `${p}/${name}`);
1932
- }
1933
- }
1934
- chunk += `removed '${p}'
1935
- `;
1936
- return chunk;
1937
- };
1938
- let out = "";
1939
- for (const f of operands) {
1940
- const st = statTypeSync(f);
1941
- if (st === "missing") continue;
1942
- const verboseLines = verbose ? collectRmVerbose(f) : "";
1943
- if (!rmSync(f)) return void 0;
1944
- if (verbose) out += verboseLines;
1945
- }
1946
- return out;
1947
- }
1948
- syncCommandEvaluators.evalSyncMkdir = evalSyncMkdir;
1949
- syncCommandEvaluators.evalSyncRm = evalSyncRm;
1950
- function evalSyncLn(opArgs, statTypeSync, rmSync, linkSync) {
1951
- const gnuInfo = gnuInformationSync("ln", opArgs);
1952
- if (gnuInfo !== void 0) return gnuInfo;
1953
- if (!statTypeSync || !rmSync || !linkSync) return void 0;
1954
- let symbolic = false;
1955
- let relative = false;
1956
- let force = false;
1957
- let verbose = false;
1958
- let noDeref = false;
1959
- let noTargetDir = false;
1960
- let targetDir;
1961
- let ended = false;
1962
- const operands = [];
1963
- for (let i = 0; i < opArgs.length; i++) {
1964
- const a = opArgs[i];
1965
- if (ended || !a.startsWith("-") || a === "-") {
1966
- operands.push(a);
1967
- continue;
1968
- }
1969
- if (a === "--") {
1970
- ended = true;
1971
- continue;
1972
- }
1973
- if (a === "-s" || a === "--symbolic") {
1974
- symbolic = true;
1975
- continue;
1976
- }
1977
- if (a === "-r" || a === "--relative") {
1978
- relative = true;
1979
- continue;
1980
- }
1981
- if (a === "-f" || a === "--force") {
1982
- force = true;
1983
- continue;
1984
- }
1985
- if (a === "-v" || a === "--verbose") {
1986
- verbose = true;
1987
- continue;
1988
- }
1989
- if (a === "-n" || a === "--no-dereference") {
1990
- noDeref = true;
1991
- continue;
1992
- }
1993
- if (a === "-T" || a === "--no-target-directory") {
1994
- noTargetDir = true;
1995
- continue;
1996
- }
1997
- if (a === "-t" || a === "--target-directory" || a.startsWith("--target-directory=")) {
1998
- const td = a.startsWith("--target-directory=") ? a.slice(19) : opArgs[++i];
1999
- if (!td) return void 0;
2000
- targetDir = td;
2001
- continue;
2002
- }
2003
- if (a.startsWith("-") && !a.startsWith("--")) {
2004
- for (let j = 1; j < a.length; j++) {
2005
- const ch = a[j];
2006
- if (ch === "s") symbolic = true;
2007
- else if (ch === "r") relative = true;
2008
- else if (ch === "f") force = true;
2009
- else if (ch === "v") verbose = true;
2010
- else if (ch === "n") noDeref = true;
2011
- else if (ch === "T") noTargetDir = true;
2012
- else if (ch === "t") {
2013
- const rest = a.slice(j + 1) || opArgs[++i];
2014
- if (!rest) return void 0;
2015
- targetDir = rest;
2016
- break;
2017
- } else return void 0;
2018
- }
2019
- continue;
2020
- }
2021
- return void 0;
2022
- }
2023
- if (noTargetDir && targetDir !== void 0 || relative && !symbolic) return void 0;
2024
- const normRel = (p) => {
2025
- const outParts = [];
2026
- for (const seg of p.split("/")) {
2027
- if (!seg || seg === ".") continue;
2028
- if (seg === "..") {
2029
- if (outParts.length > 0 && outParts[outParts.length - 1] !== "..") outParts.pop();
2030
- else if (!p.startsWith("/")) outParts.push("..");
2031
- } else outParts.push(seg);
2032
- }
2033
- return outParts;
2034
- };
2035
- const computeRelTarget = (srcPath, dstPath) => {
2036
- if (srcPath.startsWith("/") !== dstPath.startsWith("/")) return void 0;
2037
- const dstDir = dstPath.includes("/") ? dstPath.slice(0, dstPath.lastIndexOf("/")) || "/" : ".";
2038
- const fromParts = normRel(dstDir);
2039
- const toParts = normRel(srcPath);
2040
- if (fromParts.includes("..") || toParts.includes("..")) return void 0;
2041
- let common = 0;
2042
- while (common < fromParts.length && common < toParts.length && fromParts[common] === toParts[common]) common++;
2043
- const up = Array.from({ length: fromParts.length - common }, () => "..");
2044
- const rel = [...up, ...toParts.slice(common)].join("/");
2045
- return rel || ".";
2046
- };
2047
- const pairs = [];
2048
- if (targetDir !== void 0) {
2049
- if (operands.length === 0 || statTypeSync(targetDir) !== "directory") return void 0;
2050
- for (const s of operands) {
2051
- const base = s.replace(/\/+$/, "").split("/").pop() || "";
2052
- if (!base) return void 0;
2053
- pairs.push([s, `${targetDir.replace(/\/+$/, "")}/${base}`]);
2054
- }
2055
- } else if (operands.length === 1) {
2056
- if (noTargetDir) return void 0;
2057
- const s = operands[0];
2058
- const base = s.replace(/\/+$/, "").split("/").pop() || "";
2059
- if (!base) return void 0;
2060
- pairs.push([s, `./${base}`]);
2061
- } else if (operands.length >= 2) {
2062
- const last = operands[operands.length - 1];
2063
- const dstSt = statTypeSync(last);
2064
- if (!noDeref && dstSt === "directory") {
2065
- if (noTargetDir) return void 0;
2066
- for (let idx = 0; idx < operands.length - 1; idx++) {
2067
- const s = operands[idx];
2068
- const base = s.replace(/\/+$/, "").split("/").pop() || "";
2069
- if (!base) return void 0;
2070
- pairs.push([s, `${last.replace(/\/+$/, "")}/${base}`]);
2071
- }
2072
- } else if (operands.length === 2) {
2073
- pairs.push([operands[0], last]);
2074
- } else {
2075
- return void 0;
2076
- }
2077
- } else {
2078
- return void 0;
2079
- }
2080
- let out = "";
2081
- for (const [src, dst] of pairs) {
2082
- if (!symbolic && statTypeSync(src) !== "file") return void 0;
2083
- if (src === dst) return void 0;
2084
- let linkTarget = src;
2085
- if (relative) {
2086
- const rel = computeRelTarget(src, dst);
2087
- if (!rel) return void 0;
2088
- linkTarget = rel;
2089
- }
2090
- const finalSt = statTypeSync(dst);
2091
- if (finalSt === "file" || finalSt === "symlink") {
2092
- if (!force) return void 0;
2093
- if (!rmSync(dst)) return void 0;
2094
- } else if (finalSt !== "missing") {
2095
- return void 0;
2096
- }
2097
- if (!linkSync(linkTarget, dst, symbolic)) return void 0;
2098
- if (verbose) out += `'${dst}' ${symbolic ? "->" : "=>"} '${linkTarget}'
2099
- `;
2100
- }
2101
- return out;
2102
- }
2103
- syncCommandEvaluators.evalSyncLn = evalSyncLn;
2104
- function evalSyncCat(inBytes, opArgs, readFileSync) {
2105
- const gnuInfo = gnuInformationSync("cat", opArgs);
2106
- if (gnuInfo !== void 0) return gnuInfo;
2107
- let flagN = false;
2108
- let flagB = false;
2109
- let flagS = false;
2110
- let flagE = false;
2111
- let flagT = false;
2112
- let flagV = false;
2113
- let ended = false;
2114
- const operands = [];
2115
- for (let i = 0; i < opArgs.length; i++) {
2116
- const a = opArgs[i];
2117
- if (ended || !a.startsWith("-") || a === "-") {
2118
- operands.push(a);
2119
- continue;
2120
- }
2121
- if (a === "--") {
2122
- ended = true;
2123
- continue;
2124
- }
2125
- if (a === "--number") {
2126
- flagN = true;
2127
- continue;
2128
- }
2129
- if (a === "--number-nonblank") {
2130
- flagB = true;
2131
- continue;
2132
- }
2133
- if (a === "--squeeze-blank") {
2134
- flagS = true;
2135
- continue;
2136
- }
2137
- if (a === "--show-ends") {
2138
- flagE = true;
2139
- continue;
2140
- }
2141
- if (a === "--show-tabs") {
2142
- flagT = true;
2143
- continue;
2144
- }
2145
- if (a === "--show-nonprinting") {
2146
- flagV = true;
2147
- continue;
2148
- }
2149
- if (a === "--show-all") {
2150
- flagV = true;
2151
- flagE = true;
2152
- flagT = true;
2153
- continue;
2154
- }
2155
- if (a.startsWith("-") && !a.startsWith("--")) {
2156
- for (let j = 1; j < a.length; j++) {
2157
- const ch = a[j];
2158
- if (ch === "n") flagN = true;
2159
- else if (ch === "b") flagB = true;
2160
- else if (ch === "s") flagS = true;
2161
- else if (ch === "E") flagE = true;
2162
- else if (ch === "T") flagT = true;
2163
- else if (ch === "v") flagV = true;
2164
- else if (ch === "A") {
2165
- flagV = true;
2166
- flagE = true;
2167
- flagT = true;
2168
- } else if (ch === "e") {
2169
- flagV = true;
2170
- flagE = true;
2171
- } else if (ch === "t") {
2172
- flagV = true;
2173
- flagT = true;
2174
- } else if (ch === "u") continue;
2175
- else return void 0;
2176
- }
2177
- continue;
2178
- }
2179
- return void 0;
2180
- }
2181
- const chunks = [];
2182
- let totalIn = 0;
2183
- if (operands.length === 0) {
2184
- if (inBytes === void 0) return void 0;
2185
- chunks.push(inBytes);
2186
- totalIn += inBytes.byteLength;
2187
- } else {
2188
- for (const op of operands) {
2189
- if (op === "-") {
2190
- if (inBytes === void 0) return void 0;
2191
- chunks.push(inBytes);
2192
- totalIn += inBytes.byteLength;
2193
- } else {
2194
- if (!readFileSync) return void 0;
2195
- const b = readFileSync(op);
2196
- if (!b) return void 0;
2197
- chunks.push(b);
2198
- totalIn += b.byteLength;
2199
- }
2200
- if (totalIn > 16384) return void 0;
2201
- }
2202
- }
2203
- if (!flagN && !flagB && !flagS && !flagE && !flagT && !flagV) {
2204
- for (const c of chunks) {
2205
- if (c.includes(0)) return void 0;
2206
- }
2207
- if (chunks.length === 1) return decoder.decode(chunks[0]);
2208
- const merged = new Uint8Array(totalIn);
2209
- let off = 0;
2210
- for (const c of chunks) {
2211
- merged.set(c, off);
2212
- off += c.byteLength;
2213
- }
2214
- return decoder.decode(merged);
2215
- }
2216
- let lineStart = true;
2217
- let blankCount = 0;
2218
- let num = 1;
2219
- let pendingCr = false;
2220
- const showEndsOnlyCr = flagE && !flagV;
2221
- const out = [];
2222
- for (const chunk of chunks) {
2223
- for (let i = 0; i < chunk.byteLength; i++) {
2224
- const byte = chunk[i];
2225
- if (pendingCr) {
2226
- pendingCr = false;
2227
- if (byte === 10) {
2228
- out.push(94, 77);
2229
- } else {
2230
- out.push(13);
2231
- }
2232
- }
2233
- if (lineStart && byte === 10 && flagS && blankCount > 0) continue;
2234
- if (lineStart && (flagB ? byte !== 10 : flagN)) {
2235
- const digits = String(num++);
2236
- const pad = Math.max(0, 6 - digits.length);
2237
- for (let k = 0; k < pad; k++) out.push(32);
2238
- for (let k = 0; k < digits.length; k++) out.push(digits.charCodeAt(k));
2239
- out.push(9);
2240
- }
2241
- if (byte === 10) {
2242
- if (flagE) out.push(36);
2243
- out.push(10);
2244
- blankCount = lineStart ? blankCount + 1 : 0;
2245
- lineStart = true;
2246
- } else {
2247
- lineStart = false;
2248
- blankCount = 0;
2249
- if (byte === 13 && showEndsOnlyCr) {
2250
- pendingCr = true;
2251
- } else if (byte === 9) {
2252
- if (flagT) out.push(94, 73);
2253
- else out.push(9);
2254
- } else if (flagV) {
2255
- let visible = byte;
2256
- if (visible >= 128) {
2257
- out.push(77, 45);
2258
- visible -= 128;
2259
- }
2260
- if (visible < 32) out.push(94, visible + 64);
2261
- else if (visible === 127) out.push(94, 63);
2262
- else out.push(visible);
2263
- } else {
2264
- if (byte === 0) return void 0;
2265
- out.push(byte);
2266
- }
2267
- }
2268
- }
2269
- }
2270
- if (pendingCr) out.push(13);
2271
- return decoder.decode(Uint8Array.from(out));
2272
- }
2273
- function evalSyncHeadTail(name, inBytes, opArgs, readFileSync) {
2274
- const gnuInfo = gnuInformationSync(name, opArgs);
2275
- if (gnuInfo !== void 0) return gnuInfo;
2276
- let mode = "n";
2277
- let countStr = "10";
2278
- let headerMode = "default";
2279
- let zeroTerminated = false;
2280
- let ended = false;
2281
- const operands = [];
2282
- for (let i = 0; i < opArgs.length; i++) {
2283
- const a = opArgs[i];
2284
- if (ended || !a.startsWith("-") && !(name === "tail" && i === 0 && /^\+[0-9]+$/.test(a)) || a === "-") {
2285
- operands.push(a);
2286
- continue;
2287
- }
2288
- if (a === "--") {
2289
- ended = true;
2290
- continue;
2291
- }
2292
- if (a === "-q" || a === "--quiet" || a === "--silent") {
2293
- headerMode = "q";
2294
- continue;
2295
- }
2296
- if (a === "-v" || a === "--verbose") {
2297
- headerMode = "v";
2298
- continue;
2299
- }
2300
- if (a === "-z" || a === "--zero-terminated") {
2301
- zeroTerminated = true;
2302
- continue;
2303
- }
2304
- if (a === "-n" || a === "--lines") {
2305
- if (i + 1 >= opArgs.length) return void 0;
2306
- mode = "n";
2307
- countStr = opArgs[++i];
2308
- continue;
2309
- }
2310
- if (a === "-c" || a === "--bytes") {
2311
- if (i + 1 >= opArgs.length) return void 0;
2312
- mode = "c";
2313
- countStr = opArgs[++i];
2314
- continue;
2315
- }
2316
- if (a.startsWith("--lines=")) {
2317
- mode = "n";
2318
- countStr = a.slice(8);
2319
- continue;
2320
- }
2321
- if (a.startsWith("--bytes=")) {
2322
- mode = "c";
2323
- countStr = a.slice(8);
2324
- continue;
2325
- }
2326
- if (/^-[0-9]+$/.test(a) || name === "tail" && i === 0 && /^\+[0-9]+$/.test(a)) {
2327
- mode = "n";
2328
- countStr = a.startsWith("-") ? a.slice(1) : a;
2329
- continue;
2330
- }
2331
- if (a.startsWith("-") && !a.startsWith("--")) {
2332
- for (let j = 1; j < a.length; j++) {
2333
- const ch = a[j];
2334
- if (ch === "q") headerMode = "q";
2335
- else if (ch === "v") headerMode = "v";
2336
- else if (ch === "z") zeroTerminated = true;
2337
- else if (ch === "n" || ch === "c") {
2338
- mode = ch;
2339
- const rest = a.slice(j + 1) || opArgs[++i];
2340
- if (!rest) return void 0;
2341
- countStr = rest;
2342
- break;
2343
- } else return void 0;
2344
- }
2345
- continue;
2346
- }
2347
- return void 0;
2348
- }
2349
- const mCount = /^([+-]?)([0-9]{1,6})(b|kB|K|MB|M)?$/.exec(countStr);
2350
- if (!mCount) return void 0;
2351
- const mult = mCount[3] === "b" ? 512 : mCount[3] === "kB" ? 1e3 : mCount[3] === "K" ? 1024 : mCount[3] === "MB" ? 1e6 : mCount[3] === "M" ? 1048576 : 1;
2352
- const count = Number(mCount[2]) * mult;
2353
- const isPlus = countStr.startsWith("+");
2354
- const isMinus = countStr.startsWith("-");
2355
- if (name === "head" && isPlus) return void 0;
2356
- if (name === "tail" && isMinus && mode === "c") return void 0;
2357
- const targets = operands.length > 0 ? operands : ["-"];
2358
- const showHeaders = headerMode === "v" || headerMode !== "q" && targets.length > 1;
2359
- let out = "";
2360
- for (let idx = 0; idx < targets.length; idx++) {
2361
- const t = targets[idx];
2362
- let bytes;
2363
- if (t === "-") {
2364
- if (inBytes === void 0) return void 0;
2365
- bytes = inBytes;
2366
- } else {
2367
- if (!readFileSync) return void 0;
2368
- bytes = readFileSync(t);
2369
- }
2370
- if (!bytes || !zeroTerminated && bytes.includes(0)) return void 0;
2371
- const text = decoder.decode(bytes);
2372
- if (showHeaders) {
2373
- out += `${idx > 0 ? "\n" : ""}==> ${t === "-" ? "standard input" : t} <==
2374
- `;
2375
- }
2376
- if (mode === "c") {
2377
- if (name === "head") {
2378
- out += isMinus ? count === 0 ? text : decoder.decode(bytes.subarray(0, Math.max(0, bytes.byteLength - count))) : decoder.decode(bytes.subarray(0, count));
2379
- } else {
2380
- out += isPlus ? decoder.decode(bytes.subarray(Math.max(0, count - 1))) : count === 0 ? "" : decoder.decode(bytes.subarray(Math.max(0, bytes.byteLength - count)));
2381
- }
2382
- } else {
2383
- const termCode = zeroTerminated ? 0 : 10;
2384
- const lines2 = [];
2385
- let start = 0;
2386
- for (let k = 0; k < text.length; k++) {
2387
- if (text.charCodeAt(k) === termCode) {
2388
- lines2.push(text.slice(start, k + 1));
2389
- start = k + 1;
2390
- }
2391
- }
2392
- if (start < text.length) lines2.push(text.slice(start));
2393
- let selected;
2394
- if (name === "head") {
2395
- selected = isMinus ? count === 0 ? lines2 : lines2.slice(0, Math.max(0, lines2.length - count)) : lines2.slice(0, count);
2396
- } else {
2397
- selected = isPlus ? lines2.slice(Math.max(0, count - 1)) : count === 0 ? [] : lines2.slice(-count);
2398
- }
2399
- out += selected.join("");
2400
- }
2401
- }
2402
- return out;
2403
- }
2404
- syncCommandEvaluators.evalSyncCat = evalSyncCat;
2405
- syncCommandEvaluators.evalSyncHeadTail = evalSyncHeadTail;
2406
- function evalSyncWc(inBytes, opArgs, singleByte, readFileSync) {
2407
- const gnuInfo = gnuInformationSync("wc", opArgs);
2408
- if (gnuInfo !== void 0) return gnuInfo;
2409
- const flags = /* @__PURE__ */ new Set();
2410
- let totalMode = "auto";
2411
- let hasFiles0From = false;
2412
- let ended = false;
2413
- const operands = [];
2414
- for (let i = 0; i < opArgs.length; i++) {
2415
- const a = opArgs[i];
2416
- if (ended || !a.startsWith("-") || a === "-") {
2417
- operands.push(a);
2418
- continue;
2419
- }
2420
- if (a === "--") {
2421
- ended = true;
2422
- continue;
2423
- }
2424
- if (a === "--lines") {
2425
- flags.add("l");
2426
- continue;
2427
- }
2428
- if (a === "--words") {
2429
- flags.add("w");
2430
- continue;
2431
- }
2432
- if (a === "--chars") {
2433
- flags.add("m");
2434
- continue;
2435
- }
2436
- if (a === "--bytes") {
2437
- flags.add("c");
2438
- continue;
2439
- }
2440
- if (a === "--max-line-length") {
2441
- flags.add("L");
2442
- continue;
2443
- }
2444
- if (a === "--total") {
2445
- if (i + 1 >= opArgs.length) return void 0;
2446
- totalMode = opArgs[++i];
2447
- continue;
2448
- }
2449
- if (a.startsWith("--total=")) {
2450
- totalMode = a.slice(8);
2451
- continue;
2452
- }
2453
- if (a === "--files0-from" || a.startsWith("--files0-from=")) {
2454
- hasFiles0From = true;
2455
- const f0 = a === "--files0-from" ? opArgs[++i] : a.slice(14);
2456
- if (!f0) return void 0;
2457
- const fBytes = f0 === "-" ? inBytes : readFileSync?.(f0);
2458
- if (!fBytes || fBytes.byteLength > 16384) return void 0;
2459
- const fText = decoder.decode(fBytes);
2460
- const parts = fText.endsWith("\0") ? fText.slice(0, -1).split("\0") : fText.length === 0 ? [] : fText.split("\0");
2461
- for (const p of parts) {
2462
- if (!p) return void 0;
2463
- operands.push(p);
2464
- }
2465
- continue;
2466
- }
2467
- if (a.startsWith("-") && !a.startsWith("--")) {
2468
- for (let j = 1; j < a.length; j++) {
2469
- const ch = a[j];
2470
- if (ch === "l" || ch === "w" || ch === "m" || ch === "c" || ch === "L") {
2471
- flags.add(ch);
2472
- } else {
2473
- return void 0;
2474
- }
2475
- }
2476
- continue;
2477
- }
2478
- return void 0;
2479
- }
2480
- if (!["auto", "always", "only", "never"].includes(totalMode)) return void 0;
2481
- if (flags.size === 0) {
2482
- flags.add("l");
2483
- flags.add("w");
2484
- flags.add("c");
2485
- }
2486
- const selected = ["l", "w", "m", "c", "L"].filter((f) => flags.has(f));
2487
- if (hasFiles0From && operands.length === 0) return "";
2488
- const names = operands.length > 0 ? operands : ["-"];
2489
- const buffers = [];
2490
- let totalBytesAll = 0;
2491
- for (const name of names) {
2492
- let b;
2493
- if (name === "-") {
2494
- if (inBytes === void 0) return void 0;
2495
- b = inBytes;
2496
- } else {
2497
- if (!readFileSync) return void 0;
2498
- b = readFileSync(name);
2499
- if (!b) return void 0;
2500
- }
2501
- totalBytesAll += b.byteLength;
2502
- if (totalBytesAll > 65536) return void 0;
2503
- if (!singleByte && (flags.has("w") || flags.has("L")) && b.some((byte) => byte >= 128)) {
2504
- return void 0;
2505
- }
2506
- buffers.push(b);
2507
- }
2508
- let width = 1;
2509
- if (totalMode !== "only" && (names.length > 1 || selected.length > 1)) {
2510
- let totalSize = 0;
2511
- for (let i = 0; i < names.length; i++) {
2512
- if (names[i] === "-") {
2513
- width = Math.max(width, 7);
2514
- } else {
2515
- totalSize += buffers[i].byteLength;
2516
- }
2517
- }
2518
- width = Math.max(width, String(totalSize).length);
2519
- }
2520
- const totals = { l: 0, w: 0, m: 0, c: 0, L: 0 };
2521
- const rows = [];
2522
- const formatRow = (counts, label) => selected.map((f) => String(counts[f]).padStart(width)).join(" ") + (label === void 0 ? "" : ` ${label}`) + "\n";
2523
- for (let idx = 0; idx < names.length; idx++) {
2524
- const name = names[idx];
2525
- const buf = buffers[idx];
2526
- let l = 0;
2527
- let w = 0;
2528
- let m = 0;
2529
- const c = buf.byteLength;
2530
- let maxL = 0;
2531
- let columns = 0;
2532
- let inWord = false;
2533
- for (let i = 0; i < buf.byteLength; i++) {
2534
- const byte = buf[i];
2535
- if (byte === 10) {
2536
- l++;
2537
- inWord = false;
2538
- if (columns > maxL) maxL = columns;
2539
- columns = 0;
2540
- } else if (byte === 32 || byte >= 9 && byte <= 13) {
2541
- inWord = false;
2542
- if (byte === 9) columns += 8 - (columns & 7);
2543
- else if (byte === 13 || byte === 12) {
2544
- if (columns > maxL) maxL = columns;
2545
- columns = 0;
2546
- } else if (byte === 32) {
2547
- columns++;
2548
- }
2549
- } else if (byte >= 33 && byte < 127) {
2550
- if (!inWord) {
2551
- w++;
2552
- inWord = true;
2553
- }
2554
- columns++;
2555
- }
2556
- }
2557
- if (columns > maxL) maxL = columns;
2558
- if (singleByte) {
2559
- m = c;
2560
- } else if (flags.has("m")) {
2561
- m = Array.from(decoder.decode(buf)).length;
2562
- }
2563
- const counts = { l, w, m, c, L: maxL };
2564
- totals.l += l;
2565
- totals.w += w;
2566
- totals.m += m;
2567
- totals.c += c;
2568
- totals.L = Math.max(totals.L, maxL);
2569
- if (totalMode !== "only") {
2570
- rows.push(formatRow(counts, operands.length > 0 ? name : void 0));
2571
- }
2572
- }
2573
- if (totalMode === "only") {
2574
- rows.push(formatRow(totals));
2575
- } else if (totalMode === "always" || totalMode === "auto" && names.length > 1) {
2576
- rows.push(formatRow(totals, "total"));
2577
- }
2578
- return rows.join("");
2579
- }
2580
- syncCommandEvaluators.evalSyncWc = evalSyncWc;
2581
-
2582
- export {
2583
- path_exports,
2584
- inputRequirements,
2585
- textOutputRequirements,
2586
- pwdRequirements,
2587
- predicateRequirements,
2588
- RecordBuffer,
2589
- gnuInformationSync,
2590
- gnuInformation,
2591
- utf8ByteLength,
2592
- bytesFrom,
2593
- concatBytes,
2594
- compareBytes,
2595
- filledBytes,
2596
- latin1Text,
2597
- equalBytes,
2598
- base64Text,
2599
- defaultSleepScheduler,
2600
- settings,
2601
- CommandFailure,
2602
- checkSize,
2603
- emit,
2604
- timeEnvExecutorSettings,
2605
- command,
2606
- ownEnvironment,
2607
- nanosecondsPerSecond,
2608
- monthNames,
2609
- weekdayNames,
2610
- floorDivide,
2611
- millisecondsInstant,
2612
- utcMilliseconds,
2613
- TimeZone,
2614
- parseDate,
2615
- touchTimes,
2616
- RESOLVED_EXIT_ZERO,
2617
- RESOLVED_EXIT_ONE,
2618
- encoder2 as encoder,
2619
- decoder,
2620
- bufferLimit,
2621
- syncCommandEvaluators,
2622
- options,
2623
- value,
2624
- integer,
2625
- requireOperands,
2626
- codeOf,
2627
- RETURN_EXIT_ZERO,
2628
- RETURN_EXIT_ONE,
2629
- RETURN_EXIT_TWO,
2630
- outputRange,
2631
- output,
2632
- diagnostic,
2633
- define,
2634
- eachOperand,
2635
- input,
2636
- assertInputRequirements,
2637
- concatenate,
2638
- lines,
2639
- emptyInput,
2640
- replaceArgument,
2641
- escapeBytes,
2642
- builtInDirectContextExecutors2 as builtInDirectContextExecutors,
2643
- isDefaultCommandOptions,
2644
- registerDefaultExecutor,
2645
- registerDefaultExecutors,
2646
- UsageError2 as UsageError
2647
- };
2648
- //# sourceMappingURL=chunk-ISCZG7WA.js.map