Open History to see the last commit
1type CommandWrapper = "env" | "sudo";
2type CommandProgramContext = "exec" | "shell";
3
4const MAX_COMMAND_SEGMENTS = 64;
5
6const SHELL_PROGRAMS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish"]);
7const WINDOWS_SHELL_PROGRAMS = new Set([
8 "cmd",
9 "cmd.exe",
10 "powershell",
11 "powershell.exe",
12 "pwsh",
13 "pwsh.exe",
14]);
15const SHELL_OPTIONS_WITH_VALUE = new Set(["-o", "-O", "--rcfile", "--init-file"]);
16const SHELL_COMMAND_WRAPPERS = new Set(["builtin", "command", "exec"]);
17const SHELL_PRECOMMAND_MODIFIERS = new Set(["nocorrect", "noglob", "time"]);
18const POWERSHELL_SETUP_PROGRAMS = new Set(["pop-location", "push-location", "set-location"]);
19const POWERSHELL_FLAGS = new Set(["-mta", "-nologo", "-noninteractive", "-noprofile", "-sta"]);
20const POWERSHELL_OPTIONS_WITH_VALUE = new Set([
21 "-configurationname",
22 "-executionpolicy",
23 "-inputformat",
24 "-outputformat",
25 "-version",
26 "-windowstyle",
27 "-workingdirectory",
28]);
29const START_PROCESS_FLAGS = new Set([
30 "-confirm",
31 "-debug",
32 "-loaduserprofile",
33 "-nonewwindow",
34 "-passthru",
35 "-usenewenvironment",
36 "-verbose",
37 "-wait",
38 "-whatif",
39]);
40const START_PROCESS_OPTIONS_WITH_VALUE = new Set([
41 "-argumentlist",
42 "-credential",
43 "-environment",
44 "-erroraction",
45 "-errorvariable",
46 "-informationaction",
47 "-informationvariable",
48 "-outbuffer",
49 "-outvariable",
50 "-pipelinevariable",
51 "-progressaction",
52 "-redirectstandarderror",
53 "-redirectstandardinput",
54 "-redirectstandardoutput",
55 "-verb",
56 "-warningaction",
57 "-warningvariable",
58 "-windowstyle",
59 "-workingdirectory",
60]);
61const SKIPPABLE_SUDO_PROBES = new Set(["[", "[[", "test", "true"]);
62const NON_PROGRAM_PREFIX_CHARACTERS = "<>(){}[];|&$`#!%@:";
63const NON_PROGRAM_SUFFIX_CHARACTERS = "){]}`";
64
65const NON_DESCRIPTIVE_SHELL_PROGRAMS = new Set([
66 "!",
67 "#",
68 ".",
69 ":",
70 "[",
71 "[[",
72 "alias",
73 "and",
74 "autoload",
75 "begin",
76 "bg",
77 "bind",
78 "bindkey",
79 "break",
80 "builtin",
81 "caller",
82 "case",
83 "catch",
84 "cd",
85 "command",
86 "compgen",
87 "complete",
88 "compopt",
89 "continue",
90 "coproc",
91 "declare",
92 "dirs",
93 "disown",
94 "do",
95 "done",
96 "elif",
97 "else",
98 "enable",
99 "end",
100 "esac",
101 "eval",
102 "exec",
103 "exit",
104 "export",
105 "false",
106 "fc",
107 "fg",
108 "fi",
109 "finally",
110 "for",
111 "foreach",
112 "function",
113 "getopts",
114 "history",
115 "if",
116 "in",
117 "jobs",
118 "let",
119 "local",
120 "logout",
121 "mapfile",
122 "nocorrect",
123 "noglob",
124 "not",
125 "or",
126 "popd",
127 "pushd",
128 "read",
129 "readarray",
130 "readonly",
131 "repeat",
132 "return",
133 "select",
134 "set",
135 "setopt",
136 "shift",
137 "shopt",
138 "source",
139 "switch",
140 "suspend",
141 "test",
142 "then",
143 "time",
144 "times",
145 "trap",
146 "try",
147 "true",
148 "type",
149 "typeset",
150 "ulimit",
151 "umask",
152 "unalias",
153 "until",
154 "unset",
155 "unsetopt",
156 "wait",
157 "while",
158]);
159
160const TERMINAL_SHELL_PROGRAMS = new Set([
161 "and",
162 "begin",
163 "break",
164 "case",
165 "catch",
166 "continue",
167 "coproc",
168 "do",
169 "done",
170 "elif",
171 "else",
172 "end",
173 "esac",
174 "exec",
175 "exit",
176 "false",
177 "fi",
178 "finally",
179 "for",
180 "foreach",
181 "function",
182 "if",
183 "in",
184 "not",
185 "or",
186 "repeat",
187 "return",
188 "select",
189 "switch",
190 "then",
191 "try",
192 "until",
193 "while",
194]);
195
196function shellCommandArgumentIndex(
197 shell: string,
198 tokens: ReadonlyArray<string>,
199 start: number,
200): number | null {
201 for (let index = start; index < tokens.length; index += 1) {
202 const option = tokens[index]!;
203 if (option === "--" || !option.startsWith("-")) return null;
204 if (SHELL_OPTIONS_WITH_VALUE.has(option)) {
205 index += 1;
206 continue;
207 }
208 if (option === "--command" || /^-[a-zA-Z]*c[a-zA-Z]*$/.test(option)) {
209 // fish takes the next token as the script even when it is `--`.
210 return index + (shell !== "fish" && tokens[index + 1] === "--" ? 2 : 1);
211 }
212 }
213 return null;
214}
215
216const COMMAND_WRAPPER_OPTIONS_WITH_VALUE: Record<CommandWrapper, ReadonlySet<string>> = {
217 env: new Set(["-C", "--chdir", "-S", "--split-string", "-u", "--unset"]),
218 sudo: new Set(["-C", "--close-from", "-D", "--chdir", "-g", "--group", "-u", "--user"]),
219};
220
221const COMMAND_WRAPPER_FLAGS: Record<CommandWrapper, ReadonlySet<string>> = {
222 env: new Set(["-0", "--null", "-i", "--ignore-environment", "--debug", "-v"]),
223 sudo: new Set(["-A", "--askpass", "-b", "--background", "-E", "-H", "-i", "-n", "-S"]),
224};
225
226function tokenizeShellCommand(command: string): string[] | null {
227 const input = command.trim();
228 const tokens: string[] = [];
229 let current = "";
230 let quote: '"' | "'" | null = null;
231 let escaping = false;
232 let inBackticks = false;
233 let substitutionDepth = 0;
234 let parameterExpansionDepth = 0;
235 let tokenStarted = false;
236
237 for (let index = 0; index < input.length; index += 1) {
238 const character = input[index]!;
239 if (escaping) {
240 current += character;
241 escaping = false;
242 tokenStarted = true;
243 continue;
244 }
245 if (character === "\\" && quote !== "'") {
246 const nextCharacter = input[index + 1];
247 const isWindowsPath = quote === null && /^(?:[A-Za-z]:|\.{1,2})(?:\\[^\s]*)?$/u.test(current);
248 if (
249 (quote === '"' || isWindowsPath) &&
250 nextCharacter !== undefined &&
251 nextCharacter !== '"' &&
252 nextCharacter !== "\\" &&
253 nextCharacter !== "$" &&
254 nextCharacter !== "`" &&
255 nextCharacter !== "\n"
256 ) {
257 current += character;
258 tokenStarted = true;
259 continue;
260 }
261 escaping = true;
262 tokenStarted = true;
263 continue;
264 }
265 if (inBackticks) {
266 current += character;
267 if (character === "`") inBackticks = false;
268 tokenStarted = true;
269 continue;
270 }
271 if (quote !== null) {
272 if (character === quote) {
273 quote = null;
274 } else {
275 current += character;
276 }
277 tokenStarted = true;
278 continue;
279 }
280 if (character === "`") {
281 current += character;
282 inBackticks = true;
283 tokenStarted = true;
284 continue;
285 }
286 if (character === "$" && input[index + 1] === "{") {
287 current += "${";
288 parameterExpansionDepth += 1;
289 tokenStarted = true;
290 index += 1;
291 continue;
292 }
293 if (character === "{" && parameterExpansionDepth > 0) {
294 current += character;
295 parameterExpansionDepth += 1;
296 tokenStarted = true;
297 continue;
298 }
299 if (character === "}" && parameterExpansionDepth > 0) {
300 current += character;
301 parameterExpansionDepth -= 1;
302 tokenStarted = true;
303 continue;
304 }
305 if (character === "$" && input[index + 1] === "(") {
306 current += "$(";
307 substitutionDepth += 1;
308 tokenStarted = true;
309 index += 1;
310 continue;
311 }
312 if (character === "(") {
313 current += character;
314 substitutionDepth += 1;
315 tokenStarted = true;
316 continue;
317 }
318 if (character === ")" && substitutionDepth > 0) {
319 current += character;
320 substitutionDepth -= 1;
321 tokenStarted = true;
322 continue;
323 }
324 if (character === '"' || character === "'") {
325 quote = character;
326 tokenStarted = true;
327 continue;
328 }
329 if (/\s/u.test(character)) {
330 if (substitutionDepth > 0 || parameterExpansionDepth > 0) {
331 current += character;
332 tokenStarted = true;
333 continue;
334 }
335 if (tokenStarted) {
336 tokens.push(current);
337 current = "";
338 tokenStarted = false;
339 }
340 continue;
341 }
342 current += character;
343 tokenStarted = true;
344 }
345
346 if (
347 quote !== null ||
348 escaping ||
349 inBackticks ||
350 substitutionDepth > 0 ||
351 parameterExpansionDepth > 0
352 ) {
353 return null;
354 }
355 if (tokenStarted) tokens.push(current);
356 return tokens;
357}
358
359type ShellCommandSplit = {
360 readonly firstCommand: string;
361 readonly remainingCommand: string | null;
362 readonly separator: string | null;
363};
364
365type Heredoc = {
366 readonly delimiter: string;
367 readonly stripTabs: boolean;
368};
369
370type ShellSeparator = {
371 readonly index: number;
372 readonly length: number;
373};
374
375type ShellCommentRange = {
376 readonly start: number;
377 readonly end: number;
378};
379
380function commandWithoutShellComments(
381 command: string,
382 end: number,
383 comments: ReadonlyArray<ShellCommentRange>,
384): string {
385 let result = "";
386 let cursor = 0;
387 for (const comment of comments) {
388 if (comment.start >= end) break;
389 result += command.slice(cursor, comment.start);
390 cursor = Math.min(comment.end, end);
391 }
392 return result + command.slice(cursor, end);
393}
394
395function readHeredocDelimiter(
396 command: string,
397 start: number,
398 stripTabs: boolean,
399): { readonly heredoc: Heredoc; readonly end: number } | null {
400 let index = start;
401 while (command[index] === " " || command[index] === "\t") index += 1;
402
403 let delimiter = "";
404 let quote: '"' | "'" | null = null;
405 let escaping = false;
406 for (; index < command.length; index += 1) {
407 const character = command[index]!;
408 if (escaping) {
409 delimiter += character;
410 escaping = false;
411 continue;
412 }
413 if (character === "\\" && quote !== "'") {
414 escaping = true;
415 continue;
416 }
417 if (quote !== null) {
418 if (character === quote) quote = null;
419 else delimiter += character;
420 continue;
421 }
422 if (character === '"' || character === "'") {
423 quote = character;
424 continue;
425 }
426 if (/\s/u.test(character) || ";&|<>()".includes(character)) break;
427 delimiter += character;
428 }
429
430 if (!delimiter || quote !== null || escaping) return null;
431 return { heredoc: { delimiter, stripTabs }, end: index };
432}
433
434function commandAfterHeredocs(
435 command: string,
436 start: number,
437 heredocs: ReadonlyArray<Heredoc>,
438): string | null {
439 let cursor = start;
440 for (const heredoc of heredocs) {
441 let foundDelimiter = false;
442 while (cursor <= command.length) {
443 const newlineIndex = command.indexOf("\n", cursor);
444 const lineEnd = newlineIndex === -1 ? command.length : newlineIndex;
445 const line = command.slice(cursor, lineEnd).replace(/\r$/u, "");
446 const comparableLine = heredoc.stripTabs ? line.replace(/^\t+/u, "") : line;
447 cursor = newlineIndex === -1 ? command.length : newlineIndex + 1;
448 if (comparableLine === heredoc.delimiter) {
449 foundDelimiter = true;
450 break;
451 }
452 if (newlineIndex === -1) break;
453 }
454 if (!foundDelimiter) return null;
455 }
456
457 return command.slice(cursor).trim() || null;
458}
459
460function splitFirstShellCommand(command: string): ShellCommandSplit {
461 let quote: '"' | "'" | null = null;
462 let powerShellHereStringQuote: '"' | "'" | null = null;
463 let escaping = false;
464 let inBackticks = false;
465 let inComment = false;
466 let substitutionDepth = 0;
467 let parameterExpansionDepth = 0;
468 const heredocs: Heredoc[] = [];
469 const comments: ShellCommentRange[] = [];
470 let commentStart = 0;
471 let separatorBeforeHeredocs: ShellSeparator | null = null;
472
473 for (let index = 0; index < command.length; index += 1) {
474 const character = command[index]!;
475 if (powerShellHereStringQuote !== null) {
476 if (
477 character === powerShellHereStringQuote &&
478 command[index + 1] === "@" &&
479 (index === 0 || command[index - 1] === "\n")
480 ) {
481 powerShellHereStringQuote = null;
482 index += 1;
483 }
484 continue;
485 }
486 if (inComment) {
487 if (character !== "\n") continue;
488 inComment = false;
489 comments.push({ start: commentStart, end: index });
490 }
491 if (escaping) {
492 escaping = false;
493 continue;
494 }
495 if (character === "\\" && quote !== "'") {
496 escaping = true;
497 continue;
498 }
499 if (inBackticks) {
500 if (character === "`") inBackticks = false;
501 continue;
502 }
503 if (quote !== null) {
504 if (character === quote) quote = null;
505 continue;
506 }
507 if (
508 character === "@" &&
509 (command[index + 1] === '"' || command[index + 1] === "'") &&
510 (command[index + 2] === "\n" || (command[index + 2] === "\r" && command[index + 3] === "\n"))
511 ) {
512 powerShellHereStringQuote = command[index + 1] as '"' | "'";
513 index += 1;
514 continue;
515 }
516 if (character === '"' || character === "'") {
517 quote = character;
518 continue;
519 }
520 if (character === "`") {
521 inBackticks = true;
522 continue;
523 }
524 if (
525 character === "#" &&
526 (index === 0 || /\s/u.test(command[index - 1]!) || ";&|(".includes(command[index - 1]!))
527 ) {
528 inComment = true;
529 commentStart = index;
530 continue;
531 }
532 if (character === "$" && command[index + 1] === "{") {
533 parameterExpansionDepth += 1;
534 index += 1;
535 continue;
536 }
537 if (character === "{" && parameterExpansionDepth > 0) {
538 parameterExpansionDepth += 1;
539 continue;
540 }
541 if (character === "}" && parameterExpansionDepth > 0) {
542 parameterExpansionDepth -= 1;
543 continue;
544 }
545 if (character === "(") {
546 substitutionDepth += 1;
547 continue;
548 }
549 if (character === ")" && substitutionDepth > 0) {
550 substitutionDepth -= 1;
551 continue;
552 }
553 if (substitutionDepth > 0 || parameterExpansionDepth > 0) continue;
554
555 if (character === "<" && command[index + 1] === "<" && command[index + 2] !== "<") {
556 const stripTabs = command[index + 2] === "-";
557 const delimiter = readHeredocDelimiter(command, index + (stripTabs ? 3 : 2), stripTabs);
558 if (delimiter === null) {
559 return { firstCommand: command.trim(), remainingCommand: null, separator: null };
560 }
561 heredocs.push(delimiter.heredoc);
562 index = delimiter.end - 1;
563 continue;
564 }
565
566 const isDoubleOperator =
567 (character === "&" && command[index + 1] === "&") ||
568 (character === "|" && (command[index + 1] === "|" || command[index + 1] === "&"));
569 const isRedirectionAmpersand =
570 character === "&" &&
571 (command[index - 1] === ">" || command[index - 1] === "<" || command[index + 1] === ">");
572 if ((!isDoubleOperator && !";&|\n".includes(character)) || isRedirectionAmpersand) continue;
573
574 if (character === "\n" && heredocs.length > 0) {
575 const separator = separatorBeforeHeredocs;
576 const firstCommand = commandWithoutShellComments(
577 command,
578 separator?.index ?? index,
579 comments,
580 ).trimStart();
581 const commandBeforeHeredocs = separator
582 ? command.slice(separator.index + separator.length, index).trim()
583 : "";
584 const commandFollowingHeredocs = commandAfterHeredocs(command, index + 1, heredocs);
585 const remainingCommand = [commandBeforeHeredocs, commandFollowingHeredocs]
586 .filter((part): part is string => Boolean(part))
587 .join("\n");
588 return {
589 firstCommand,
590 remainingCommand: remainingCommand || null,
591 separator: separator
592 ? command.slice(separator.index, separator.index + separator.length)
593 : "\n",
594 };
595 }
596 if (heredocs.length > 0) {
597 separatorBeforeHeredocs ??= {
598 index,
599 length: isDoubleOperator ? 2 : 1,
600 };
601 if (isDoubleOperator) index += 1;
602 continue;
603 }
604
605 const firstCommand = commandWithoutShellComments(command, index, comments).trimStart();
606 let nextCommandIndex = index + (isDoubleOperator ? 2 : 1);
607 while (/\s/u.test(command[nextCommandIndex] ?? "")) nextCommandIndex += 1;
608 const nextCommand = command.slice(nextCommandIndex).trim();
609 return {
610 firstCommand,
611 remainingCommand: nextCommand || null,
612 separator: isDoubleOperator ? command.slice(index, index + 2) : character,
613 };
614 }
615
616 if (inComment) comments.push({ start: commentStart, end: command.length });
617 return {
618 firstCommand: commandWithoutShellComments(command, command.length, comments).trim(),
619 remainingCommand: null,
620 separator: null,
621 };
622}
623
624function commandWithoutLeadingShellComments(command: string): string | null {
625 let remainingCommand = command.trimStart();
626 while (remainingCommand.startsWith("#")) {
627 const newlineIndex = remainingCommand.indexOf("\n");
628 if (newlineIndex === -1) return null;
629 remainingCommand = remainingCommand.slice(newlineIndex + 1).trimStart();
630 }
631 return remainingCommand || null;
632}
633
634function withoutShellLineContinuations(command: string): string {
635 let normalizedCommand = "";
636 let quote: '"' | "'" | null = null;
637 let escaping = false;
638
639 for (let index = 0; index < command.length; index += 1) {
640 const character = command[index]!;
641 if (escaping) {
642 normalizedCommand += character;
643 escaping = false;
644 continue;
645 }
646 if (character === "\\" && quote !== "'") {
647 if (command[index + 1] === "\n") {
648 index += 1;
649 continue;
650 }
651 if (command[index + 1] === "\r" && command[index + 2] === "\n") {
652 index += 2;
653 continue;
654 }
655 normalizedCommand += character;
656 escaping = true;
657 continue;
658 }
659 if (quote !== null) {
660 if (character === quote) quote = null;
661 } else if (character === '"' || character === "'") {
662 quote = character;
663 }
664 normalizedCommand += character;
665 }
666
667 return normalizedCommand;
668}
669
670function indexAfterShellRedirection(tokens: ReadonlyArray<string>, index: number): number | null {
671 const token = tokens[index];
672 if (!token || /^[<>]\(/u.test(token)) return null;
673 const match = token.match(
674 /^(?:(?:(?:\d+|\*|\{[A-Za-z_][A-Za-z0-9_]*\})?(?:<<<|<<-|<<|<>|>>|>\||<&|>&|<|>))|&>>|&>)(.*)$/u,
675 );
676 if (!match) return null;
677 if (match[1]) return index + 1;
678 return tokens[index + 1] === undefined ? tokens.length + 1 : index + 2;
679}
680
681function serializeShellTokens(tokens: ReadonlyArray<string>): string {
682 return tokens.map((token) => `'${token.replaceAll("'", "'\\''")}'`).join(" ");
683}
684
685function transparentWrapperCommandIndex(
686 wrapper: string,
687 tokens: ReadonlyArray<string>,
688 index: number,
689): number | null {
690 if (wrapper === "bundle") {
691 return tokens[index + 1] === "exec" && tokens[index + 2] !== undefined ? index + 2 : null;
692 }
693
694 if (wrapper === "nohup") {
695 let targetIndex = index + 1;
696 if (tokens[targetIndex] === "--") targetIndex += 1;
697 const target = tokens[targetIndex];
698 return target && !target.startsWith("-") ? targetIndex : null;
699 }
700
701 if (wrapper === "script") {
702 // BSD `script` takes an output file before the optional command. Requiring
703 // an option and both operands avoids guessing about a plain `script file`.
704 return /^-[adkpqr]+$/u.test(tokens[index + 1] ?? "") && tokens[index + 3] !== undefined
705 ? index + 3
706 : null;
707 }
708
709 if (wrapper === "arch") {
710 if (/^-(?:arm64|arm64e|i386|x86_64)$/u.test(tokens[index + 1] ?? "")) {
711 return tokens[index + 2] !== undefined ? index + 2 : null;
712 }
713 return tokens[index + 1] === "-arch" && tokens[index + 3] !== undefined ? index + 3 : null;
714 }
715
716 if (wrapper === "timeout" || wrapper === "gtimeout") {
717 return /^(?:\d+(?:\.\d*)?|\.\d+)[smhd]?$/u.test(tokens[index + 1] ?? "") &&
718 tokens[index + 2] !== undefined
719 ? index + 2
720 : null;
721 }
722
723 return null;
724}
725
726function staticProgramName(value: string): string | null {
727 const trimmedValue = value.trim();
728 if (!trimmedValue || /^[A-Za-z][A-Za-z0-9+.-]*:(?![\\/])/u.test(trimmedValue)) return null;
729 const program = trimmedValue.split(/[\\/]/u).at(-1);
730 if (
731 !program ||
732 (/\s/u.test(program) && !/[\\/]/u.test(trimmedValue)) ||
733 NON_PROGRAM_PREFIX_CHARACTERS.includes(program[0] ?? "") ||
734 NON_PROGRAM_SUFFIX_CHARACTERS.includes(program.at(-1) ?? "")
735 ) {
736 return null;
737 }
738 return program;
739}
740
741function leadingPowerShellLiteral(command: string): string | null {
742 const input = command.trimStart();
743 const quote = input[0];
744 if (quote !== '"' && quote !== "'") return staticProgramName(input.match(/^\S+/u)?.[0] ?? "");
745
746 let value = "";
747 for (let index = 1; index < input.length; index += 1) {
748 const character = input[index]!;
749 if (character === "`" && input[index + 1] !== undefined) {
750 value += input[index + 1];
751 index += 1;
752 continue;
753 }
754 if (character === quote) {
755 if (quote === "'" && input[index + 1] === "'") {
756 value += "'";
757 index += 1;
758 continue;
759 }
760 return staticProgramName(value);
761 }
762 value += character;
763 }
764 return null;
765}
766
767function powerShellCallOperatorProgramName(command: string): string | null | undefined {
768 const match = command.match(/^\s*&\s+([\s\S]*)$/u);
769 return match ? leadingPowerShellLiteral(match[1]!) : undefined;
770}
771
772type PowerShellAssignment = {
773 readonly matched: boolean;
774 readonly program: string | null;
775};
776
777function powerShellAssignmentProgramName(
778 command: string,
779 depth: number,
780 remainingCommand: string | null,
781 segmentsRemaining: number,
782): PowerShellAssignment {
783 const assignment = command.match(
784 /^\s*\$(?:(env|global|local|script):)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*([\s\S]*)$/iu,
785 );
786 if (!assignment) return { matched: false, program: null };
787
788 if (assignment[1]?.toLowerCase() === "env") {
789 return {
790 matched: true,
791 program: remainingCommand
792 ? commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1)
793 : null,
794 };
795 }
796
797 const value = assignment[2]!.trim();
798 // The POSIX-oriented segment splitter does not balance PowerShell arrays or
799 // hashtables. Do not mistake a key after an internal semicolon for a command.
800 if (/^(?:\[ordered\]\s*)?@\s*[{(]/iu.test(value)) {
801 return { matched: true, program: null };
802 }
803 const calledProgram = powerShellCallOperatorProgramName(value);
804 if (calledProgram !== undefined) return { matched: true, program: calledProgram };
805
806 const directCommand = value.match(/^(?:@?\(\s*)?([A-Za-z][A-Za-z0-9_.-]*)\b/u)?.[1];
807 if (directCommand && !NON_DESCRIPTIVE_SHELL_PROGRAMS.has(directCommand.toLowerCase())) {
808 const parsedCommand = commandProgramNameInternal(value, depth + 1, "shell", segmentsRemaining);
809 return { matched: true, program: parsedCommand ?? directCommand };
810 }
811
812 return {
813 matched: true,
814 program: remainingCommand
815 ? commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1)
816 : null,
817 };
818}
819
820type WindowsShellPayload = {
821 readonly matched: boolean;
822 readonly program: string | null;
823};
824
825function windowsShellPayloadProgramName(
826 shell: string,
827 tokens: ReadonlyArray<string>,
828 start: number,
829 depth: number,
830 remainingCommand: string | null,
831 separator: string | null,
832 segmentsRemaining: number,
833): WindowsShellPayload {
834 const parsePayload = (payload: string | undefined): string | null => {
835 if (!payload) return null;
836 const command =
837 remainingCommand && separator ? `${payload} ${separator} ${remainingCommand}` : payload;
838 return commandProgramNameInternal(command, depth + 1, "shell", segmentsRemaining);
839 };
840
841 if (shell === "cmd" || shell === "cmd.exe") {
842 for (let index = start; index < tokens.length; index += 1) {
843 const option = tokens[index]!.toLowerCase();
844 if (option !== "/c" && option !== "/k") continue;
845 const payload = tokens[index + 1];
846 return {
847 matched: true,
848 program: parsePayload(payload),
849 };
850 }
851 return { matched: false, program: null };
852 }
853
854 for (let index = start; index < tokens.length; index += 1) {
855 const option = tokens[index]!.toLowerCase();
856 if (option === "-command" || option === "-c") {
857 const payload = tokens[index + 1];
858 return {
859 matched: true,
860 program: parsePayload(payload),
861 };
862 }
863 if (option === "-file" || option === "-f") {
864 return { matched: true, program: staticProgramName(tokens[index + 1] ?? "") };
865 }
866 if (option === "-encodedcommand" || option === "-enc" || option === "-e") {
867 return { matched: true, program: null };
868 }
869 if (POWERSHELL_OPTIONS_WITH_VALUE.has(option)) {
870 index += 1;
871 continue;
872 }
873 if (POWERSHELL_FLAGS.has(option)) continue;
874 if (!option.startsWith("-")) {
875 return { matched: true, program: staticProgramName(tokens[index]!) };
876 }
877 }
878 return { matched: false, program: null };
879}
880
881function startProcessProgramName(tokens: ReadonlyArray<string>, start: number): string | null {
882 for (let index = start; index < tokens.length; index += 1) {
883 const token = tokens[index]!;
884 const option = token.toLowerCase();
885 if (option === "-filepath") return staticProgramName(tokens[index + 1] ?? "");
886 if (START_PROCESS_FLAGS.has(option)) continue;
887 if (START_PROCESS_OPTIONS_WITH_VALUE.has(option)) {
888 if (tokens[index + 1] === undefined) return null;
889 index += 1;
890 continue;
891 }
892 if (token.startsWith("-")) return null;
893 return staticProgramName(token);
894 }
895 return null;
896}
897
898function literalAssignmentProgram(
899 token: string,
900): { readonly name: string; readonly program: string | null } | null {
901 const assignment = token.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/su);
902 if (!assignment) return null;
903 const name = assignment[1]!;
904 let value = assignment[2]!.trim();
905 if (!value || /[$`]/u.test(value)) return { name, program: null };
906
907 if (value.startsWith("(") && value.endsWith(")")) {
908 const arrayTokens = tokenizeShellCommand(value.slice(1, -1));
909 value = arrayTokens?.[0] ?? "";
910 } else if (/\s/u.test(value) && !/[\\/]/u.test(value)) {
911 return { name, program: null };
912 }
913
914 return { name, program: staticProgramName(value) };
915}
916
917function referencedCommandAlias(token: string): string | null {
918 const reference = token.match(
919 /^\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)(?:\[@\])?\})$/u,
920 );
921 return reference?.[1] ?? reference?.[2] ?? null;
922}
923
924function literalCommandAliasProgramName(command: string): string | null {
925 const aliases = new Map<string, string>();
926 let remainingCommand: string | null = command;
927 let controlFlowDepth = 0;
928
929 for (let segmentCount = 0; remainingCommand && segmentCount < 64; segmentCount += 1) {
930 const commandWithoutComments = commandWithoutLeadingShellComments(remainingCommand);
931 if (commandWithoutComments === null) return null;
932 const commandSplit = splitFirstShellCommand(commandWithoutComments);
933 const tokens = tokenizeShellCommand(withoutShellLineContinuations(commandSplit.firstCommand));
934 if (tokens === null) return null;
935
936 let commandIndex = tokens[0] === "do" || tokens[0] === "then" ? 1 : 0;
937 while (commandIndex < tokens.length) {
938 const indexAfterRedirection = indexAfterShellRedirection(tokens, commandIndex);
939 if (indexAfterRedirection !== null && indexAfterRedirection <= tokens.length) {
940 commandIndex = indexAfterRedirection;
941 continue;
942 }
943 if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(tokens[commandIndex] ?? "")) {
944 commandIndex += 1;
945 continue;
946 }
947 break;
948 }
949
950 const aliasName = referencedCommandAlias(tokens[commandIndex] ?? "");
951 const aliasedProgram = aliasName ? aliases.get(aliasName) : undefined;
952 if (aliasedProgram) return aliasedProgram;
953
954 const leadingToken = tokens[0];
955 if (leadingToken === "fi" || leadingToken === "done" || leadingToken === "esac") {
956 controlFlowDepth = Math.max(0, controlFlowDepth - 1);
957 }
958 if (
959 leadingToken === "if" ||
960 leadingToken === "for" ||
961 leadingToken === "while" ||
962 leadingToken === "until" ||
963 leadingToken === "select" ||
964 leadingToken === "case"
965 ) {
966 controlFlowDepth += 1;
967 }
968
969 if (controlFlowDepth === 0 && leadingToken === "unset") {
970 for (const name of tokens.slice(1)) aliases.delete(name);
971 }
972
973 const assignmentStart = tokens[0] === "export" ? 1 : 0;
974 const assignments = tokens.slice(assignmentStart).map(literalAssignmentProgram);
975 if (
976 controlFlowDepth === 0 &&
977 assignments.length > 0 &&
978 assignments.every((assignment) => assignment !== null)
979 ) {
980 for (const assignment of assignments) {
981 if (assignment.program) aliases.set(assignment.name, assignment.program);
982 else aliases.delete(assignment.name);
983 }
984 }
985
986 remainingCommand = commandSplit.remainingCommand;
987 }
988
989 return null;
990}
991
992function wrappedShellCommandProgramName(
993 wrapper: string,
994 tokens: ReadonlyArray<string>,
995 start: number,
996 depth: number,
997 remainingCommand: string | null,
998 segmentsRemaining: number,
999): string | null {
1000 let index = start;
1001
1002 if (wrapper === "command") {
1003 while (index < tokens.length) {
1004 const option = tokens[index]!;
1005 if (option === "--") {
1006 index += 1;
1007 break;
1008 }
1009 if (!option.startsWith("-") || option === "-") break;
1010 if (option !== "-p") return null;
1011 index += 1;
1012 }
1013 } else if (wrapper === "builtin") {
1014 if (tokens[index] === "--") index += 1;
1015 else if (tokens[index]?.startsWith("-")) return null;
1016 } else if (wrapper === "exec") {
1017 while (index < tokens.length) {
1018 const option = tokens[index]!;
1019 if (option === "--") {
1020 index += 1;
1021 break;
1022 }
1023 if (option === "-a") {
1024 if (tokens[index + 1] === undefined) return null;
1025 index += 2;
1026 continue;
1027 }
1028 if (/^-a.+/u.test(option) || /^-[cl]+$/u.test(option)) {
1029 index += 1;
1030 continue;
1031 }
1032 if (option.startsWith("-") && option !== "-") return null;
1033 break;
1034 }
1035 }
1036
1037 const wrappedTokens = tokens.slice(index);
1038 if (wrappedTokens.length === 0) return null;
1039 let targetIndex = 0;
1040 while (targetIndex < wrappedTokens.length) {
1041 const indexAfterRedirection = indexAfterShellRedirection(wrappedTokens, targetIndex);
1042 if (indexAfterRedirection === null || indexAfterRedirection > wrappedTokens.length) break;
1043 targetIndex = indexAfterRedirection;
1044 }
1045 const target = wrappedTokens[targetIndex];
1046 if (target && /^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(target)) return null;
1047
1048 const wrappedProgram = commandProgramNameInternal(
1049 serializeShellTokens(wrappedTokens),
1050 depth + 1,
1051 wrapper === "exec" ? "exec" : "shell",
1052 segmentsRemaining,
1053 );
1054 if (wrappedProgram !== null) return wrappedProgram;
1055
1056 if (
1057 wrapper !== "exec" &&
1058 target &&
1059 target === target.toLowerCase() &&
1060 NON_DESCRIPTIVE_SHELL_PROGRAMS.has(target) &&
1061 !TERMINAL_SHELL_PROGRAMS.has(target) &&
1062 remainingCommand
1063 ) {
1064 return commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1);
1065 }
1066 return null;
1067}
1068
1069function parseCommandProgramName(
1070 command: string,
1071 depth: number,
1072 context: CommandProgramContext,
1073 segmentsRemaining: number,
1074): string | null {
1075 if (depth >= 8 || segmentsRemaining <= 0) return null;
1076 const commandWithoutComments = commandWithoutLeadingShellComments(command);
1077 if (commandWithoutComments === null) return null;
1078 if (
1079 /^(?:catch|finally|for|foreach|function|if|param|switch|try|while)\s*[{(]/iu.test(
1080 commandWithoutComments,
1081 )
1082 ) {
1083 return null;
1084 }
1085 if (/^[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/u.test(commandWithoutComments)) return null;
1086 // `&&` and `||` inside a `[[ ... ]]` expression are not top-level command
1087 // separators. Keep the label conservative instead of scanning the test body.
1088 if (commandWithoutComments.startsWith("[[")) return null;
1089 const commandSplit = splitFirstShellCommand(commandWithoutComments);
1090 if (/^@["'](?:\r?\n)/u.test(commandSplit.firstCommand.trimStart())) {
1091 return commandSplit.remainingCommand
1092 ? commandProgramNameInternal(
1093 commandSplit.remainingCommand,
1094 depth,
1095 "shell",
1096 segmentsRemaining - 1,
1097 )
1098 : null;
1099 }
1100 const powerShellAssignment = powerShellAssignmentProgramName(
1101 commandSplit.firstCommand,
1102 depth,
1103 commandSplit.remainingCommand,
1104 segmentsRemaining,
1105 );
1106 if (powerShellAssignment.matched) return powerShellAssignment.program;
1107 const windowsPath = commandSplit.firstCommand.match(
1108 /^\s*((?:\.{1,2}|%[A-Za-z_][A-Za-z0-9_]*%|\$env:[A-Za-z_][A-Za-z0-9_]*)\\\S+)/iu,
1109 )?.[1];
1110 if (windowsPath) return staticProgramName(windowsPath);
1111 const tokens = tokenizeShellCommand(withoutShellLineContinuations(commandSplit.firstCommand));
1112 if (tokens === null) return null;
1113 const firstCharacter = commandSplit.firstCommand.trimStart()[0];
1114 if (
1115 tokens.length === 1 &&
1116 (firstCharacter === '"' || firstCharacter === "'") &&
1117 /[\s()=]/u.test(tokens[0] ?? "") &&
1118 !/[\\/]/u.test(tokens[0] ?? "")
1119 ) {
1120 return commandSplit.remainingCommand
1121 ? commandProgramNameInternal(
1122 commandSplit.remainingCommand,
1123 depth,
1124 context,
1125 segmentsRemaining - 1,
1126 )
1127 : null;
1128 }
1129 let index = 0;
1130 let wrapper: CommandWrapper | null = null;
1131 let executionContext = context;
1132 let sawAssignment = false;
1133 let sawRedirection = false;
1134
1135 while (index < tokens.length) {
1136 const token = tokens[index];
1137 if (!token) return null;
1138 const indexAfterRedirection = indexAfterShellRedirection(tokens, index);
1139 if (indexAfterRedirection !== null) {
1140 if (indexAfterRedirection > tokens.length) return null;
1141 sawRedirection = true;
1142 index = indexAfterRedirection;
1143 continue;
1144 }
1145 if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(token)) {
1146 sawAssignment = true;
1147 index += 1;
1148 continue;
1149 }
1150 if (executionContext === "shell" && token === ":") {
1151 return commandSplit.remainingCommand
1152 ? commandProgramNameInternal(
1153 commandSplit.remainingCommand,
1154 depth,
1155 executionContext,
1156 segmentsRemaining - 1,
1157 )
1158 : null;
1159 }
1160 if (
1161 NON_PROGRAM_PREFIX_CHARACTERS.includes(token[0] ?? "") &&
1162 !(token.startsWith("$") && token.includes("/"))
1163 ) {
1164 return executionContext === "shell" && token.startsWith("[") && commandSplit.remainingCommand
1165 ? commandProgramNameInternal(
1166 commandSplit.remainingCommand,
1167 depth,
1168 executionContext,
1169 segmentsRemaining - 1,
1170 )
1171 : null;
1172 }
1173 const tokenProgram = token.split(/[\\/]/).at(-1);
1174 const isUnqualifiedToken = token === tokenProgram;
1175 if (tokenProgram === "env" || tokenProgram === "sudo") {
1176 wrapper = tokenProgram;
1177 executionContext = "exec";
1178 index += 1;
1179 continue;
1180 }
1181 if (wrapper !== null && token === "--") {
1182 wrapper = null;
1183 index += 1;
1184 continue;
1185 }
1186 if (wrapper !== null && token.startsWith("-")) {
1187 if (wrapper === "env" && (token === "-S" || token === "--split-string")) {
1188 const splitCommand = tokens[index + 1];
1189 return splitCommand
1190 ? commandProgramNameInternal(splitCommand, depth + 1, executionContext, segmentsRemaining)
1191 : null;
1192 }
1193 if (wrapper === "env" && token.startsWith("--split-string=")) {
1194 return commandProgramNameInternal(
1195 token.slice("--split-string=".length),
1196 depth + 1,
1197 executionContext,
1198 segmentsRemaining,
1199 );
1200 }
1201 if (COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(token)) {
1202 if (tokens[index + 1] === undefined) return null;
1203 index += 2;
1204 continue;
1205 }
1206 if (COMMAND_WRAPPER_FLAGS[wrapper].has(token)) {
1207 index += 1;
1208 continue;
1209 }
1210 const equalsIndex = token.indexOf("=");
1211 if (token.startsWith("--") && equalsIndex > 2) {
1212 if (!COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(token.slice(0, equalsIndex))) {
1213 return null;
1214 }
1215 index += 1;
1216 continue;
1217 }
1218 if (/^-[A-Za-z].+/.test(token) && !token.startsWith("--")) {
1219 let consumesNextToken = false;
1220 for (const [optionIndex, option] of token.slice(1).split("").entries()) {
1221 const shortOption = `-${option}`;
1222 if (COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(shortOption)) {
1223 consumesNextToken = optionIndex === token.length - 2;
1224 break;
1225 }
1226 if (!COMMAND_WRAPPER_FLAGS[wrapper].has(shortOption)) return null;
1227 }
1228 if (consumesNextToken && tokens[index + 1] === undefined) return null;
1229 index += consumesNextToken ? 2 : 1;
1230 continue;
1231 }
1232 return null;
1233 }
1234 const shellProgram = tokenProgram?.replace(/\.exe$/i, "").toLowerCase();
1235 if (shellProgram && SHELL_PROGRAMS.has(shellProgram)) {
1236 const scriptIndex = shellCommandArgumentIndex(shellProgram, tokens, index + 1);
1237 if (scriptIndex !== null) {
1238 const script = tokens[scriptIndex];
1239 return script
1240 ? commandProgramNameInternal(script, depth + 1, "shell", segmentsRemaining)
1241 : null;
1242 }
1243 }
1244 const lowerTokenProgram = tokenProgram?.toLowerCase();
1245 if (lowerTokenProgram && WINDOWS_SHELL_PROGRAMS.has(lowerTokenProgram)) {
1246 const payload = windowsShellPayloadProgramName(
1247 lowerTokenProgram,
1248 tokens,
1249 index + 1,
1250 depth,
1251 commandSplit.remainingCommand,
1252 commandSplit.separator,
1253 segmentsRemaining,
1254 );
1255 if (payload.matched) return payload.program;
1256 }
1257 if (lowerTokenProgram === "start-process") {
1258 const startedProgram = startProcessProgramName(tokens, index + 1);
1259 if (startedProgram !== null) return startedProgram;
1260 }
1261 if (
1262 executionContext === "shell" &&
1263 isUnqualifiedToken &&
1264 tokenProgram &&
1265 SHELL_PRECOMMAND_MODIFIERS.has(tokenProgram)
1266 ) {
1267 index += 1;
1268 if (tokenProgram === "time" && tokens[index] === "-p") index += 1;
1269 if (tokens[index]?.startsWith("-")) return null;
1270 continue;
1271 }
1272 if (isUnqualifiedToken && tokenProgram) {
1273 const targetIndex = transparentWrapperCommandIndex(tokenProgram, tokens, index);
1274 if (targetIndex !== null) {
1275 const wrappedProgram = commandProgramNameInternal(
1276 serializeShellTokens(tokens.slice(targetIndex)),
1277 depth + 1,
1278 "exec",
1279 segmentsRemaining,
1280 );
1281 if (wrappedProgram !== null) return wrappedProgram;
1282 }
1283 }
1284 if (isUnqualifiedToken && tokenProgram && SHELL_COMMAND_WRAPPERS.has(tokenProgram)) {
1285 return wrappedShellCommandProgramName(
1286 tokenProgram,
1287 tokens,
1288 index + 1,
1289 depth,
1290 commandSplit.remainingCommand,
1291 segmentsRemaining,
1292 );
1293 }
1294 if (
1295 (executionContext === "shell" ||
1296 (wrapper === "sudo" && tokenProgram && SKIPPABLE_SUDO_PROBES.has(tokenProgram))) &&
1297 isUnqualifiedToken &&
1298 tokenProgram &&
1299 NON_DESCRIPTIVE_SHELL_PROGRAMS.has(tokenProgram) &&
1300 (!TERMINAL_SHELL_PROGRAMS.has(tokenProgram) ||
1301 (tokenProgram === "false" && commandSplit.separator !== "&&")) &&
1302 commandSplit.remainingCommand
1303 ) {
1304 return commandProgramNameInternal(
1305 commandSplit.remainingCommand,
1306 depth,
1307 "shell",
1308 segmentsRemaining - 1,
1309 );
1310 }
1311 if (
1312 executionContext === "shell" &&
1313 isUnqualifiedToken &&
1314 lowerTokenProgram &&
1315 POWERSHELL_SETUP_PROGRAMS.has(lowerTokenProgram) &&
1316 commandSplit.remainingCommand
1317 ) {
1318 return commandProgramNameInternal(
1319 commandSplit.remainingCommand,
1320 depth,
1321 "shell",
1322 segmentsRemaining - 1,
1323 );
1324 }
1325 if (
1326 !tokenProgram ||
1327 (isUnqualifiedToken && NON_DESCRIPTIVE_SHELL_PROGRAMS.has(tokenProgram)) ||
1328 NON_PROGRAM_PREFIX_CHARACTERS.includes(tokenProgram[0] ?? "") ||
1329 NON_PROGRAM_SUFFIX_CHARACTERS.includes(tokenProgram.at(-1) ?? "") ||
1330 tokenProgram.endsWith("()") ||
1331 /^[A-Za-z_][A-Za-z0-9_]*\(\)\{$/u.test(tokenProgram)
1332 ) {
1333 return null;
1334 }
1335 return tokenProgram || null;
1336 }
1337
1338 if ((sawAssignment || sawRedirection) && wrapper === null && commandSplit.remainingCommand) {
1339 return commandProgramNameInternal(
1340 commandSplit.remainingCommand,
1341 depth,
1342 executionContext,
1343 segmentsRemaining - 1,
1344 );
1345 }
1346 return null;
1347}
1348
1349function commandProgramNameInternal(
1350 command: string,
1351 depth: number,
1352 context: CommandProgramContext,
1353 segmentsRemaining = MAX_COMMAND_SEGMENTS,
1354): string | null {
1355 if (segmentsRemaining <= 0) return null;
1356 const calledProgram = powerShellCallOperatorProgramName(command);
1357 if (calledProgram !== undefined) return calledProgram;
1358 return (
1359 parseCommandProgramName(command, depth, context, segmentsRemaining) ??
1360 (context === "shell" ? literalCommandAliasProgramName(command) : null)
1361 );
1362}
1363
1364export function commandProgramName(command: string, depth = 0): string | null {
1365 return commandProgramNameInternal(command, depth, "shell", MAX_COMMAND_SEGMENTS);
1366}
1367
1368// Escape bytes and other control characters render as invisible gaps; display
1369// shows them as Unicode control pictures (ESC becomes ␛) instead. Tab, newline
1370// and carriage return lay out as whitespace, so CRLF scripts stay unmarked.
1371const CONTROL_CHARACTERS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu;
1372
1373export function commandDisplayText(command: string): string {
1374 return withVisibleControlCharacters(withoutShellWrapper(command));
1375}
1376
1377export function withVisibleControlCharacters(text: string): string {
1378 return text.replace(CONTROL_CHARACTERS, (character) =>
1379 character === "\u007f" ? "␡" : String.fromCharCode(0x2400 + character.charCodeAt(0)),
1380 );
1381}
1382
1383// A wrapper whose quoting does not balance is kept: the script's end cannot be
1384// known, which happens when Codex's secret redaction removes the backslash of
1385// an escaped quote inside `-lc "…"`.
1386function withoutShellWrapper(command: string): string {
1387 const trimmed = command.trim();
1388 const split = splitFirstShellCommand(trimmed);
1389 if (split.remainingCommand !== null) return trimmed;
1390 const tokens = tokenizeShellCommand(trimmed);
1391 const executable = tokens?.[0]?.split(/[\\/]/u).at(-1);
1392 const program = executable?.replace(/\.exe$/iu, "");
1393 if (!tokens || !executable || !program) return trimmed;
1394 const scriptIndex = SHELL_PROGRAMS.has(program)
1395 ? shellCommandArgumentIndex(program, tokens, 1)
1396 : WINDOWS_SHELL_PROGRAMS.has(executable.toLowerCase())
1397 ? windowsShellScriptIndex(program.toLowerCase(), tokens)
1398 : null;
1399 // Positional arguments can affect the script; keep those invocations intact.
1400 if (scriptIndex === null || scriptIndex !== tokens.length - 1) return trimmed;
1401 return tokens[scriptIndex]?.trim() || trimmed;
1402}
1403
1404function windowsShellScriptIndex(shell: string, tokens: ReadonlyArray<string>): number | null {
1405 for (let index = 1; index < tokens.length; index += 1) {
1406 const option = tokens[index]!.toLowerCase();
1407 if (shell === "cmd") {
1408 if (option === "/c") return index + 1;
1409 if (!option.startsWith("/")) return null;
1410 continue;
1411 }
1412 if (option === "-command" || option === "-c") return index + 1;
1413 if (POWERSHELL_OPTIONS_WITH_VALUE.has(option)) {
1414 index += 1;
1415 continue;
1416 }
1417 if (!POWERSHELL_FLAGS.has(option)) return null;
1418 }
1419 return null;
1420}
1421
1422const POWERSHELL_PROGRAMS = new Set(["powershell", "pwsh"]);
1423
1424const POWERSHELL_VERBS = new Set(
1425 `Add Approve Assert Backup Block Build Checkpoint Clear Close Compare Complete Compress Confirm Connect Convert ConvertFrom ConvertTo Copy Debug Deny Deploy Disable Disconnect Dismount Edit Enable Enter Exit Expand Export Find ForEach Format Get Grant Group Hide Import Initialize Install Invoke Join Limit Lock Measure Merge Mount Move New Open Optimize Out Ping Pop Protect Publish Push Read Receive Redo Register Remove Rename Repair Request Reset Resize Resolve Restart Restore Resume Revoke Save Search Select Send Set Show Skip Sort Split Start Step Stop Submit Suspend Switch Sync Tee Test Trace Unblock Undo Uninstall Unlock Unprotect Unpublish Unregister Update Use Wait Watch Where Write`.split(
1426 " ",
1427 ),
1428);
1429
1430function isPowerShellCmdlet(word: string): boolean {
1431 const cmdlet = /^([A-Z][a-z]+(?:[A-Z][a-z]+)?)-[A-Z][A-Za-z]*$/u.exec(word);
1432 return cmdlet !== null && POWERSHELL_VERBS.has(cmdlet[1]!);
1433}
1434
1435export function commandHighlightLanguage(command: string): "powershell" | "shellscript" {
1436 const program = /^(?:&\s*)?(?:"([^"]*)"|'([^']*)'|(\S+))/u.exec(command.trim());
1437 const name = (program?.[1] ?? program?.[2] ?? program?.[3] ?? "")
1438 .split(/[\\/]/u)
1439 .at(-1)
1440 ?.toLowerCase()
1441 .replace(/\.exe$/u, "");
1442 if (name && POWERSHELL_PROGRAMS.has(name)) return "powershell";
1443 return isPowerShellScript(command) ? "powershell" : "shellscript";
1444}
1445
1446function isPowerShellScript(command: string): boolean {
1447 let rest: string | null = command.trim();
1448 if (/^&\s*\S/u.test(rest)) return true;
1449 for (let segment = 0; rest && segment < MAX_COMMAND_SEGMENTS; segment += 1) {
1450 const { firstCommand, remainingCommand } = splitFirstShellCommand(rest);
1451 const statement = firstCommand.trim();
1452 if (
1453 /^\$(?:env|global|local|script):/iu.test(statement) ||
1454 /^\$[A-Za-z_]\w*\s+=/u.test(statement) ||
1455 isPowerShellCmdlet(statement.match(/^\S+/u)?.[0] ?? "")
1456 ) {
1457 return true;
1458 }
1459 rest = remainingCommand;
1460 }
1461 return false;
1462}