@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,67 @@
1
+ import { type ShellType } from './shell.js';
2
+ import { type CmdDelayedExpansion, type FoundCommand } from './command-reading.js';
3
+ /**
4
+ * What a shell started by a command runs, by the shell's own rules for its
5
+ * arguments: a command text (bash -c 'sudo ls', pwsh -Command 'net user',
6
+ * powershell -EncodedCommand <base64>, cmd /c net user), a script file
7
+ * (bash deploy.sh, pwsh -File deploy.ps1), or its input (bash -s). The
8
+ * shell around it sees a command text only as an argument, so
9
+ * checkCommand() checks the text like any command, read for the shell that
10
+ * runs it. A script file's commands aren't in the text, so the check notes it.
11
+ * eval and Invoke-Expression run a command text too, in the same shell
12
+ * (eval 'sudo ls', Invoke-Expression 'net user'), and their texts follow the
13
+ * same rules: see sameShellTexts(). So do the programs that run one command
14
+ * text in a shell (su -c 'sudo ls', watch 'sudo ls': see TEXT_PROGRAMS in
15
+ * command-wrappers.ts).
16
+ *
17
+ * The rules are which option gives the command text or the file, and which
18
+ * options take a value. They work on the words a reader found, so they read
19
+ * no shell grammar of their own. A POSIX shell's options are read by the
20
+ * wrappers' reader, from its rules there (see command-wrappers.ts), in every
21
+ * way they can be read. A word known only at run time is used as its
22
+ * text ("cd $HOME && sudo ls"), so the programs written in it are still seen.
23
+ * The shell that starts the shell fills that word in before the started shell
24
+ * reads it, so it may hold any command (pwsh -Command $cmd, bash -c "ls $X"):
25
+ * such a command text notes the shell too (file null), as a script file named
26
+ * only at run time does.
27
+ */
28
+ /** What a shell runs, or eval or Invoke-Expression in the shell they are in */
29
+ export interface ShellRun {
30
+ /** The command texts it is given, each to be read by the shell that runs it */
31
+ texts: string[];
32
+ /**
33
+ * The script file it is given, undefined when it is given none; null when the file, or a part of a command
34
+ * text it is given, is known only at run time, or when its options can be read as naming different files
35
+ */
36
+ file?: string | null;
37
+ /** The shell that reads its texts, when it isn't the program itself: sh for su -c's, cmd for runas's command line */
38
+ shell?: string;
39
+ /** A new CMD invocation's explicit mode; absent/unknown never inherits the outer CMD mode. */
40
+ cmdDelayedExpansion?: CmdDelayedExpansion;
41
+ }
42
+ /**
43
+ * What eval (in a POSIX shell) or Invoke-Expression (in PowerShell, also
44
+ * written iex) runs in the shell it is in: its command texts. eval joins its
45
+ * words with spaces. Invoke-Expression runs one text, its Command; PowerShell
46
+ * binds one of the words that aren't parameter names to it, and the others
47
+ * may be values of other parameters (iex -ea 0 'net user'), so each of them
48
+ * is a text. Written with a colon, the parameter and its value are one word
49
+ * (iex -Command:'net user'), which runs what iex given that value runs. A
50
+ * text with a part known only at run time is read as written,
51
+ * as the text of bash -c is, so the programs written in it are checked
52
+ * (eval "cd $HOME && sudo ls"). That part may hold any command, so file is
53
+ * null then, and the command is noted; so is a text that comes from the
54
+ * pipeline ('net user' | iex). gsudo, in any shell, runs its command in the
55
+ * shell it was started from too (gsudo 'net user'), and gsudo !! runs the
56
+ * last command again, which the check can't see, so it is noted. No texts
57
+ * for any other command.
58
+ */
59
+ export declare function sameShellTexts(found: FoundCommand, shellType: ShellType): ShellRun;
60
+ /**
61
+ * What the shell `found` starts runs, or the program that runs one command
62
+ * text in a shell (su -c 'sudo ls'): nothing for any other command. Its kind
63
+ * of shell is taken from its name as found, as checkCommand() takes the
64
+ * reader for a text from the shell it is given.
65
+ * Existing callers may omit context, so preserve their historical program-name readings.
66
+ */
67
+ export declare function shellRuns(found: FoundCommand, callerShellType?: ShellType): ShellRun;
@@ -0,0 +1,310 @@
1
+ import { getShellType, POSIX_SHELLS, programName } from './shell.js';
2
+ import { requireCompleteArguments } from './command-reading.js';
3
+ import { sameShellProgramReadings, shellOptionReadings, textProgramReadings } from './command-wrappers.js';
4
+ /**
5
+ * PowerShell's parameters that take the next word as their value, whatever
6
+ * it is (-wd /home/me). A parameter may be shortened to any start of its
7
+ * full name (-ex for -ExecutionPolicy); ep, wd, if, of and ea are short names
8
+ * of their own.
9
+ */
10
+ const POWERSHELL_VALUE_PARAMETERS = [
11
+ 'executionpolicy', 'ep', 'windowstyle', 'workingdirectory', 'wd', 'configurationname', 'configurationfile',
12
+ 'custompipename', 'inputformat', 'if', 'outputformat', 'of', 'settingsfile', 'version', 'psconsolefile',
13
+ 'encodedarguments', 'ea',
14
+ ];
15
+ /** PowerShell's switches, in pwsh and in Windows PowerShell */
16
+ const POWERSHELL_SWITCHES = [
17
+ 'help', 'login', 'noexit', 'nologo', 'noninteractive', 'noprofile', 'noprofileloadtime', 'interactive', 'sta', 'mta',
18
+ 'servermode', 'socketservermode', 'v2socketservermode', 'namedpipeservermode', 'sshservermode',
19
+ 'removeworkingdirectorytrailingcharacter',
20
+ ];
21
+ /** Every PowerShell parameter: those above, and those that give the command text or the script file */
22
+ const POWERSHELL_PARAMETERS = [
23
+ ...POWERSHELL_VALUE_PARAMETERS, ...POWERSHELL_SWITCHES, 'command', 'commandwithargs', 'cwa', 'encodedcommand', 'ec', 'file',
24
+ ];
25
+ /**
26
+ * The name a word gives a PowerShell parameter, written -Name, --Name or /Name, in lowercase. PowerShell takes an
27
+ * en dash, an em dash or a horizontal bar (–, —, ―) for - too, and a second dash only if it is the same
28
+ */
29
+ const parameterName = (word) => /^(?:([-\u2013\u2014\u2015])\1?|\/)([a-z]+)$/i.exec(word)?.[2].toLowerCase();
30
+ /** Whether a word is written as a PowerShell parameter is, with the start of a parameter's name (/c, not /tmp) */
31
+ function isPowerShellParameter(word) {
32
+ const name = word === null ? undefined : parameterName(word);
33
+ return name !== undefined && POWERSHELL_PARAMETERS.some((known) => known.startsWith(name));
34
+ }
35
+ /**
36
+ * What a POSIX shell runs, by its options as the wrappers' reader reads them
37
+ * (shellOptionReadings()): the command text, which is the first word after
38
+ * bash's options with -c (bash -lc make, bash -c -e 'sudo ls') or the value
39
+ * of fish's -c, --command or -C (fish -C : -c 'sudo ls'), or else the script
40
+ * file, the first word after the options (bash -o pipefail -x deploy.sh).
41
+ * With bash -s or fish -c, the words after the options are the command's
42
+ * arguments. Where the options can be read more than one way, every reading
43
+ * counts. bash's --rcfile or --init-file names a file it runs too.
44
+ */
45
+ function posixShellRuns(found, program) {
46
+ requireCompleteArguments(found);
47
+ return readingsRun(shellOptionReadings(program, found.words), found, { script: true });
48
+ }
49
+ /**
50
+ * What a program that runs one command text in a shell runs (su -c 'sudo
51
+ * ls', watch 'sudo ls': see TEXT_PROGRAMS in command-wrappers.ts), and the
52
+ * shell that reads it. The words after its options are no script file: a
53
+ * user, a file or a group.
54
+ */
55
+ function textProgramRuns(found, program) {
56
+ const text = textProgramReadings(program, found.words, found);
57
+ if (!text)
58
+ return { texts: [] };
59
+ const run = { ...readingsRun(text.readings, found, { script: false }), shell: text.shell };
60
+ // An explicit command text consumes the shell's later words as arguments, not another script.
61
+ if (run.texts.length > 0 || !text.arguments?.length)
62
+ return run;
63
+ const at = text.arguments;
64
+ const shellWords = {
65
+ ...found, name: text.shell,
66
+ words: [text.shell, ...at.map(i => found.words[i])],
67
+ written: [text.shell, ...at.map(i => found.written[i])],
68
+ wordTexts: [text.shell, ...at.map(i => found.wordTexts[i])],
69
+ };
70
+ const inner = posixShellRuns(shellWords, text.shell);
71
+ const file = run.file === null ? null : inner.file;
72
+ return {
73
+ ...run, texts: [...new Set([...run.texts, ...inner.texts])],
74
+ ...(file === undefined ? {} : { file }),
75
+ };
76
+ }
77
+ /**
78
+ * What the readings of a command's options give it to run: its command texts,
79
+ * each once also when more than one reading finds it, and one known only at
80
+ * run time as written; and for a shell (`script`), its script file. A part
81
+ * known only at run time, in a text or the word after the options, may hold
82
+ * any command, and so may a script file the readings don't agree on, and
83
+ * texts that aren't among its words at all (parallel :::: jobs.txt): the
84
+ * command is noted then (file null).
85
+ */
86
+ function readingsRun({ operands, texts, hidden }, { words, wordTexts }, { script }) {
87
+ const textOf = ({ text, at, to }) => {
88
+ if (at === undefined)
89
+ return text ?? '';
90
+ if (to !== undefined)
91
+ return wordTexts.slice(at, to).join(' ');
92
+ return wordTexts[at];
93
+ };
94
+ const after = [...new Set(operands.filter((at) => at < words.length).map((at) => words[at]))];
95
+ const atRunTime = hidden || texts.some(({ text, at }) => at !== undefined && text === null) || after.includes(null)
96
+ || (script && after.length > 1);
97
+ const file = script && after.length === 1 ? { file: after[0] } : {};
98
+ return { texts: [...new Set(texts.map(textOf))], ...(atRunTime ? { file: null } : file) };
99
+ }
100
+ /**
101
+ * What a PowerShell runs: the words after -Command (-c) joined with spaces,
102
+ * the base64 UTF-16LE text after -EncodedCommand (-e, -enc, -ec), or the
103
+ * script file after -File (-f). Without these, its first word that isn't a
104
+ * parameter is a script file in PowerShell 7; Windows PowerShell runs it, and
105
+ * the words after it, as a command, or as a script file when it is a .ps1.
106
+ * Parameters start with -, -- or / (pwsh takes –, — and ― for -, and Windows
107
+ * PowerShell, whose parser isn't open source, may too, so there such a word
108
+ * is read as no parameter as well), and a parameter's value is the next word,
109
+ * whatever it is (-wd /home/me). A word known only at run time where a
110
+ * parameter can be may be any of them: a switch, a parameter with a value,
111
+ * -Command or -File. Where the check can't tell which word is a value,
112
+ * every reading counts.
113
+ */
114
+ function powerShellRuns(found, program) {
115
+ requireCompleteArguments(found);
116
+ const { words, wordTexts } = found;
117
+ const texts = [];
118
+ // The script files the readings name, and null for a part known only at run time, which may hold any command
119
+ const files = new Set();
120
+ const read = new Set();
121
+ // Adds the command texts made of the words `parts`
122
+ const addTexts = (found, parts) => {
123
+ texts.push(...found);
124
+ if (parts.includes(null))
125
+ files.add(null);
126
+ };
127
+ // Reads the words from the `from`th on, as PowerShell does
128
+ const readFrom = (from) => {
129
+ if (read.has(from))
130
+ return;
131
+ read.add(from);
132
+ for (let i = from; i < words.length; i++) {
133
+ const word = words[i];
134
+ if (word === null) {
135
+ // Such a word may be any parameter, the command or the script file, so the shell is noted. As -Command, the
136
+ // words after it are the command text (pwsh $mode net user); as a parameter with a value, the next word is that
137
+ files.add(null);
138
+ if (i + 1 < words.length)
139
+ texts.push(wordTexts.slice(i + 1).join(' '));
140
+ readFrom(i + 2);
141
+ continue;
142
+ }
143
+ const parameter = parameterName(word);
144
+ if (parameter === undefined || (program !== 'pwsh' && /^[\u2013\u2014\u2015]/.test(word))) {
145
+ if (program === 'pwsh' || /\.ps1$/i.test(word))
146
+ files.add(word);
147
+ else
148
+ addTexts([wordTexts.slice(i).join(' ')], words.slice(i));
149
+ if (parameter === undefined)
150
+ return;
151
+ }
152
+ if (parameter === 'ec' || 'encodedcommand'.startsWith(parameter)) {
153
+ const encoded = words[i + 1];
154
+ return addTexts(encoded ? [Buffer.from(encoded, 'base64').toString('utf16le')] : [], [encoded]);
155
+ }
156
+ if ('command'.startsWith(parameter)) {
157
+ // -Command - reads the command from standard input
158
+ const text = words[i + 1] === '-' ? '' : wordTexts.slice(i + 1).join(' ');
159
+ return addTexts(text ? [text] : [], words.slice(i + 1));
160
+ }
161
+ // -CommandWithArgs: the next word is the command, and the words after it are its $args
162
+ if (parameter === 'cwa' || parameter === 'commandwithargs')
163
+ return addTexts(i + 1 < words.length ? [wordTexts[i + 1]] : [], [words[i + 1]]);
164
+ if ('file'.startsWith(parameter)) {
165
+ if (i + 1 < words.length && words[i + 1] !== '-')
166
+ files.add(words[i + 1]);
167
+ return;
168
+ }
169
+ // A parameter's value, also one known only at run time. When the next word is written as a parameter is (-wd /c:
170
+ // Git Bash's C: drive, and -Command's short form), or the parameter may be a switch (pwsh's -i is a switch,
171
+ // Windows PowerShell's -i takes a value), it is read as the next parameter too
172
+ if (POWERSHELL_VALUE_PARAMETERS.some((name) => name.startsWith(parameter)) && i + 1 < words.length) {
173
+ if (isPowerShellParameter(words[i + 1]) || POWERSHELL_SWITCHES.some((name) => name.startsWith(parameter)))
174
+ readFrom(i + 1);
175
+ i++;
176
+ }
177
+ }
178
+ };
179
+ readFrom(1);
180
+ // A script file the readings don't agree on may hold any command too
181
+ const file = [...files];
182
+ return { texts: [...new Set(texts)], ...(file.length === 0 ? {} : { file: file.length === 1 ? file[0] : null }) };
183
+ }
184
+ /**
185
+ * cmd's rule for quotes around the command after /c: when it starts with ",
186
+ * cmd drops that quote and the last one. It keeps both when there are only
187
+ * those two, with whitespace and no special characters between them, and
188
+ * they enclose a program's path (cmd /c "C:\Program Files\x\tool.exe" -v).
189
+ * Whether that file exists depends on where the command runs, so both ways
190
+ * of reading the command are returned then.
191
+ */
192
+ function cmdQuoteReadings(line, alwaysDropsQuotes) {
193
+ if (!line.startsWith('"'))
194
+ return [line];
195
+ const last = line.lastIndexOf('"');
196
+ const dropped = line.slice(1, last) + line.slice(last + 1);
197
+ const keeps = !alwaysDropsQuotes && (line.match(/"/g) ?? []).length === 2 && /^"[^"&<>()@^|]*\s[^"&<>()@^|]*"/.test(line);
198
+ return keeps ? [line, dropped] : [dropped];
199
+ }
200
+ /**
201
+ * What cmd runs: what follows /c, /k or /r, after other switches such as /q,
202
+ * /d or /v:on. Switches can be written together (/q/c), and the command can
203
+ * start in the same word (/cnet). cmd gets the words as one command line,
204
+ * where a word with whitespace in it is in quotes, as PowerShell and Git Bash
205
+ * pass it.
206
+ */
207
+ function cmdRuns(found) {
208
+ requireCompleteArguments(found);
209
+ const { words, wordTexts } = found;
210
+ // Each word is a switch or a part of the command, so one known only at run time may hold any command (cmd $opts)
211
+ const noted = words.slice(1).includes(null) ? { file: null } : {};
212
+ let alwaysDropsQuotes = false;
213
+ let cmdDelayedExpansion = 'unknown';
214
+ for (let i = 1; i < wordTexts.length; i++) {
215
+ const word = wordTexts[i];
216
+ if (!word.startsWith('/'))
217
+ break;
218
+ const run = /^((?:\/(?![ckr])[^/]*)*)\/[ckr](.*)$/is.exec(word);
219
+ const switches = run ? run[1] : word;
220
+ if (words[i] === null) {
221
+ cmdDelayedExpansion = 'unknown';
222
+ }
223
+ else {
224
+ for (const match of switches.matchAll(/\/v:(on|off)(?=\/|$)/gi)) {
225
+ cmdDelayedExpansion = match[1].toLowerCase();
226
+ }
227
+ }
228
+ // /s: cmd drops the quotes around the command in every case
229
+ if (/\/s(?:\/|$)/i.test(run ? run[1] : word))
230
+ alwaysDropsQuotes = true;
231
+ if (!run)
232
+ continue;
233
+ const lineWords = run[2] ? [run[2], ...wordTexts.slice(i + 1)] : wordTexts.slice(i + 1);
234
+ if (lineWords.length === 0)
235
+ break;
236
+ const line = lineWords.map((lineWord) => (lineWord === '' || /\s/.test(lineWord) ? `"${lineWord}"` : lineWord)).join(' ');
237
+ return { texts: cmdQuoteReadings(line, alwaysDropsQuotes), cmdDelayedExpansion, ...noted };
238
+ }
239
+ return { texts: [], cmdDelayedExpansion, ...noted };
240
+ }
241
+ /**
242
+ * What eval (in a POSIX shell) or Invoke-Expression (in PowerShell, also
243
+ * written iex) runs in the shell it is in: its command texts. eval joins its
244
+ * words with spaces. Invoke-Expression runs one text, its Command; PowerShell
245
+ * binds one of the words that aren't parameter names to it, and the others
246
+ * may be values of other parameters (iex -ea 0 'net user'), so each of them
247
+ * is a text. Written with a colon, the parameter and its value are one word
248
+ * (iex -Command:'net user'), which runs what iex given that value runs. A
249
+ * text with a part known only at run time is read as written,
250
+ * as the text of bash -c is, so the programs written in it are checked
251
+ * (eval "cd $HOME && sudo ls"). That part may hold any command, so file is
252
+ * null then, and the command is noted; so is a text that comes from the
253
+ * pipeline ('net user' | iex). gsudo, in any shell, runs its command in the
254
+ * shell it was started from too (gsudo 'net user'), and gsudo !! runs the
255
+ * last command again, which the check can't see, so it is noted. No texts
256
+ * for any other command.
257
+ */
258
+ export function sameShellTexts(found, shellType) {
259
+ const { name, words, wordTexts } = found;
260
+ const program = programName(name, shellType);
261
+ const sameShell = sameShellProgramReadings(program, words, found);
262
+ if (sameShell) {
263
+ const run = readingsRun(sameShell, found, { script: false });
264
+ return run.texts.includes('!!') ? { texts: [], file: null } : run;
265
+ }
266
+ if (shellType === 'posix' && program === 'eval') {
267
+ requireCompleteArguments(found);
268
+ const from = words[1] === '--' ? 2 : 1;
269
+ return {
270
+ texts: from < words.length ? [wordTexts.slice(from).join(' ')] : [],
271
+ ...(words.slice(from).includes(null) ? { file: null } : {}),
272
+ };
273
+ }
274
+ if (shellType === 'powershell' && program === 'invoke-expression') {
275
+ requireCompleteArguments(found);
276
+ // Where the words that aren't parameter names are; with none, the text comes from the pipeline
277
+ const at = words.flatMap((word, i) => (i > 0 && (word === null || !/^[-\u2013\u2014\u2015]/.test(word)) ? [i] : []));
278
+ // -Command:'net user' (-c: 'net user'): the command without the parameter's name runs the same, and is shorter
279
+ const withColon = words.flatMap((word) => {
280
+ const colon = word === null ? null : /^[-\u2013\u2014\u2015]([a-z]+):(.*)$/is.exec(word);
281
+ return colon && colon[2] !== '' && 'command'.startsWith(colon[1].toLowerCase())
282
+ ? [`${wordTexts[0]} ${colon[2]}`]
283
+ : [];
284
+ });
285
+ return {
286
+ texts: [...at.map((i) => wordTexts[i]), ...withColon],
287
+ ...((at.length === 0 && withColon.length === 0) || at.some((i) => words[i] === null) ? { file: null } : {}),
288
+ };
289
+ }
290
+ return { texts: [] };
291
+ }
292
+ /**
293
+ * What the shell `found` starts runs, or the program that runs one command
294
+ * text in a shell (su -c 'sudo ls'): nothing for any other command. Its kind
295
+ * of shell is taken from its name as found, as checkCommand() takes the
296
+ * reader for a text from the shell it is given.
297
+ * Existing callers may omit context, so preserve their historical program-name readings.
298
+ */
299
+ export function shellRuns(found, callerShellType) {
300
+ const program = programName(found.name, callerShellType);
301
+ switch (getShellType(found.name)) {
302
+ case 'powershell':
303
+ return powerShellRuns(found, program);
304
+ case 'cmd':
305
+ return cmdRuns(found);
306
+ default:
307
+ // getShellType() takes every other program for a POSIX shell
308
+ return POSIX_SHELLS.has(program) ? posixShellRuns(found, program) : textProgramRuns(found, program);
309
+ }
310
+ }
@@ -0,0 +1,6 @@
1
+ import type { CommandReading } from './command-reading.js';
2
+ /**
3
+ * The caller supplies its actual selected native endpoint; no endpoint or unsupported capability
4
+ * retains the legacy reading exactly. Capability capture happens on import, not after caller changes.
5
+ */
6
+ export declare function readPosixCommands(command: string, selectedShell?: string): Promise<CommandReading>;
@@ -0,0 +1,237 @@
1
+ import { parse, forEachChild } from 'unbash';
2
+ import { braceWords, quotedChars, unquotedChars, MAX_BRACE_WORDS } from './brace-expansion.js';
3
+ import { posixBraceSemantics } from './posix-shell-capabilities.js';
4
+ /**
5
+ * The command check's reader for POSIX shells (bash, zsh, sh, dash, ksh,
6
+ * fish), with unbash, a bash parser. It finds every command the shell would
7
+ * run, also on later lines and inside $( ), backticks, <( ), { } groups,
8
+ * subshells, functions and if, while, for and case bodies. Words inside
9
+ * quotes and heredoc bodies are text. A command name with a {a,b} brace
10
+ * expansion is the first word it expands to, so {sudo,ls} is sudo, and so is
11
+ * {$X,sudo} when $X is empty. zsh and
12
+ * the other shells are read as bash, which covers the commands they have in
13
+ * common.
14
+ *
15
+ * unbash doesn't stop at a syntax error: it returns what it could read and
16
+ * lists the errors, each on the script it found it in ($( ) and backticks
17
+ * are scripts of their own). Any error anywhere is a parse error here, so the
18
+ * check never decides on a command it read only in part.
19
+ */
20
+ /** Quoted and literal text is known before execution; globs depend on the matching files */
21
+ const STATIC_PARTS = new Set(['Literal', 'SingleQuoted', 'AnsiCQuoted']);
22
+ /** Word parts that bash drops when they are empty and unquoted ($X, ${X}, $(cmd)) */
23
+ const VANISHING_PARTS = new Set(['SimpleExpansion', 'ParameterExpansion', 'CommandExpansion']);
24
+ /** The commands that remove a function: unset -f, and zsh's unfunction, unhash -f and disable -f */
25
+ const FUNCTION_REMOVERS = new Set(['unset', 'unfunction', 'unhash', 'disable']);
26
+ /**
27
+ * Stand-ins for a piece known only at run time in a brace word's characters,
28
+ * so that braceWords keeps the words next to it ({$X,sudo} makes $X and sudo):
29
+ * one for a piece in VANISHING_PARTS, one for any other ("$X"). They start
30
+ * with a NUL, which no command text holds: Node starts no command that has one.
31
+ */
32
+ const DROPPED_IF_EMPTY = '\0$';
33
+ const KEPT_IF_EMPTY = '\0"';
34
+ /**
35
+ * A word that brace expansion made and bash may drop: only pieces it drops
36
+ * when they are empty, and letters, digits or _ after one, which bash may read
37
+ * into a $X's name ({$X,su}do makes $Xdo)
38
+ */
39
+ const MAY_VANISH = /^(?:\0\$\w*)+$/;
40
+ /**
41
+ * The commands that run, in this shell, code the reader doesn't read: eval and
42
+ * zsh's emulate -c (their words), trap and mapfile or readarray -C (later), .
43
+ * and source (a file), and alias (its value, where the name is used: an alias
44
+ * comes before a function)
45
+ */
46
+ const CODE_RUNNERS = new Set(['eval', 'emulate', 'trap', 'mapfile', 'readarray', '.', 'source', 'alias']);
47
+ /** The words that run the next word as a command in this shell: builtin, command, and zsh's noglob and nocorrect */
48
+ const COMMAND_PREFIXES = new Set(['builtin', 'command', 'noglob', 'nocorrect']);
49
+ /**
50
+ * A word's value as bash reads it (quotes and escapes removed, $'…' decoded),
51
+ * or null when part of it is known only at run time: an expansion, a command's
52
+ * output, or a {a,b} brace expansion, which makes several words (the reader
53
+ * expands a command name's braces with braceWords).
54
+ */
55
+ function wordValue(word) {
56
+ return (word.parts ?? []).every((part) => partValue(part) !== null) ? word.value : null;
57
+ }
58
+ /** One part's value as bash reads it, or null when it is known only at run time */
59
+ function partValue(part) {
60
+ if (part.type === 'DoubleQuoted' || part.type === 'LocaleString') {
61
+ if (!part.parts.every((inner) => inner.type === 'Literal'))
62
+ return null;
63
+ return part.parts.map((inner) => (inner.type === 'Literal' ? inner.value : '')).join('');
64
+ }
65
+ return STATIC_PARTS.has(part.type) && 'value' in part ? part.value : null;
66
+ }
67
+ /**
68
+ * A word's characters for brace expansion. Only the braces unbash reads as an
69
+ * expansion are syntax. The rest of the word is text, and so are the quoted
70
+ * pieces inside the braces: {"a,b",c} gives a,b and c.
71
+ */
72
+ function braceChars(word) {
73
+ const chars = [];
74
+ for (const part of word.parts ?? []) {
75
+ if (part.type !== 'BraceExpansion') {
76
+ chars.push(...partChars(part));
77
+ continue;
78
+ }
79
+ // The braces' text as written, except the quoted or expanded pieces inside, which are parts of their own
80
+ let at = part.pos;
81
+ for (const inner of part.parts ?? []) {
82
+ chars.push(...unquotedChars(part.text.slice(at - part.pos, inner.pos - part.pos)));
83
+ chars.push(...(inner.type === 'Literal' ? unquotedChars(inner.text) : partChars(inner)));
84
+ at = inner.end;
85
+ }
86
+ chars.push(...unquotedChars(part.text.slice(at - part.pos)));
87
+ }
88
+ return chars;
89
+ }
90
+ /** A part's characters, all text: its value, or a stand-in when it is known only at run time */
91
+ function partChars(part) {
92
+ const value = partValue(part);
93
+ if (value !== null)
94
+ return quotedChars(value);
95
+ return quotedChars(VANISHING_PARTS.has(part.type) ? DROPPED_IF_EMPTY : KEPT_IF_EMPTY);
96
+ }
97
+ /**
98
+ * The words bash makes from a word, each with its value (null when it is known
99
+ * only at run time) and whether bash may drop it, or null past braceWords' limits.
100
+ * A brace expansion makes several and bash drops the empty ones: {,sudo} ls
101
+ * runs sudo, {,} sudo runs sudo, and {$X,sudo} id runs sudo when $X is empty.
102
+ */
103
+ function wordsMade(word, options) {
104
+ if (!word.parts?.some((part) => part.type === 'BraceExpansion')) {
105
+ return [{ value: wordValue(word), mayVanish: mayVanish(word) }];
106
+ }
107
+ const made = braceWords(braceChars(word), options);
108
+ return made && made.map((text) => ({ value: text.includes('\0') ? null : text, mayVanish: MAY_VANISH.test(text) }));
109
+ }
110
+ const BRACE_LIMIT_ERROR = `brace expansion makes more than ${MAX_BRACE_WORDS} words, or takes too long to read`;
111
+ /** Keep inspected words aligned; only a tail after a retained command name may defer a bounded failure. */
112
+ function commandWords(words, options) {
113
+ const expanded = [];
114
+ for (const source of words) {
115
+ const made = wordsMade(source, options);
116
+ if (made === null) {
117
+ if (!expanded.some((word) => !word.mayVanish))
118
+ return null;
119
+ return { words: expanded, argumentError: BRACE_LIMIT_ERROR };
120
+ }
121
+ expanded.push(...made.map((word) => ({ ...word, source })));
122
+ }
123
+ return { words: expanded };
124
+ }
125
+ /** A retained runtime word still ends name selection even when its source was already listed. */
126
+ function commandNames(expanded) {
127
+ const names = [];
128
+ const runtimeSources = new Set();
129
+ for (let index = 0; index < expanded.length; index++) {
130
+ const name = expanded[index];
131
+ if (name.value !== null || !runtimeSources.has(name.source)) {
132
+ names.push({ index, name });
133
+ if (name.value === null)
134
+ runtimeSources.add(name.source);
135
+ }
136
+ if (!name.mayVanish)
137
+ break;
138
+ }
139
+ return names;
140
+ }
141
+ /** Whether bash may drop the word entirely, so that the next word is the command's name */
142
+ function mayVanish(word) {
143
+ const parts = word.parts ?? [];
144
+ return parts.length > 0 && parts.every((part) => VANISHING_PARTS.has(part.type));
145
+ }
146
+ /**
147
+ * Whether a command may remove the function `name`: one of FUNCTION_REMOVERS
148
+ * anywhere among the command's words (so also after builtin, command or
149
+ * eval), followed by the name or by a word known only at run time
150
+ */
151
+ function mayRemoveFunction(command, name) {
152
+ const at = command.words.findIndex((word) => word !== null && FUNCTION_REMOVERS.has(word));
153
+ return at >= 0 && command.words.slice(at + 1).some((word) => word === null || word === name);
154
+ }
155
+ /**
156
+ * Whether a command may run code the reader doesn't read, which may remove any
157
+ * function: one of CODE_RUNNERS, also after COMMAND_PREFIXES (command -p eval),
158
+ * or a name known only at run time ($cmd may be unset or eval)
159
+ */
160
+ function mayRunUnreadCode(command) {
161
+ const { words } = command;
162
+ let at = 0;
163
+ while (COMMAND_PREFIXES.has(words[at] ?? '')) {
164
+ at++;
165
+ while (words[at]?.startsWith('-'))
166
+ at++;
167
+ }
168
+ const name = words[at];
169
+ return name === null || (name !== undefined && CODE_RUNNERS.has(name));
170
+ }
171
+ /**
172
+ * The caller supplies its actual selected native endpoint; no endpoint or unsupported capability
173
+ * retains the legacy reading exactly. Capability capture happens on import, not after caller changes.
174
+ */
175
+ export async function readPosixCommands(command, selectedShell) {
176
+ const semantics = selectedShell === undefined ? 'legacy' : await posixBraceSemantics(selectedShell) ?? 'legacy';
177
+ const options = { semantics };
178
+ const script = parse(command);
179
+ let parseError;
180
+ const commands = [];
181
+ // Positions inside backticks count from the backticks' own text, so a command
182
+ // there is given the start of the backticks around it
183
+ const visit = (node, backticksStart) => {
184
+ if (node.type === 'Script')
185
+ parseError ?? (parseError = node.errors?.[0]?.message);
186
+ if (node.type === 'Command' && node.name) {
187
+ const words = [node.name, ...node.args.filter((arg) => arg.type === 'Word')];
188
+ const expanded = commandWords(words, options);
189
+ if (expanded === null) {
190
+ parseError ?? (parseError = BRACE_LIMIT_ERROR);
191
+ }
192
+ else {
193
+ const candidates = commandNames(expanded.words).map(({ index, name }) => {
194
+ const remaining = expanded.words.slice(index);
195
+ return {
196
+ name: name.value ?? name.source.text,
197
+ words: remaining.map((word) => word.value),
198
+ written: remaining.map((word) => word.source.text),
199
+ wordTexts: remaining.map((word) => word.value ?? word.source.value),
200
+ start: backticksStart ?? (name.source === words[0] ? node.pos : name.source.pos),
201
+ nameAtRunTime: name.value === null,
202
+ ...(expanded.argumentError === undefined ? {} : { argumentError: expanded.argumentError }),
203
+ };
204
+ });
205
+ const unsafePrefix = candidates.some((candidate) => candidate.nameAtRunTime
206
+ || COMMAND_PREFIXES.has(candidate.words[0] ?? '') || mayRunUnreadCode(candidate));
207
+ if (expanded.argumentError !== undefined && unsafePrefix) {
208
+ parseError ?? (parseError = expanded.argumentError);
209
+ }
210
+ else {
211
+ commands.push(...candidates);
212
+ }
213
+ }
214
+ }
215
+ const inBackticks = node.type === 'CommandExpansion' && node.text.startsWith('`');
216
+ const childBackticksStart = inBackticks ? backticksStart ?? node.pos : backticksStart;
217
+ forEachChild(node, (child) => visit(child, childBackticksStart));
218
+ };
219
+ visit(script, undefined);
220
+ if (parseError !== undefined)
221
+ return { commands: [], functions: [], parseError };
222
+ // Only the script's own statements (see CommandReading.functions), and none the
223
+ // text may remove: wherever the removal is written, it may run before a call,
224
+ // from a function's body. Code the reader doesn't read may remove any of them.
225
+ const functions = [];
226
+ const statements = commands.some((command) => command.argumentError !== undefined || mayRunUnreadCode(command))
227
+ ? [] : script.commands;
228
+ for (const statement of statements) {
229
+ if (statement.command.type !== 'Function' || statement.background)
230
+ continue;
231
+ const name = statement.command.name.value;
232
+ if (!commands.some((command) => mayRemoveFunction(command, name))) {
233
+ functions.push({ name, end: statement.command.end });
234
+ }
235
+ }
236
+ return { commands: commands.sort((a, b) => a.start - b.start), functions };
237
+ }
@@ -0,0 +1,8 @@
1
+ import type { BraceSemantics } from './brace-expansion.js';
2
+ /**
3
+ * Fixed --version only, on a matching precaptured native endpoint; never caller code or a profile.
4
+ * Native Bash5.2 retains the backslash slot that Bash5.3 omits; other Bash4/5 calls keep legacy rules.
5
+ * Bash3.2 and Zsh5.9 defaults remain supported; startup options and profiles are not evaluated.
6
+ * One bounded query per endpoint (at most 32); unknown, unavailable or other versions retain legacy behavior.
7
+ */
8
+ export declare function posixBraceSemantics(shell: string): Promise<BraceSemantics | undefined>;