@wonderwhy-er/desktop-commander 0.3.2-alpha.1 → 0.3.2

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 (194) hide show
  1. package/dist/bootstrap.js +7 -7
  2. package/dist/command-manager.d.ts +98 -1
  3. package/dist/command-manager.js +237 -16
  4. package/dist/remote-device/desktop-commander-integration.js +3 -1
  5. package/dist/remote-device/diagnostics/redact.js +30 -8
  6. package/dist/remote-device/diagnostics/report.js +30 -13
  7. package/dist/remote-device/mqtt/mqtt-enrollment.js +1 -1
  8. package/dist/remote-device/mqtt/mqtt-transport.js +2 -2
  9. package/dist/remote-device/remote-channel.d.ts +1 -1
  10. package/dist/remote-device/remote-channel.js +1 -1
  11. package/dist/remote-device/transport-telemetry.js +5 -4
  12. package/dist/server.js +2 -0
  13. package/dist/terminal-manager.js +4 -6
  14. package/dist/tools/improved-process-tools.d.ts +2 -0
  15. package/dist/tools/improved-process-tools.js +68 -40
  16. package/dist/tools/pdf/markdown.js +7 -3
  17. package/dist/tools/process.js +10 -2
  18. package/dist/track-installation.js +2 -2
  19. package/dist/ui/config-editor/config-editor-runtime.js +80 -61
  20. package/dist/ui/file-preview/preview-runtime.js +225 -207
  21. package/dist/utils/brace-expansion.d.ts +30 -0
  22. package/dist/utils/brace-expansion.js +192 -0
  23. package/dist/utils/capture.d.ts +8 -2
  24. package/dist/utils/capture.js +1 -1
  25. package/dist/utils/cmd-commands.d.ts +3 -0
  26. package/dist/utils/cmd-commands.js +370 -0
  27. package/dist/utils/command-reading.d.ts +92 -0
  28. package/dist/utils/command-reading.js +14 -0
  29. package/dist/utils/command-wrappers.d.ts +45 -0
  30. package/dist/utils/command-wrappers.js +964 -0
  31. package/dist/utils/inline-shells.d.ts +67 -0
  32. package/dist/utils/inline-shells.js +310 -0
  33. package/dist/utils/posix-commands.d.ts +6 -0
  34. package/dist/utils/posix-commands.js +237 -0
  35. package/dist/utils/posix-shell-capabilities.d.ts +8 -0
  36. package/dist/utils/posix-shell-capabilities.js +120 -0
  37. package/dist/utils/powershell-commands.d.ts +61 -0
  38. package/dist/utils/powershell-commands.js +468 -0
  39. package/dist/utils/process-tree.js +4 -4
  40. package/dist/utils/shell-script-files.d.ts +8 -0
  41. package/dist/utils/shell-script-files.js +140 -0
  42. package/dist/utils/shell.d.ts +37 -0
  43. package/dist/utils/shell.js +73 -0
  44. package/dist/utils/system-info.d.ts +2 -0
  45. package/dist/utils/system-info.js +5 -1
  46. package/dist/utils/threadpool-size.d.ts +36 -0
  47. package/dist/utils/threadpool-size.js +143 -0
  48. package/dist/version.d.ts +1 -1
  49. package/dist/version.js +1 -1
  50. package/package.json +11 -9
  51. package/dist/bootstrap.js.map +0 -1
  52. package/dist/command-manager.js.map +0 -1
  53. package/dist/config-field-definitions.js.map +0 -1
  54. package/dist/config-manager.js.map +0 -1
  55. package/dist/config-recovery.js.map +0 -1
  56. package/dist/config.js.map +0 -1
  57. package/dist/custom-stdio.js.map +0 -1
  58. package/dist/error-handlers.js.map +0 -1
  59. package/dist/handlers/edit-search-handlers.js.map +0 -1
  60. package/dist/handlers/filesystem-handlers.js.map +0 -1
  61. package/dist/handlers/history-handlers.js.map +0 -1
  62. package/dist/handlers/index.js.map +0 -1
  63. package/dist/handlers/process-handlers.js.map +0 -1
  64. package/dist/handlers/search-answers.js.map +0 -1
  65. package/dist/handlers/search-handlers.js.map +0 -1
  66. package/dist/handlers/terminal-handlers.js.map +0 -1
  67. package/dist/index.js.map +0 -1
  68. package/dist/npm-scripts/remote.js.map +0 -1
  69. package/dist/npm-scripts/setup.js.map +0 -1
  70. package/dist/npm-scripts/uninstall.js.map +0 -1
  71. package/dist/npm-scripts/verify-ripgrep.js.map +0 -1
  72. package/dist/remote-device/desktop-commander-integration.js.map +0 -1
  73. package/dist/remote-device/device-authenticator.js.map +0 -1
  74. package/dist/remote-device/device.js.map +0 -1
  75. package/dist/remote-device/diagnostics/device-log.js.map +0 -1
  76. package/dist/remote-device/diagnostics/redact.js.map +0 -1
  77. package/dist/remote-device/diagnostics/report.js.map +0 -1
  78. package/dist/remote-device/diagnostics/upload.js.map +0 -1
  79. package/dist/remote-device/mqtt/config.js.map +0 -1
  80. package/dist/remote-device/mqtt/mqtt-enrollment.js.map +0 -1
  81. package/dist/remote-device/mqtt/mqtt-transport.js.map +0 -1
  82. package/dist/remote-device/realtime-health-telemetry.js.map +0 -1
  83. package/dist/remote-device/remote-channel.js.map +0 -1
  84. package/dist/remote-device/remote-utils.js.map +0 -1
  85. package/dist/remote-device/rollouts.js.map +0 -1
  86. package/dist/remote-device/transport-telemetry.js.map +0 -1
  87. package/dist/search-manager.js.map +0 -1
  88. package/dist/server.js.map +0 -1
  89. package/dist/terminal-manager.js.map +0 -1
  90. package/dist/tools/config.js.map +0 -1
  91. package/dist/tools/edit.js.map +0 -1
  92. package/dist/tools/feedback.js.map +0 -1
  93. package/dist/tools/filesystem.js.map +0 -1
  94. package/dist/tools/fuzzySearch.js.map +0 -1
  95. package/dist/tools/fuzzySearchCore.js.map +0 -1
  96. package/dist/tools/improved-process-tools.js.map +0 -1
  97. package/dist/tools/mime-types.js.map +0 -1
  98. package/dist/tools/pdf/extract-images.js.map +0 -1
  99. package/dist/tools/pdf/index.js.map +0 -1
  100. package/dist/tools/pdf/lib/pdf2md.js.map +0 -1
  101. package/dist/tools/pdf/manipulations.js.map +0 -1
  102. package/dist/tools/pdf/markdown.js.map +0 -1
  103. package/dist/tools/pdf/utils.js.map +0 -1
  104. package/dist/tools/process.js.map +0 -1
  105. package/dist/tools/prompts.js.map +0 -1
  106. package/dist/tools/schemas.js.map +0 -1
  107. package/dist/tools/usage.js.map +0 -1
  108. package/dist/types.js.map +0 -1
  109. package/dist/ui/config-editor/src/app.js.map +0 -1
  110. package/dist/ui/config-editor/src/array-modal.js.map +0 -1
  111. package/dist/ui/config-editor/src/main.js.map +0 -1
  112. package/dist/ui/contracts.js.map +0 -1
  113. package/dist/ui/file-preview/shared/preview-file-types.js.map +0 -1
  114. package/dist/ui/file-preview/src/app.js.map +0 -1
  115. package/dist/ui/file-preview/src/components/code-viewer.js.map +0 -1
  116. package/dist/ui/file-preview/src/components/highlighting.js.map +0 -1
  117. package/dist/ui/file-preview/src/components/html-renderer.js.map +0 -1
  118. package/dist/ui/file-preview/src/components/markdown-renderer.js.map +0 -1
  119. package/dist/ui/file-preview/src/directory-controller.js.map +0 -1
  120. package/dist/ui/file-preview/src/document-layout.js.map +0 -1
  121. package/dist/ui/file-preview/src/document-outline.js.map +0 -1
  122. package/dist/ui/file-preview/src/document-workspace.js.map +0 -1
  123. package/dist/ui/file-preview/src/file-type-handlers.js.map +0 -1
  124. package/dist/ui/file-preview/src/host/external-actions.js.map +0 -1
  125. package/dist/ui/file-preview/src/host/selection-context.js.map +0 -1
  126. package/dist/ui/file-preview/src/image-preview.js.map +0 -1
  127. package/dist/ui/file-preview/src/main.js.map +0 -1
  128. package/dist/ui/file-preview/src/markdown/conflict-dialog.js.map +0 -1
  129. package/dist/ui/file-preview/src/markdown/controller.js.map +0 -1
  130. package/dist/ui/file-preview/src/markdown/editor.js.map +0 -1
  131. package/dist/ui/file-preview/src/markdown/linking.js.map +0 -1
  132. package/dist/ui/file-preview/src/markdown/outline.js.map +0 -1
  133. package/dist/ui/file-preview/src/markdown/parser.js.map +0 -1
  134. package/dist/ui/file-preview/src/markdown/preview.js.map +0 -1
  135. package/dist/ui/file-preview/src/markdown/slugify.js.map +0 -1
  136. package/dist/ui/file-preview/src/markdown/utils.js.map +0 -1
  137. package/dist/ui/file-preview/src/model.js.map +0 -1
  138. package/dist/ui/file-preview/src/panel-actions.js.map +0 -1
  139. package/dist/ui/file-preview/src/path-utils.js.map +0 -1
  140. package/dist/ui/file-preview/src/payload-utils.js.map +0 -1
  141. package/dist/ui/file-preview/src/types.js.map +0 -1
  142. package/dist/ui/resources.js.map +0 -1
  143. package/dist/ui/shared/compact-row.js.map +0 -1
  144. package/dist/ui/shared/escape-html.js.map +0 -1
  145. package/dist/ui/shared/host-context.js.map +0 -1
  146. package/dist/ui/shared/tool-bridge.js.map +0 -1
  147. package/dist/ui/shared/tool-shell.js.map +0 -1
  148. package/dist/ui/shared/ui-event-tracker.js.map +0 -1
  149. package/dist/ui/shared/widget-state.js.map +0 -1
  150. package/dist/utils/ab-test.js.map +0 -1
  151. package/dist/utils/atomic-write.js.map +0 -1
  152. package/dist/utils/capture.js.map +0 -1
  153. package/dist/utils/dockerPrompt.js.map +0 -1
  154. package/dist/utils/exit-process.js.map +0 -1
  155. package/dist/utils/feature-flags.js.map +0 -1
  156. package/dist/utils/files/base.js.map +0 -1
  157. package/dist/utils/files/binary.js.map +0 -1
  158. package/dist/utils/files/docx.js.map +0 -1
  159. package/dist/utils/files/excel.js.map +0 -1
  160. package/dist/utils/files/factory.js.map +0 -1
  161. package/dist/utils/files/image.js.map +0 -1
  162. package/dist/utils/files/index.js.map +0 -1
  163. package/dist/utils/files/pdf.js.map +0 -1
  164. package/dist/utils/files/text.js.map +0 -1
  165. package/dist/utils/fuzzySearchLogger.js.map +0 -1
  166. package/dist/utils/internal-facts.js.map +0 -1
  167. package/dist/utils/lazy-package.js.map +0 -1
  168. package/dist/utils/lineEndingHandler.js.map +0 -1
  169. package/dist/utils/logger.js.map +0 -1
  170. package/dist/utils/mcp-ui-ab-test.js.map +0 -1
  171. package/dist/utils/open-browser.js.map +0 -1
  172. package/dist/utils/process-detection.js.map +0 -1
  173. package/dist/utils/process-tree.js.map +0 -1
  174. package/dist/utils/rename.js.map +0 -1
  175. package/dist/utils/ripgrep-resolver.js.map +0 -1
  176. package/dist/utils/shell.js.map +0 -1
  177. package/dist/utils/system-info.js.map +0 -1
  178. package/dist/utils/terminal-timestamps.js.map +0 -1
  179. package/dist/utils/toolHistory.js.map +0 -1
  180. package/dist/utils/trackTools.js.map +0 -1
  181. package/dist/utils/unsupportedParams.js.map +0 -1
  182. package/dist/utils/usageTracker.js.map +0 -1
  183. package/dist/utils/welcome-onboarding.js.map +0 -1
  184. package/dist/utils/withTimeout.js.map +0 -1
  185. package/dist/version.js.map +0 -1
  186. package/node_modules/@desktop-commander/telemetry-contract/README.md +0 -56
  187. package/node_modules/@desktop-commander/telemetry-contract/package.json +0 -32
  188. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +0 -39
  189. package/node_modules/@desktop-commander/telemetry-contract/transport.js +0 -167
  190. package/vendor/telemetry-contract/README.md +0 -56
  191. package/vendor/telemetry-contract/package.json +0 -32
  192. package/vendor/telemetry-contract/transport.d.ts +0 -38
  193. package/vendor/telemetry-contract/transport.js +0 -164
  194. package/vendor/telemetry-contract/transport.test.js +0 -39
@@ -0,0 +1,964 @@
1
+ import { getShellType, programName } from './shell.js';
2
+ import { requireCompleteArguments } from './command-reading.js';
3
+ /** tmux's commands that start the program after their options (tmux new-session -d sudo ls), by name and alias */
4
+ const TMUX_NEW_SESSION = { letters: 'cefFnstxy', flags: 'AdDEPX' };
5
+ const TMUX_NEW_WINDOW = { letters: 'ceFnt', flags: 'abdEkPS' };
6
+ const TMUX_SPLIT_WINDOW = { letters: 'BceFlmpRsStT', flags: 'bdEfhIkPvWZ' };
7
+ const TMUX_RESPAWN = { letters: 'cet', flags: 'Ek' };
8
+ const TMUX_COMMANDS = new Map([
9
+ ['new-session', TMUX_NEW_SESSION], ['new', TMUX_NEW_SESSION],
10
+ ['new-window', TMUX_NEW_WINDOW], ['neww', TMUX_NEW_WINDOW],
11
+ ['split-window', TMUX_SPLIT_WINDOW], ['splitw', TMUX_SPLIT_WINDOW],
12
+ ['respawn-pane', TMUX_RESPAWN], ['respawnp', TMUX_RESPAWN], ['respawn-window', TMUX_RESPAWN], ['respawnw', TMUX_RESPAWN],
13
+ ]);
14
+ /** find's words that take the next one as their value, GNU's and BSD's: -newerXY is each of -newerat … -newertt */
15
+ const FIND_VALUES = [
16
+ 'amin', 'anewer', 'atime', 'Bmin', 'Bnewer', 'Btime', 'cmin', 'cnewer', 'context', 'ctime', 'D', 'f', 'files0-from', 'flags', 'fls',
17
+ 'fprint', 'fprint0', 'fprintf', 'fstype', 'gid', 'group', 'ilname', 'iname', 'inum', 'ipath', 'iregex', 'iwholename', 'links', 'lname',
18
+ 'maxdepth', 'mindepth', 'mmin', 'mtime', 'name', 'newer', 'path', 'perm', 'printf', 'regex', 'regextype', 'samefile', 'size', 'type', 'uid',
19
+ 'used', 'user', 'wholename', 'xattrname', 'xtype', ...[...'aBcmt'].flatMap((x) => [...'aBcmt'].map((y) => `newer${x}${y}`)),
20
+ ].map((name) => `-${name}`);
21
+ /**
22
+ * tmux's commands that run a shell-command, read for its text (see
23
+ * TEXT_PROGRAMS): those in TMUX_COMMANDS, and display-popup (popup)
24
+ */
25
+ const TMUX_POPUP = { letters: 'bcdehsStTwxy', flags: 'BCEkN' };
26
+ const TMUX_TEXT_COMMANDS = new Map([...TMUX_COMMANDS, ['display-popup', TMUX_POPUP], ['popup', TMUX_POPUP]]
27
+ .map(([name, rules]) => [name, { ...rules, textOperands: 0, textEnds: [';'] }]));
28
+ /**
29
+ * The wrappers that are programs, with their options from each one's manual
30
+ * or --help: GNU's, BSD's and macOS's where there are several (and Windows'
31
+ * sudo), util-linux's, systemd's, OpenBSD's doas, polkit's pkexec, and the
32
+ * usage text of busybox, wsl, gsudo and psexec
33
+ */
34
+ const PROGRAMS = new Map([
35
+ ['env', {
36
+ letters: 'uCPLUa', flags: 'i0v', long: ['unset', 'chdir', 'argv0'],
37
+ longFlags: ['ignore-environment', 'null', 'debug', 'block-signal', 'default-signal', 'ignore-signal', 'list-signal-handling', 'help', 'version'],
38
+ assignments: true, texts: { letters: 'S', long: ['split-string'] },
39
+ }],
40
+ ['nohup', { longFlags: ['help', 'version'] }],
41
+ ['xargs', {
42
+ letters: 'adEIJLnPRSs', attachedLetters: 'eil', flags: '0oprtx',
43
+ long: ['arg-file', 'delimiter', 'max-args', 'max-chars', 'max-lines', 'max-procs', 'process-slot-var'],
44
+ longFlags: ['null', 'eof', 'replace', 'open-tty', 'interactive', 'no-run-if-empty', 'show-limits', 'verbose', 'exit', 'help', 'version'],
45
+ }],
46
+ ['timeout', {
47
+ letters: 'ks', flags: 'fpv', long: ['kill-after', 'signal'], longFlags: ['foreground', 'preserve-status', 'verbose', 'help', 'version'],
48
+ before: 1, noProgramWords: ['/t', '/nobreak'],
49
+ }],
50
+ ['nice', { letters: 'n', attachedLetters: '0123456789', long: ['adjustment'], longFlags: ['help', 'version'] }],
51
+ ['stdbuf', { letters: 'ioe', long: ['input', 'output', 'error'], longFlags: ['help', 'version'] }],
52
+ ['setsid', { flags: 'cfwhV', longFlags: ['ctty', 'fork', 'wait', 'help', 'version'] }],
53
+ ['chroot', { letters: 'Ggu', flags: 'n', long: ['groups', 'userspec'], longFlags: ['skip-chdir', 'help', 'version'], before: 1 }],
54
+ ['sudo', {
55
+ letters: 'aCcDghpRrTtUu', flags: 'ABbEeHiKklNnPSsVv',
56
+ long: ['auth-type', 'chdir', 'chroot', 'close-from', 'command-timeout', 'group', 'host', 'login-class', 'other-user', 'prompt', 'role', 'type', 'user'],
57
+ longFlags: [
58
+ 'askpass', 'bell', 'background', 'preserve-env', 'edit', 'set-home', 'help', 'login', 'remove-timestamp', 'reset-timestamp', 'list',
59
+ 'no-update', 'non-interactive', 'preserve-groups', 'stdin', 'shell', 'version', 'validate', 'new-window', 'disable-input', 'inline',
60
+ ],
61
+ assignments: true,
62
+ }],
63
+ ['doas', { letters: 'au', flags: 'ns', noProgram: 'CL' }],
64
+ ['pkexec', { long: ['user'], longFlags: ['keep-cwd', 'disable-internal-agent', 'help', 'version'] }],
65
+ ['busybox', { noProgramWords: ['--list', '--list-full', '--install', '--show', '--help'] }],
66
+ ['wsl', { letters: 'du', flags: 'e', long: ['cd', 'distribution', 'distribution-id', 'user', 'shell-type'], longFlags: ['exec', 'system'] }],
67
+ ['nsenter', {
68
+ letters: 'tNGS', attachedLetters: 'muinpUCTrwW', flags: 'aeFZchV', long: ['target', 'net-socket', 'setgid', 'setuid'],
69
+ longFlags: [
70
+ 'all', 'mount', 'uts', 'ipc', 'net', 'pid', 'user', 'user-parent', 'cgroup', 'time', 'keep-caps', 'preserve-credentials', 'root',
71
+ 'wd', 'wdns', 'env', 'no-fork', 'follow-context', 'join-cgroup', 'help', 'version',
72
+ ],
73
+ }],
74
+ ['unshare', {
75
+ letters: 'lRwSG', attachedLetters: 'imnpuUCT', flags: 'frchV',
76
+ long: [
77
+ 'load-interp', 'map-user', 'map-users', 'map-group', 'map-groups', 'owner', 'propagation', 'setgroups', 'root', 'wd', 'setuid',
78
+ 'setgid', 'monotonic', 'boottime', 'whitelist-env',
79
+ ],
80
+ longFlags: [
81
+ 'ipc', 'mount', 'net', 'pid', 'uts', 'user', 'cgroup', 'time', 'fork', 'forward-signals', 'keep-caps', 'kill-child', 'mount-proc',
82
+ 'mount-binfmt', 'map-auto', 'map-subids', 'map-root-user', 'map-current-user', 'clear-env', 'help', 'version',
83
+ ],
84
+ }],
85
+ ['ionice', { letters: 'cn', flags: 'thV', long: ['class', 'classdata'], longFlags: ['ignore', 'help', 'version'], noProgram: 'pPu', noProgramLong: ['pid', 'pgid', 'uid'] }],
86
+ ['taskset', { flags: 'achV', longFlags: ['all-tasks', 'cpu-list', 'help', 'version'], noProgram: 'p', noProgramLong: ['pid'], before: 1 }],
87
+ ['chrt', {
88
+ letters: 'TPDUX', flags: 'ofrbideGORavhV', long: ['sched-runtime', 'sched-period', 'sched-deadline', 'clamp-min', 'clamp-max'],
89
+ longFlags: ['other', 'fifo', 'rr', 'batch', 'idle', 'deadline', 'ext', 'reclaim-grub', 'deadline-overrun', 'reset-on-fork', 'all-tasks', 'verbose', 'help', 'version'],
90
+ noProgram: 'mp', noProgramLong: ['max', 'pid'], before: 1, beforeOptional: true,
91
+ }],
92
+ ['numactl', {
93
+ letters: 'iwmNCpP', flags: 'alb',
94
+ long: ['interleave', 'weighted-interleave', 'membind', 'cpunodebind', 'physcpubind', 'preferred', 'preferred-many', 'offset', 'shmmode', 'length'],
95
+ longFlags: ['all', 'localalloc', 'balancing', 'cpu-compress', 'huge', 'strict', 'touch', 'dump', 'dump-nodes'],
96
+ noProgram: 'sH', noProgramLong: ['show', 'hardware', 'version', 'shm', 'shmid', 'file'],
97
+ }],
98
+ ['prlimit', {
99
+ letters: 'o', attachedLetters: 'cdefilmnqrstuvxy', flags: 'hV', long: ['output'],
100
+ longFlags: [
101
+ 'noheadings', 'raw', 'verbose', 'help', 'version', 'core', 'data', 'nice', 'fsize', 'sigpending', 'memlock', 'rss', 'nofile',
102
+ 'msgqueue', 'rtprio', 'stack', 'cpu', 'nproc', 'as', 'locks', 'rttime',
103
+ ],
104
+ noProgram: 'p', noProgramLong: ['pid'],
105
+ }],
106
+ ['setpriv', {
107
+ flags: 'hV',
108
+ long: [
109
+ 'groups', 'inh-caps', 'ambient-caps', 'bounding-set', 'rgid', 'egid', 'regid', 'ruid', 'euid', 'reuid', 'securebits', 'pdeathsig',
110
+ 'ptracer', 'selinux-label', 'apparmor-profile', 'landlock-access', 'landlock-rule', 'seccomp-filter',
111
+ ],
112
+ longFlags: ['clear-groups', 'keep-groups', 'init-groups', 'nnp', 'no-new-privs', 'reset-env', 'help', 'version'],
113
+ noProgram: 'd', noProgramLong: ['dump', 'list-caps'],
114
+ }],
115
+ ['capsh', { equalsOnly: true, programOptions: { long: ['shell'], default: 'bash' } }],
116
+ ['cpulimit', {
117
+ letters: 'lcs', flags: 'bfqkmrvzh', long: ['limit', 'cpu', 'signal'],
118
+ longFlags: ['background', 'foreground', 'quiet', 'kill', 'monitor-forks', 'restore', 'verbose', 'lazy', 'help'],
119
+ noProgram: 'peP', noProgramLong: ['pid', 'exe', 'path'],
120
+ }],
121
+ ['systemd-run', {
122
+ letters: 'upEHMC', flags: 'rdRtTPSqvGh',
123
+ long: [
124
+ 'unit', 'property', 'description', 'slice', 'expand-environment', 'service-type', 'uid', 'gid', 'nice', 'working-directory',
125
+ 'root-directory', 'setenv', 'output', 'on-active', 'on-boot', 'on-startup', 'on-unit-active', 'on-unit-inactive', 'on-calendar',
126
+ 'path-property', 'socket-property', 'timer-property', 'job-mode', 'background', 'host', 'machine', 'capsule', 'json',
127
+ ],
128
+ longFlags: [
129
+ 'scope', 'slice-inherit', 'remain-after-exit', 'send-sighup', 'same-dir', 'same-root-dir', 'pty', 'pty-late', 'pipe', 'shell',
130
+ 'quiet', 'verbose', 'on-clock-change', 'on-timezone-change', 'no-block', 'wait', 'collect', 'ignore-failure', 'user', 'system',
131
+ 'no-ask-password', 'help', 'version', 'no-pager',
132
+ ],
133
+ }],
134
+ ['run0', {
135
+ letters: 'ugD', flags: 'kKinh',
136
+ long: [
137
+ 'unit', 'property', 'description', 'slice', 'user', 'group', 'nice', 'chdir', 'setenv', 'background', 'shell-prompt-prefix',
138
+ 'lightweight', 'area', 'machine',
139
+ ],
140
+ longFlags: [
141
+ 'slice-inherit', 'reset-timestamp', 'remove-timestamp', 'via-shell', 'pty', 'pty-late', 'pipe', 'empower', 'same-root-dir',
142
+ 'non-interactive', 'no-ask-password', 'help', 'version',
143
+ ],
144
+ noProgram: 'v', noProgramLong: ['validate'],
145
+ }],
146
+ ['strace', {
147
+ letters: 'eEpubIPaoOsSUX', flags: 'DfcCdhiknNqrtTvVwxyYzZAF',
148
+ long: [
149
+ 'env', 'attach', 'user', 'argv0', 'detach-on', 'interruptible', 'syscall-limit', 'trace', 'trace-fds', 'signal', 'status',
150
+ 'trace-path', 'columns', 'abbrev', 'verbose', 'raw', 'read', 'write', 'silent', 'silence', 'kvm', 'namespace',
151
+ 'stack-trace-frame-limit', 'output', 'color', 'string-limit', 'const-print-style', 'summary-syscall-overhead', 'summary-sort-by',
152
+ 'summary-columns', 'inject', 'fault',
153
+ ],
154
+ longFlags: [
155
+ 'daemonize', 'follow-forks', 'output-separately', 'kill-on-exit', 'successful-only', 'failed-only', 'quiet', 'decode-fds',
156
+ 'decode-pids', 'pidns-translation', 'instruction-pointer', 'syscall-number', 'arg-names', 'stack-trace', 'output-append-mode',
157
+ 'relative-timestamps', 'absolute-timestamps', 'timestamps', 'syscall-times', 'no-abbrev', 'strings-in-hex', 'summary-only',
158
+ 'summary', 'summary-wall-clock', 'debug', 'help', 'seccomp-bpf', 'tips', 'version', 'always-show-pid', 'secontext',
159
+ ],
160
+ }],
161
+ ['ltrace', {
162
+ letters: 'aAdDeFlnopsuwx', flags: 'bcCfhiLrStTV', long: ['align', 'max-depth', 'debug', 'config', 'library', 'indent', 'output', 'where'],
163
+ longFlags: ['no-signals', 'demangle', 'help', 'version'],
164
+ }],
165
+ ['time', { letters: 'fo', flags: 'paqvV', long: ['format', 'output'], longFlags: ['portability', 'append', 'verbose', 'quiet', 'help', 'version'] }],
166
+ ['firejail', {
167
+ equalsOnly: true, flags: 'c', noProgram: '?',
168
+ noProgramLong: [
169
+ 'list', 'tree', 'top', 'netstats', 'nettrace', 'icmptrace', 'dnstrace', 'snitrace', 'version', 'help', 'debug-caps',
170
+ 'debug-errnos', 'debug-syscalls', 'debug-syscalls32', 'debug-protocols', 'shutdown', 'bandwidth', 'ids-init', 'ids-check', 'ls',
171
+ 'get', 'put', 'cat',
172
+ ],
173
+ }],
174
+ ['bwrap', {
175
+ long: [
176
+ 'args', 'userns', 'userns2', 'pidns', 'uid', 'gid', 'hostname', 'chdir', 'unsetenv', 'lock-file', 'sync-fd', 'perms', 'size',
177
+ 'remount-ro', 'proc', 'dev', 'tmpfs', 'mqueue', 'dir', 'seccomp', 'add-seccomp-fd', 'exec-label', 'file-label', 'block-fd',
178
+ 'userns-block-fd', 'info-fd', 'json-status-fd', 'cap-add', 'cap-drop',
179
+ ],
180
+ longPairs: [
181
+ 'setenv', 'bind', 'bind-try', 'dev-bind', 'dev-bind-try', 'ro-bind', 'ro-bind-try', 'file', 'bind-data', 'ro-bind-data', 'symlink',
182
+ 'chmod',
183
+ ],
184
+ longFlags: [
185
+ 'help', 'version', 'unshare-user', 'unshare-user-try', 'unshare-ipc', 'unshare-pid', 'unshare-net', 'unshare-uts',
186
+ 'unshare-cgroup', 'unshare-cgroup-try', 'unshare-all', 'share-net', 'disable-userns', 'assert-userns-disabled', 'clearenv',
187
+ 'new-session', 'die-with-parent', 'as-pid-1',
188
+ ],
189
+ }],
190
+ ['unbuffer', { flags: 'p' }],
191
+ ['rlwrap', {
192
+ letters: 'bCDefgHlMOPqsStwz', attachedLetters: 'aAmp', flags: 'cEhiInNorRUvW',
193
+ long: [
194
+ 'break-chars', 'command-name', 'history-no-dupes', 'extra-char-after-completion', 'file', 'forget-matching', 'history-filename',
195
+ 'logfile', 'multi-line-ext', 'only-cook', 'pre-given', 'quote-characters', 'histsize', 'substitute-prompt', 'set-term-name',
196
+ 'wait-before-prompt', 'filter',
197
+ ],
198
+ longFlags: [
199
+ 'always-readline', 'ansi-colour-aware', 'complete-filenames', 'always-echo', 'help', 'case-insensitive', 'pass-sigint-as-sigterm',
200
+ 'multi-line', 'no-warnings', 'no-children', 'one-shot', 'prompt-colour', 'remember', 'renice', 'mirror-arguments', 'version', 'polling',
201
+ ],
202
+ }],
203
+ ['chpst', { letters: 'uUbe/nlLmdopfct', flags: 'vVP012' }],
204
+ ['setuidgid', { before: 1 }],
205
+ ['start-stop-daemon', {
206
+ letters: 'pnugsRcrdONPIk', flags: 'StoqbCmv',
207
+ long: [
208
+ 'pid', 'ppid', 'pidfile', 'name', 'user', 'group', 'signal', 'retry', 'chuid', 'chroot', 'chdir', 'notify-timeout', 'output',
209
+ 'nicelevel', 'procsched', 'iosched', 'umask',
210
+ ],
211
+ longFlags: ['start', 'test', 'oknodo', 'quiet', 'background', 'notify-await', 'no-close', 'make-pidfile', 'remove-pidfile', 'verbose'],
212
+ noProgram: 'KTHV', noProgramLong: ['stop', 'status', 'help', 'version'], programOptions: { letters: 'xa', long: ['exec', 'startas'] },
213
+ }],
214
+ ['caffeinate', { letters: 'tw', flags: 'dimsu' }],
215
+ ['arch', { wordOptions: true, long: ['arch', 'd', 'e'], longFlags: ['32', '64', 'i386', 'x86_64', 'x86_64h', 'arm64', 'arm64e', 'c', 'h'] }],
216
+ ['sandbox-exec', { letters: 'fnpD' }],
217
+ ['find', { programAfter: { words: ['-exec', '-execdir', '-ok', '-okdir'], ends: [';', '+'], values: FIND_VALUES } }],
218
+ ['parallel', {
219
+ letters: 'aCdEIjJnNPsLS', attachedLetters: 'eil', flags: '0kmqrtuvXx',
220
+ long: [
221
+ 'arg-file', 'arg-file-sep', 'arg-sep', 'basefile', 'bf', 'basenamereplace', 'bnr', 'basenameextensionreplace', 'bner', 'bin', 'block',
222
+ 'block-size', 'block-timeout', 'bt', 'colsep', 'combineexec', 'compress-program', 'decompress-program', 'delay', 'delimiter',
223
+ 'dirnamereplace', 'dnr', 'env', 'extensionreplace', 'er', 'filter', 'group-by', 'halt', 'halt-on-error', 'header', 'jobs',
224
+ 'max-procs', 'joblog', 'jl', 'limit', 'load', 'match', 'max-args', 'max-chars', 'max-replace-args', 'memfree', 'memsuspend',
225
+ 'milestone', 'minversion', 'nice', 'parens', 'process-slot-var', 'profile', 'recend', 'recstart', 'results', 'res', 'retries',
226
+ 'return', 'rpl', 'rsync-opts', 'sshlogin', 'sshloginfile', 'tagstring', 'timeout', 'tmpdir', 'workdir', 'wd',
227
+ ],
228
+ longFlags: [
229
+ 'eof', 'max-lines', 'keep-order', 'tag', 'dry-run', 'pipe', 'group', 'ungroup', 'line-buffer', 'progress', 'eta', 'bar', 'verbose',
230
+ 'null', 'quote', 'no-run-if-empty', 'shuf', 'tty', 'xargs', 'cleanup', 'transfer', 'help', 'version',
231
+ ],
232
+ }],
233
+ ['xterm', {
234
+ wordOptions: true, plus: true,
235
+ long: [
236
+ 'b', 'bcf', 'bcn', 'bd', 'bg', 'bw', 'cc', 'class', 'cr', 'display', 'en', 'fa', 'fb', 'fc', 'fd', 'fg', 'fi', 'fn', 'font', 'fs', 'fw',
237
+ 'fwb', 'fx', 'geometry', 'hc', 'into', 'kt', 'lcc', 'lf', 'mc', 'ms', 'n', 'name', 'nb', 'pf', 'selbg', 'selfg', 'sh', 'sl', 'ti',
238
+ 'title', 'tm', 'tn', 'T', 'w', 'xrm', 'ziconbeep', 'baudrate',
239
+ ],
240
+ longFlags: [
241
+ 'e', 'ah', 'aw', 'bc', 'cb', 'cjk_width', 'cm', 'cn', 'cu', 'dc', 'fbb', 'fbx', 'fullscreen', 'hf', 'hm', 'hold', 'ie', 'im', 'itc',
242
+ 'j', 'k8', 'l', 'lc', 'leftbar', 'ls', 'maximized', 'mb', 'mesg', 'mk_width', 'nul', 'pc', 'pob', 'rightbar', 'rv', 'rvc', 'rw', 's',
243
+ 'samename', 'sb', 'sf', 'si', 'sk', 'sm', 'sp', 't', 'tb', 'toolbar', 'u8', 'ulc', 'ulit', 'ut', 'vb', 'wc', 'wf', 'iconic',
244
+ 'reverse', 'help', 'version',
245
+ ],
246
+ }],
247
+ ['tmux', { letters: 'cfLST', flags: '2CDhlNuVv', subcommands: TMUX_COMMANDS }],
248
+ ['screen', { letters: 'cehpsStT', flags: 'aAdDfiLlmOPqRU', noProgram: 'rxXQv', noProgramWords: ['-ls', '-list', '-wipe'] }],
249
+ ['gsudo', {
250
+ letters: 'ui', flags: 'nwskd', long: ['user', 'integrity', 'loglevel', 'chdir'],
251
+ longFlags: ['new', 'wait', 'keepShell', 'keepWindow', 'system', 'ti', 'direct', 'loadProfile', 'debug', 'copyns', 'copyev'],
252
+ }],
253
+ ['psexec', {
254
+ wordOptions: true, long: ['u', 'p', 'n', 'r', 'w', 'a', 'g'],
255
+ longFlags: [
256
+ 's', 'e', 'h', 'l', 'x', 'c', 'f', 'v', 'd', 'accepteula', 'nobanner', 'low', 'belownormal', 'abovenormal', 'high', 'realtime',
257
+ 'background',
258
+ ],
259
+ remote: ['\\\\', '@'],
260
+ }],
261
+ ]);
262
+ /** The POSIX shells' own commands that start a program */
263
+ const POSIX_SHELL_COMMANDS = new Map([
264
+ ['exec', { letters: 'a', flags: 'cl' }],
265
+ ['command', { flags: 'p', noProgram: 'vV' }],
266
+ ]);
267
+ /** fish's commands that start the command after them */
268
+ const FISH_COMMANDS = new Map([
269
+ ['and', {}],
270
+ ['or', {}],
271
+ ['not', {}],
272
+ ]);
273
+ /**
274
+ * How a POSIX shell reads its own options, for shellRuns(): bash's, from bash
275
+ * 5.3's --help and bash(1), for every shell but fish (sh, dash, zsh and ksh
276
+ * have the same -c, -s, -o and +o), and fish's, from fish(1). bash's -c makes
277
+ * the first word after the options the command text, and its other words are
278
+ * the command's $0, $1 and so on; fish's -c and -C (--init-command) take the
279
+ * command text as their value, and fish runs -C's before the rest.
280
+ */
281
+ const BASH_OPTIONS = {
282
+ letters: 'oO', flags: 'abcefhiklmnprstuvxBCDEHPT', long: ['init-file', 'rcfile'],
283
+ longFlags: [
284
+ 'debug', 'debugger', 'dump-po-strings', 'dump-strings', 'help', 'login', 'noediting', 'noprofile', 'norc', 'posix',
285
+ 'pretty-print', 'protected', 'restricted', 'verbose', 'version', 'wordexp',
286
+ ],
287
+ plus: true, groupValues: 'words', operandRoles: { c: 'text', s: 'arguments' },
288
+ };
289
+ const FISH_OPTIONS = {
290
+ letters: 'dfop', flags: 'hilnNPv', long: ['debug', 'debug-output', 'features', 'profile', 'profile-startup'],
291
+ longFlags: ['help', 'interactive', 'login', 'no-config', 'no-execute', 'print-debug-categories', 'print-rusage-self', 'private', 'version'],
292
+ texts: { letters: 'cC', long: ['command', 'init-command'] }, optionsAfterTexts: true,
293
+ operandRoles: { c: 'arguments', command: 'arguments' },
294
+ };
295
+ /**
296
+ * The programs that run one command text in a shell, as bash -c does, with
297
+ * the shell that reads it: shellRuns() gives their texts to the check. Their
298
+ * options are from their --help on Debian 12 (util-linux's su, runuser,
299
+ * script and flock, procps' watch, sg from login) and from Windows' runas /? help;
300
+ * wsl's, tmux's and parallel's are their rows in PROGRAMS, and display-popup's
301
+ * are from OpenBSD's tmux(1).
302
+ * - su, runuser and script run the text of -c (--command) in the user's
303
+ * shell, and -c can come after the user or the file too; runuser -u runs
304
+ * the program after the user directly, without reading it as a shell text;
305
+ * - sg runs its command with sh -c, given with -c or not, after its group;
306
+ * - flock runs -c's text with sh -c, or the program after the lock file;
307
+ * - watch runs its words with sh -c;
308
+ * - runas runs its quoted command line, which is read as cmd reads one;
309
+ * - wsl without --exec gives its words to the Linux shell as one command line;
310
+ * - tmux runs -c's text in the user's shell, and the shell-command of new,
311
+ * split-window, respawn-pane, display-popup and the like with sh -c when it
312
+ * is one word (tmux new 'sudo ls'), the program after their options otherwise;
313
+ * - parallel runs its command line with a shell, once for each argument after
314
+ * :::, and without a command each of those arguments is a command.
315
+ */
316
+ const TEXT_PROGRAMS = new Map([
317
+ ['su', { shell: 'sh', rules: {
318
+ letters: 'gGsw', flags: 'flmpP', long: ['group', 'supp-group', 'shell', 'whitelist-environment'],
319
+ longFlags: ['fast', 'login', 'preserve-environment', 'pty', 'help', 'version'],
320
+ texts: { letters: 'c', long: ['command', 'session-command'] },
321
+ optionsAfterTexts: true, permute: true, shellArgumentsAfter: 1,
322
+ } }],
323
+ ['runuser', { shell: 'sh', rules: {
324
+ letters: 'gGswu', flags: 'flmpP', long: ['group', 'supp-group', 'shell', 'whitelist-environment', 'user'],
325
+ longFlags: ['fast', 'login', 'preserve-environment', 'pty', 'help', 'version'],
326
+ texts: { letters: 'c', long: ['command', 'session-command'] },
327
+ optionsAfterTexts: true, permute: true, shellArgumentsAfter: 1,
328
+ operandRoles: { u: 'program', user: 'program' },
329
+ } }],
330
+ ['sg', { shell: 'sh', rules: { texts: { letters: 'c', long: [] }, optionsAfterTexts: true, permute: true, textOperands: 1 } }],
331
+ ['script', { shell: 'sh', rules: {
332
+ letters: 'IOBTmEo', attachedLetters: 't', flags: 'aefq',
333
+ long: ['log-in', 'log-out', 'log-io', 'log-timing', 'logging-format', 'echo', 'output-limit'],
334
+ longFlags: ['timing', 'append', 'return', 'flush', 'force', 'quiet', 'help', 'version'],
335
+ texts: { letters: 'c', long: ['command'] }, optionsAfterTexts: true, permute: true,
336
+ } }],
337
+ ['flock', { shell: 'sh', rules: {
338
+ letters: 'wE', flags: 'sxunoF', long: ['timeout', 'conflict-exit-code'],
339
+ longFlags: ['shared', 'exclusive', 'unlock', 'nonblock', 'close', 'no-fork', 'verbose', 'help', 'version'],
340
+ texts: { letters: 'c', long: ['command'] }, optionsAfterTexts: true, permute: true, textOperands: 1,
341
+ } }],
342
+ ['watch', { shell: 'sh', rules: {
343
+ letters: 'qn', attachedLetters: 'd', flags: 'bcegptwx', long: ['equexit', 'interval'],
344
+ longFlags: ['beep', 'color', 'differences', 'errexit', 'chgexit', 'precise', 'no-title', 'no-wrap', 'exec', 'help', 'version'],
345
+ textOperands: 0,
346
+ } }],
347
+ ['runas', { shell: 'cmd', rules: { slash: true, textOperands: 0 } }],
348
+ ['wsl', { shell: 'sh', rules: { ...PROGRAMS.get('wsl'), textOperands: 0, operandRoles: { e: 'arguments', exec: 'arguments' } } }],
349
+ ['tmux', { shell: 'sh', rules: { ...PROGRAMS.get('tmux'), texts: { letters: 'c', long: [] }, subcommands: TMUX_TEXT_COMMANDS, separator: ';' } }],
350
+ ['parallel', { shell: 'sh', rules: {
351
+ ...PROGRAMS.get('parallel'), textOperands: 0, textEnds: [':::', ':::+', '::::', '::::+'], commandArguments: [':::', ':::+'],
352
+ commandFiles: ['::::', '::::+'],
353
+ } }],
354
+ ]);
355
+ /**
356
+ * The programs that run one command text in the shell they were started
357
+ * from, as eval does: gsudo 'net user' runs net there (gsudo's README).
358
+ * sameShellTexts() gives their texts to the check.
359
+ */
360
+ const SAME_SHELL_PROGRAMS = new Map([
361
+ ['gsudo', { ...PROGRAMS.get('gsudo'), textOperands: 0 }],
362
+ ]);
363
+ /** cmd's start switches that take the next word as their value (/D also takes it in the same word: /Dpath) */
364
+ const CMD_START_VALUE_SWITCHES = ['/d', '/node', '/affinity', '/machine'];
365
+ /**
366
+ * The commands that run in `shell`: each of `commands`, followed by the
367
+ * programs that the wrappers among them start (for env sudo ls: env, then
368
+ * sudo). A started program has its wrapper's start.
369
+ */
370
+ export function withStartedPrograms(commands, shell) {
371
+ const running = [];
372
+ // Each program once: readings of nested wrappers reach the same one many ways (find . -exec find . -exec … echo
373
+ // finds each level's program from every level before it), and another copy adds no answer
374
+ const seen = new Set();
375
+ const add = (command) => {
376
+ if (command.nameAtRunTime)
377
+ requireCompleteArguments(command);
378
+ const key = JSON.stringify([command.start, command.words, command.written, command.argumentError]);
379
+ if (seen.has(key))
380
+ return;
381
+ seen.add(key);
382
+ running.push(command);
383
+ if (command.nameAtRunTime)
384
+ return;
385
+ for (const { words, written, wordTexts, argumentError } of startedPrograms(command, shell)) {
386
+ add({ name: words[0] ?? written[0], words, written, wordTexts, start: command.start,
387
+ nameAtRunTime: words[0] === null, ...(argumentError === undefined ? {} : { argumentError }) });
388
+ }
389
+ };
390
+ commands.forEach(add);
391
+ return running;
392
+ }
393
+ /** The programs a command starts when it is a wrapper: none for any other command */
394
+ function startedPrograms(command, shell) {
395
+ const shellType = getShellType(shell);
396
+ const name = programName(command.name, shellType);
397
+ const { words, written, wordTexts } = command;
398
+ const from = (at) => ({ words: words.slice(at), written: written.slice(at),
399
+ wordTexts: wordTexts.slice(at),
400
+ ...(command.argumentError === undefined ? {} : { argumentError: command.argumentError }) });
401
+ // runuser -u starts the program and its arguments directly, without a shell's text parsing.
402
+ if (name === 'runuser') {
403
+ requireCompleteArguments(command);
404
+ const readings = readOptions(words, TEXT_PROGRAMS.get(name).rules);
405
+ return readings.programs.flatMap(({ at }) => at === undefined ? [] : [from(at)]);
406
+ }
407
+ const posix = PROGRAMS.get(name)
408
+ ?? (shellType === 'posix' ? POSIX_SHELL_COMMANDS.get(name) : undefined)
409
+ ?? (programName(shell, shellType) === 'fish' ? FISH_COMMANDS.get(name) : undefined);
410
+ if (posix) {
411
+ requireCompleteArguments(command);
412
+ return posixPrograms(command, posix);
413
+ }
414
+ // Its own arguments are in -ArgumentList, a text the check doesn't read, so a program Start-Process starts has only its name
415
+ if (shellType === 'powershell' && name === 'start-process') {
416
+ requireCompleteArguments(command);
417
+ return (command.filePaths ?? []).map(({ word, written }) => ({
418
+ words: [word], written: [written], wordTexts: [word ?? written],
419
+ ...(command.argumentError === undefined ? {} : { argumentError: command.argumentError }),
420
+ }));
421
+ }
422
+ if (shellType === 'cmd' && name === 'start') {
423
+ requireCompleteArguments(command);
424
+ return cmdStartProgramsAt(command).map(from);
425
+ }
426
+ if (shellType === 'cmd' && name === 'call') {
427
+ requireCompleteArguments(command);
428
+ return words.length > 1 ? [from(1)] : [];
429
+ }
430
+ return [];
431
+ }
432
+ /**
433
+ * The programs a POSIX wrapper starts: its words from each place the program
434
+ * can be. env -S puts the words of its text in its own place and reads them as
435
+ * env's words, followed by the words after the text (env -S ls sudo runs ls).
436
+ */
437
+ function posixPrograms({ words, written, wordTexts, argumentError }, rules) {
438
+ // Windows' timeout /t 5 only waits, and GNU's timeout stops with an error at /t, which is no duration
439
+ const first = words[1];
440
+ if (first && rules.noProgramWords?.includes(first.toLowerCase()))
441
+ return [];
442
+ const from = (i, end = words.length) => ({ words: words.slice(i, end),
443
+ written: written.slice(i, end), wordTexts: wordTexts.slice(i, end),
444
+ ...(argumentError === undefined ? {} : { argumentError }) });
445
+ const after = rules.programAfter;
446
+ if (after) {
447
+ // find -exec sudo rm {} ;: each program runs from the word after -exec up to ;. A word known only at run time
448
+ // where -exec could be may be -exec (find . $ACT sudo {} ;), or -exec and its program, known only at run time;
449
+ // a value (find -name "$NAME") and a word in an -exec's command (-exec grep "$PATTERN" {} ;) are neither
450
+ const programs = [];
451
+ let commandEnd = 0;
452
+ for (let i = 1; i < words.length; i++) {
453
+ const word = words[i];
454
+ if (word !== null && !after.words.includes(word)) {
455
+ if (i >= commandEnd && after.values.includes(word))
456
+ i++;
457
+ continue;
458
+ }
459
+ if (word === null && i < commandEnd)
460
+ continue;
461
+ const end = words.findIndex((next, j) => j > i && next !== null && after.ends.includes(next));
462
+ const stop = end === -1 ? words.length : end;
463
+ if (word === null)
464
+ programs.push(from(i, stop));
465
+ else
466
+ commandEnd = Math.max(commandEnd, stop);
467
+ if (stop > i + 1)
468
+ programs.push(from(i + 1, stop));
469
+ }
470
+ return programs;
471
+ }
472
+ const { operands, texts, programs: named } = readOptions(words, rules);
473
+ if (rules.programOptions) {
474
+ // The program an option names, or the one that runs without it, takes the words after -- as its arguments
475
+ const end = words.indexOf('--');
476
+ const args = end === -1 ? words.length : end + 1;
477
+ const fallback = rules.programOptions.default;
478
+ const runs = named.length > 0 ? named : end !== -1 && fallback ? [{ program: fallback }] : [];
479
+ return runs.map(({ program, at }) => ({
480
+ words: [program, ...words.slice(args)],
481
+ written: [at === undefined ? program ?? '' : written[at], ...written.slice(args)],
482
+ wordTexts: [at === undefined ? program ?? '' : wordTexts[at], ...wordTexts.slice(args)],
483
+ ...(argumentError === undefined ? {} : { argumentError }),
484
+ }));
485
+ }
486
+ // psexec \\server sudo ls runs sudo on another computer
487
+ const remote = (i) => words.slice(1, i + 1).some((word) => rules.remote?.some((start) => word?.startsWith(start)));
488
+ const at = new Set();
489
+ for (let i of operands) {
490
+ // After the options: the NAME=VALUE settings, then the words before the program, which chrt may leave out. A word
491
+ // known only at run time whose = is only in an expansion may be no setting but the program (env "${TOOL:=sudo}")
492
+ while (rules.assignments && i < words.length && (words[i] ?? written[i]).includes('=')) {
493
+ if (words[i] === null && !hasWrittenEquals(written[i]) && !remote(i))
494
+ at.add(i);
495
+ i++;
496
+ }
497
+ if (rules.beforeOptional && i < words.length)
498
+ at.add(i);
499
+ i += rules.before ?? 0;
500
+ if (i < words.length && !remote(i))
501
+ at.add(i);
502
+ }
503
+ // A command of the program's own, such as tmux new-session, reads its words by its own rules
504
+ const programs = [...at].flatMap((i) => {
505
+ const subcommand = subcommandOf(words[i], rules);
506
+ return subcommand ? posixPrograms(from(i), subcommand) : [from(i)];
507
+ });
508
+ // A wrapper's command text is more of its own words, split as env splits -S's: env is the one wrapper with one.
509
+ // One known only at run time is read on as a word known only at run time (see readOptions)
510
+ return [...programs, ...texts.flatMap(({ text, after }) => {
511
+ if (text === null)
512
+ return [];
513
+ const split = envSplitWords(text);
514
+ return posixPrograms({
515
+ words: [words[0], ...split.words, ...words.slice(after)],
516
+ written: [written[0], ...split.written, ...written.slice(after)],
517
+ wordTexts: [wordTexts[0], ...split.wordTexts, ...wordTexts.slice(after)],
518
+ ...(argumentError === undefined ? {} : { argumentError }),
519
+ }, rules);
520
+ })];
521
+ }
522
+ /**
523
+ * Whether a word as written has an = outside its expansions ($X, ${…}, $(…), `…`, cmd's %X%), so that its value
524
+ * has one whatever they give: env "FOO=$BAR" sets FOO
525
+ */
526
+ function hasWrittenEquals(written) {
527
+ let depth = 0;
528
+ for (let i = 0; i < written.length; i++) {
529
+ const char = written[i];
530
+ if (char === '\\') {
531
+ i++;
532
+ if (depth === 0 && written[i] === '=')
533
+ return true;
534
+ }
535
+ else if (char === "'" && depth === 0) {
536
+ const close = written.indexOf("'", i + 1);
537
+ if (close === -1)
538
+ return false;
539
+ if (written.slice(i + 1, close).includes('='))
540
+ return true;
541
+ i = close;
542
+ }
543
+ else if (char === '`' || (char === '%' && depth === 0)) {
544
+ const close = written.indexOf(char, i + 1);
545
+ if (close !== -1)
546
+ i = close;
547
+ }
548
+ else if (char === '$' && (written[i + 1] === '{' || written[i + 1] === '(')) {
549
+ depth++;
550
+ i++;
551
+ }
552
+ else if (depth > 0 && (char === '{' || char === '(')) {
553
+ depth++;
554
+ }
555
+ else if (depth > 0 && (char === '}' || char === ')')) {
556
+ depth--;
557
+ }
558
+ else if (char === '=' && depth === 0) {
559
+ return true;
560
+ }
561
+ }
562
+ return false;
563
+ }
564
+ /** How a POSIX shell, by its name in POSIX_SHELLS, reads its own options (see BASH_OPTIONS) */
565
+ export function shellOptionReadings(program, words) {
566
+ return readOptions(words, program === 'fish' ? FISH_OPTIONS : BASH_OPTIONS);
567
+ }
568
+ /**
569
+ * For a program that runs one command text in a shell (see TEXT_PROGRAMS): its
570
+ * options read in every way, and the shell that reads its texts. Undefined for
571
+ * any other program.
572
+ */
573
+ export function textProgramReadings(program, words, inspection = {}) {
574
+ const found = TEXT_PROGRAMS.get(program);
575
+ if (!found)
576
+ return undefined;
577
+ requireCompleteArguments(inspection);
578
+ const readings = readOptions(words, found.rules);
579
+ // A command of the program's own reads its words by its own rules (tmux new 'sudo ls'), and so does each one
580
+ // after a separator (tmux new -d \; new-window 'sudo ls')
581
+ const first = Math.min(words.length, ...readings.operands);
582
+ const separated = words.flatMap((word, j) => (j > first && word !== null && word === found.rules.separator ? [j + 1] : []));
583
+ for (const at of new Set([...readings.operands, ...separated])) {
584
+ const subcommand = subcommandOf(words[at], found.rules);
585
+ if (!subcommand)
586
+ continue;
587
+ const own = readOptions(words.slice(at), subcommand);
588
+ readings.hidden || (readings.hidden = own.hidden);
589
+ readings.texts.push(...own.texts.map((text) => ({
590
+ ...text, after: text.after + at, ...(text.at === undefined ? {} : { at: text.at + at }), ...(text.to === undefined ? {} : { to: text.to + at }),
591
+ })));
592
+ }
593
+ const argumentsAfter = found.rules.shellArgumentsAfter;
594
+ const argumentsAt = argumentsAfter === undefined ? {} : {
595
+ arguments: [...new Set(readings.operands)].sort((a, b) => a - b).slice(argumentsAfter),
596
+ };
597
+ return { readings, shell: found.shell, ...argumentsAt };
598
+ }
599
+ /** For a program that runs one command text in the shell it was started from (see SAME_SHELL_PROGRAMS): its options read in every way */
600
+ export function sameShellProgramReadings(program, words, inspection = {}) {
601
+ const rules = SAME_SHELL_PROGRAMS.get(program);
602
+ if (!rules)
603
+ return undefined;
604
+ requireCompleteArguments(inspection);
605
+ return readOptions(words, rules);
606
+ }
607
+ /**
608
+ * Reads a program's options by its rules, in every way they can be read: an
609
+ * option the rules don't list, and a word known only at run time, may take the
610
+ * next word as its value or not, though not a word that is an option itself.
611
+ * A wrapper's command text known only at run time (env -S "$CMD") is read on
612
+ * as a word known only at run time. For a shell, each reading also knows what
613
+ * the words after its options are (bash -c makes the first one the text).
614
+ */
615
+ function readOptions(words, rules) {
616
+ const readings = { operands: [], texts: [], programs: [], hidden: false };
617
+ const read = new Set();
618
+ const isOption = (word) => typeof word === 'string' && (word.startsWith('-') || (rules.plus === true && word.length > 1 && word.startsWith('+'))
619
+ || (rules.slash === true && word.length > 1 && word.startsWith('/')));
620
+ // A word after the options, the `count`th of them, by what the options before it made it. True when the
621
+ // options can go on after it (permute)
622
+ const operand = (i, role, count) => {
623
+ if (role === 'text') {
624
+ if (i < words.length)
625
+ readings.texts.push({ text: words[i], at: i, after: i + 1 });
626
+ return false;
627
+ }
628
+ if (role === 'program') {
629
+ if (i < words.length)
630
+ readings.programs.push({ program: words[i], at: i });
631
+ return false;
632
+ }
633
+ if (role === 'arguments')
634
+ return false;
635
+ if (count === rules.textOperands) {
636
+ // The text goes on to the end, or to a word that ends it (parallel's :::)
637
+ const end = (from) => {
638
+ const found = words.findIndex((word, j) => j >= from && word !== null && rules.textEnds?.includes(word));
639
+ return found === -1 ? words.length : found;
640
+ };
641
+ const to = end(i);
642
+ if (to > i) {
643
+ const text = words.slice(i, to);
644
+ readings.texts.push({ text: text.includes(null) ? null : text.join(' '), at: i, to, after: to });
645
+ return false;
646
+ }
647
+ // With no text before them, each argument after parallel's ::: is a command of its own, and those in a ::::
648
+ // file or in its input, when it is given no arguments, can't be seen
649
+ words.forEach((word, j) => {
650
+ if (j < i || word === null || !rules.commandArguments?.includes(word))
651
+ return;
652
+ for (let k = j + 1; k < end(j + 1); k++)
653
+ readings.texts.push({ text: words[k], at: k, after: k + 1 });
654
+ });
655
+ const after = words.slice(i).filter((word) => word !== null);
656
+ if (rules.commandFiles && (after.some((word) => rules.commandFiles?.includes(word)) || !after.some((word) => rules.textEnds?.includes(word)))) {
657
+ readings.hidden = true;
658
+ }
659
+ return false;
660
+ }
661
+ readings.operands.push(i);
662
+ return rules.permute === true;
663
+ };
664
+ const readFrom = (i, role, count = 0) => {
665
+ const key = `${i} ${role ?? ''} ${count}`;
666
+ if (read.has(key))
667
+ return;
668
+ read.add(key);
669
+ const word = words[i];
670
+ if (word === null) {
671
+ // An option with or without a value, or the first word after them
672
+ if (operand(i, role, count))
673
+ readFrom(i + 1, role, count + 1);
674
+ readFrom(i + 1, role, count);
675
+ const next = words[i + 1];
676
+ if (isOption(next))
677
+ return;
678
+ readFrom(i + 2, role, count);
679
+ // Or an option that gives the command text: its value (fish $X 'sudo ls', su $OPTS 'sudo ls'), or the first
680
+ // word after the options (bash $X 'sudo ls')
681
+ if (next !== undefined && rules.texts) {
682
+ readings.texts.push({ text: next, at: i + 1, after: i + 2 });
683
+ if (rules.optionsAfterTexts)
684
+ readFrom(i + 2, role, count);
685
+ }
686
+ if (Object.values(rules.operandRoles ?? {}).includes('text'))
687
+ readFrom(i + 1, 'text', count);
688
+ if (Object.values(rules.operandRoles ?? {}).includes('program'))
689
+ readFrom(i + 1, 'program', count);
690
+ return;
691
+ }
692
+ if (!isOption(word)) {
693
+ if (word !== undefined && operand(i, role, count))
694
+ readFrom(i + 1, role, count + 1);
695
+ else if (word === undefined)
696
+ operand(i, role, count);
697
+ return;
698
+ }
699
+ if (word === '--') {
700
+ // Every word after -- is one after the options
701
+ for (let j = i + 1, n = count; operand(j, role, n) && j < words.length; j++, n++)
702
+ ;
703
+ return;
704
+ }
705
+ for (const reading of optionReadings(word, rules)) {
706
+ if (reading === null)
707
+ continue;
708
+ // A value the rules don't know of isn't a word that is an option itself
709
+ if (reading.uncertain && reading.next > 0 && isOption(words[i + reading.next]))
710
+ continue;
711
+ const next = reading.role === 'text' || role === 'text' ? 'text' : reading.role ?? role;
712
+ if (reading.program !== undefined) {
713
+ const at = reading.next === 1 ? i + 1 : undefined;
714
+ const program = at === undefined ? reading.program : words[at];
715
+ if (program !== undefined)
716
+ readings.programs.push({ program, at });
717
+ readFrom(i + 1 + reading.next, next, count);
718
+ continue;
719
+ }
720
+ if (reading.text === undefined) {
721
+ readFrom(i + 1 + reading.next, next, count);
722
+ continue;
723
+ }
724
+ const at = reading.next === 1 ? i + 1 : undefined;
725
+ const text = at === undefined ? reading.text : words[at];
726
+ if (text === undefined)
727
+ continue;
728
+ readings.texts.push({ text, at, after: i + 1 + reading.next });
729
+ if (rules.optionsAfterTexts)
730
+ readFrom(i + 1 + reading.next, next, count);
731
+ else if (text === null)
732
+ readFrom(i + 1, role, count);
733
+ }
734
+ };
735
+ readFrom(1);
736
+ return readings;
737
+ }
738
+ /**
739
+ * The ways to read an option word, null for one with which no program runs.
740
+ * An option that takes a value takes the rest of the word (-uroot,
741
+ * --user=root), or the next word when the rest is empty. One the rules don't
742
+ * list may take a value or not, so it has both readings. A lone - is an
743
+ * option too: env's -i.
744
+ */
745
+ function optionReadings(option, rules) {
746
+ // A switch keeps its value in its own word (runas /user:admin)
747
+ if (rules.slash && option.startsWith('/'))
748
+ return [{ next: 0 }];
749
+ let long;
750
+ if (option.startsWith('--'))
751
+ long = option.slice(2);
752
+ else if (rules.wordOptions)
753
+ long = option.slice(1);
754
+ if (long !== undefined) {
755
+ const equals = long.indexOf('=');
756
+ const name = longOption(equals === -1 ? long : long.slice(0, equals), rules);
757
+ if (name !== undefined && rules.noProgramLong?.includes(name))
758
+ return [null];
759
+ const isText = name !== undefined && rules.texts?.long.includes(name);
760
+ const isProgram = name !== undefined && rules.programOptions?.long.includes(name);
761
+ const role = name === undefined ? undefined : rules.operandRoles?.[name];
762
+ const value = long.slice(equals + 1);
763
+ if (equals !== -1) {
764
+ if (isText)
765
+ return [{ next: 0, text: value, role }];
766
+ if (isProgram)
767
+ return [{ next: 0, program: value }];
768
+ return [{ next: 0, role }];
769
+ }
770
+ if (rules.equalsOnly)
771
+ return [{ next: 0, role }];
772
+ if (name === undefined)
773
+ return [{ next: 0 }, { next: 1, uncertain: true }];
774
+ if (isText)
775
+ return [{ next: 1, text: '', role }];
776
+ if (isProgram)
777
+ return [{ next: 1, program: '' }];
778
+ if (rules.longPairs?.includes(name))
779
+ return [{ next: 2, role }];
780
+ if (rules.long?.includes(name))
781
+ return [{ next: 1, role }];
782
+ return [{ next: 0, role }];
783
+ }
784
+ if (rules.groupValues === 'words')
785
+ return groupWordReadings(option, rules);
786
+ const readings = [];
787
+ let role;
788
+ for (let i = 1; i < option.length; i++) {
789
+ const letter = option[i];
790
+ role = role === 'text' ? role : rules.operandRoles?.[letter] ?? role;
791
+ const value = i === option.length - 1 ? { next: 1, role } : { next: 0, role };
792
+ if (rules.noProgram?.includes(letter))
793
+ return [...readings, null];
794
+ if (rules.texts?.letters.includes(letter))
795
+ return [...readings, { ...value, text: option.slice(i + 1) }];
796
+ if (rules.programOptions?.letters?.includes(letter))
797
+ return [...readings, { ...value, program: option.slice(i + 1) }];
798
+ if (rules.attachedLetters?.includes(letter))
799
+ return [...readings, { next: 0, role }];
800
+ if (rules.letters?.includes(letter))
801
+ return [...readings, value];
802
+ // An option the rules don't list may take a value, and the next letters read on as if it takes none
803
+ if (!rules.flags?.includes(letter))
804
+ readings.push({ ...value, uncertain: true });
805
+ }
806
+ return [...readings, { next: 0, role }];
807
+ }
808
+ /**
809
+ * The ways to read a group of letters as bash reads it: each letter that
810
+ * takes a value takes one of the words after the group, in order (bash -euo
811
+ * pipefail deploy.sh), and one the rules don't list may take one too.
812
+ */
813
+ function groupWordReadings(option, rules) {
814
+ let values = 0;
815
+ let unlisted = 0;
816
+ let role;
817
+ for (const letter of option.slice(1)) {
818
+ if (rules.noProgram?.includes(letter))
819
+ return [null];
820
+ role = role === 'text' ? role : rules.operandRoles?.[letter] ?? role;
821
+ if (rules.letters?.includes(letter))
822
+ values++;
823
+ else if (!rules.flags?.includes(letter))
824
+ unlisted++;
825
+ }
826
+ return Array.from({ length: unlisted + 1 }, (_, taken) => ({
827
+ next: values + taken, role, ...(taken > 0 ? { uncertain: true } : {}),
828
+ }));
829
+ }
830
+ /** The long option a name means: the one it names, or the only one it shortens */
831
+ function longOption(name, rules) {
832
+ const long = [
833
+ ...rules.long ?? [], ...rules.longPairs ?? [], ...rules.longFlags ?? [], ...rules.noProgramLong ?? [],
834
+ ...rules.texts?.long ?? [], ...rules.programOptions?.long ?? [],
835
+ ];
836
+ if (long.includes(name))
837
+ return name;
838
+ // firejail and capsh know their long options only in full
839
+ if (rules.equalsOnly)
840
+ return undefined;
841
+ const shortened = long.filter((known) => known.startsWith(name));
842
+ return shortened.length === 1 ? shortened[0] : undefined;
843
+ }
844
+ /** The command of the program's own that a word names: the one it names, or the one it shortens (tmux new-s) */
845
+ function subcommandOf(word, rules) {
846
+ if (!word || !rules.subcommands)
847
+ return undefined;
848
+ const named = rules.subcommands.get(word);
849
+ if (named)
850
+ return named;
851
+ const shortened = new Set([...rules.subcommands].filter(([name]) => name.startsWith(word)).map(([, subcommand]) => subcommand));
852
+ return shortened.size === 1 ? [...shortened][0] : undefined;
853
+ }
854
+ /** What a backslash escape in env -S's text gives, besides the character after the backslash */
855
+ const ENV_ESCAPES = { f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', _: ' ' };
856
+ /**
857
+ * The words env makes of -S's text, as GNU's and BSD's env split it: spaces,
858
+ * tabs and \_ between words; '…' and "…" keep a word together, and in '…'
859
+ * only \\ and \' are escapes; a backslash escape gives its character (\t a
860
+ * tab, \_ a space inside "…"), and \c ends the text; a # that starts a word
861
+ * starts a comment; and env fills in ${NAME} at run time, so its word is known
862
+ * only then. Where env would stop with an error, nothing runs, so the text is
863
+ * read as well as it can be.
864
+ */
865
+ function envSplitWords(text) {
866
+ const split = { words: [], written: [], wordTexts: [] };
867
+ // The word being read: undefined between words, null when known only at run time
868
+ let word;
869
+ // Its text, with ${NAME} as written
870
+ let wordText = '';
871
+ let start = 0;
872
+ let quote = '';
873
+ const add = (chars, at, asText = chars ?? '') => {
874
+ if (word === undefined) {
875
+ word = '';
876
+ wordText = '';
877
+ start = at;
878
+ }
879
+ word = word === null || chars === null ? null : word + chars;
880
+ wordText += asText;
881
+ };
882
+ const end = (at) => {
883
+ if (word === undefined)
884
+ return;
885
+ split.words.push(word);
886
+ split.written.push(text.slice(start, at));
887
+ split.wordTexts.push(wordText);
888
+ word = undefined;
889
+ };
890
+ for (let i = 0; i < text.length; i++) {
891
+ const char = text[i];
892
+ if (quote === "'") {
893
+ if (char === "'")
894
+ quote = '';
895
+ else if (char === '\\' && (text[i + 1] === '\\' || text[i + 1] === "'"))
896
+ add(text[++i], i - 1);
897
+ else
898
+ add(char, i);
899
+ continue;
900
+ }
901
+ if (char === '\\') {
902
+ const escaped = text[++i];
903
+ if (escaped === undefined || escaped === 'c') {
904
+ end(i - 1);
905
+ return split;
906
+ }
907
+ if (escaped === '_' && !quote)
908
+ end(i - 1);
909
+ else
910
+ add(ENV_ESCAPES[escaped] ?? escaped, i - 1);
911
+ continue;
912
+ }
913
+ if (char === quote) {
914
+ quote = '';
915
+ continue;
916
+ }
917
+ if (!quote && (char === '"' || char === "'")) {
918
+ quote = char;
919
+ add('', i);
920
+ continue;
921
+ }
922
+ const close = char === '$' && text[i + 1] === '{' ? text.indexOf('}', i) : -1;
923
+ if (close !== -1) {
924
+ add(null, i, text.slice(i, close + 1));
925
+ i = close;
926
+ continue;
927
+ }
928
+ if (!quote && ' \t\n\v\f\r'.includes(char)) {
929
+ end(i);
930
+ continue;
931
+ }
932
+ // A comment, to the end of the text
933
+ if (!quote && char === '#' && word === undefined)
934
+ break;
935
+ add(char, i);
936
+ }
937
+ end(text.length);
938
+ return split;
939
+ }
940
+ /**
941
+ * Where the program cmd's start starts can be: after its switches and its
942
+ * window title, the first word in quotes. A word with %VAR% in it may be a
943
+ * switch or the program: it counts, and so does the next word.
944
+ */
945
+ function cmdStartProgramsAt({ words, written }) {
946
+ const at = [];
947
+ let title = false;
948
+ for (let i = 1; i < words.length; i++) {
949
+ const word = words[i];
950
+ if (!title && written[i].startsWith('"')) {
951
+ title = true;
952
+ continue;
953
+ }
954
+ if (word?.startsWith('/')) {
955
+ if (CMD_START_VALUE_SWITCHES.includes(word.toLowerCase()))
956
+ i++;
957
+ continue;
958
+ }
959
+ at.push(i);
960
+ if (word !== null)
961
+ break;
962
+ }
963
+ return at;
964
+ }