Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

commandLabel.ts

1,454 lines43.6 KB

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(tokens: ReadonlyArray<string>, start: number): number | null {
197 for (let index = start; index < tokens.length; index += 1) {
198 const option = tokens[index]!;
199 if (option === "--" || !option.startsWith("-")) return null;
200 if (SHELL_OPTIONS_WITH_VALUE.has(option)) {
201 index += 1;
202 continue;
203 }
204 if (option === "--command" || /^-[a-zA-Z]*c[a-zA-Z]*$/.test(option)) return index + 1;
205 }
206 return null;
208​
209const COMMAND_WRAPPER_OPTIONS_WITH_VALUE: Record<CommandWrapper, ReadonlySet<string>> = {
210 env: new Set(["-C", "--chdir", "-S", "--split-string", "-u", "--unset"]),
211 sudo: new Set(["-C", "--close-from", "-D", "--chdir", "-g", "--group", "-u", "--user"]),
212};
213​
214const COMMAND_WRAPPER_FLAGS: Record<CommandWrapper, ReadonlySet<string>> = {
215 env: new Set(["-0", "--null", "-i", "--ignore-environment", "--debug", "-v"]),
216 sudo: new Set(["-A", "--askpass", "-b", "--background", "-E", "-H", "-i", "-n", "-S"]),
217};
218​
219function tokenizeShellCommand(command: string): string[] | null {
220 const input = command.trim();
221 const tokens: string[] = [];
222 let current = "";
223 let quote: '"' | "'" | null = null;
224 let escaping = false;
225 let inBackticks = false;
226 let substitutionDepth = 0;
227 let parameterExpansionDepth = 0;
228 let tokenStarted = false;
229​
230 for (let index = 0; index < input.length; index += 1) {
231 const character = input[index]!;
232 if (escaping) {
233 current += character;
234 escaping = false;
235 tokenStarted = true;
236 continue;
237 }
238 if (character === "\\" && quote !== "'") {
239 const nextCharacter = input[index + 1];
240 const isWindowsPath = quote === null && /^(?:[A-Za-z]:|\.{1,2})(?:\\[^\s]*)?$/u.test(current);
241 if (
242 (quote === '"' || isWindowsPath) &&
243 nextCharacter !== undefined &&
244 nextCharacter !== '"' &&
245 nextCharacter !== "\\" &&
246 nextCharacter !== "$" &&
247 nextCharacter !== "`" &&
248 nextCharacter !== "\n"
249 ) {
250 current += character;
251 tokenStarted = true;
252 continue;
253 }
254 escaping = true;
255 tokenStarted = true;
256 continue;
257 }
258 if (inBackticks) {
259 current += character;
260 if (character === "`") inBackticks = false;
261 tokenStarted = true;
262 continue;
263 }
264 if (quote !== null) {
265 if (character === quote) {
266 quote = null;
267 } else {
268 current += character;
269 }
270 tokenStarted = true;
271 continue;
272 }
273 if (character === "`") {
274 current += character;
275 inBackticks = true;
276 tokenStarted = true;
277 continue;
278 }
279 if (character === "$" && input[index + 1] === "{") {
280 current += "${";
281 parameterExpansionDepth += 1;
282 tokenStarted = true;
283 index += 1;
284 continue;
285 }
286 if (character === "{" && parameterExpansionDepth > 0) {
287 current += character;
288 parameterExpansionDepth += 1;
289 tokenStarted = true;
290 continue;
291 }
292 if (character === "}" && parameterExpansionDepth > 0) {
293 current += character;
294 parameterExpansionDepth -= 1;
295 tokenStarted = true;
296 continue;
297 }
298 if (character === "$" && input[index + 1] === "(") {
299 current += "$(";
300 substitutionDepth += 1;
301 tokenStarted = true;
302 index += 1;
303 continue;
304 }
305 if (character === "(") {
306 current += character;
307 substitutionDepth += 1;
308 tokenStarted = true;
309 continue;
310 }
311 if (character === ")" && substitutionDepth > 0) {
312 current += character;
313 substitutionDepth -= 1;
314 tokenStarted = true;
315 continue;
316 }
317 if (character === '"' || character === "'") {
318 quote = character;
319 tokenStarted = true;
320 continue;
321 }
322 if (/\s/u.test(character)) {
323 if (substitutionDepth > 0 || parameterExpansionDepth > 0) {
324 current += character;
325 tokenStarted = true;
326 continue;
327 }
328 if (tokenStarted) {
329 tokens.push(current);
330 current = "";
331 tokenStarted = false;
332 }
333 continue;
334 }
335 current += character;
336 tokenStarted = true;
337 }
338​
339 if (
340 quote !== null ||
341 escaping ||
342 inBackticks ||
343 substitutionDepth > 0 ||
344 parameterExpansionDepth > 0
345 ) {
346 return null;
347 }
348 if (tokenStarted) tokens.push(current);
349 return tokens;
351​
352type ShellCommandSplit = {
353 readonly firstCommand: string;
354 readonly remainingCommand: string | null;
355 readonly separator: string | null;
356};
357​
358type Heredoc = {
359 readonly delimiter: string;
360 readonly stripTabs: boolean;
361};
362​
363type ShellSeparator = {
364 readonly index: number;
365 readonly length: number;
366};
367​
368type ShellCommentRange = {
369 readonly start: number;
370 readonly end: number;
371};
372​
373function commandWithoutShellComments(
374 command: string,
375 end: number,
376 comments: ReadonlyArray<ShellCommentRange>,
377): string {
378 let result = "";
379 let cursor = 0;
380 for (const comment of comments) {
381 if (comment.start >= end) break;
382 result += command.slice(cursor, comment.start);
383 cursor = Math.min(comment.end, end);
384 }
385 return result + command.slice(cursor, end);
387​
388function readHeredocDelimiter(
389 command: string,
390 start: number,
391 stripTabs: boolean,
392): { readonly heredoc: Heredoc; readonly end: number } | null {
393 let index = start;
394 while (command[index] === " " || command[index] === "\t") index += 1;
395​
396 let delimiter = "";
397 let quote: '"' | "'" | null = null;
398 let escaping = false;
399 for (; index < command.length; index += 1) {
400 const character = command[index]!;
401 if (escaping) {
402 delimiter += character;
403 escaping = false;
404 continue;
405 }
406 if (character === "\\" && quote !== "'") {
407 escaping = true;
408 continue;
409 }
410 if (quote !== null) {
411 if (character === quote) quote = null;
412 else delimiter += character;
413 continue;
414 }
415 if (character === '"' || character === "'") {
416 quote = character;
417 continue;
418 }
419 if (/\s/u.test(character) || ";&|<>()".includes(character)) break;
420 delimiter += character;
421 }
422​
423 if (!delimiter || quote !== null || escaping) return null;
424 return { heredoc: { delimiter, stripTabs }, end: index };
426​
427function commandAfterHeredocs(
428 command: string,
429 start: number,
430 heredocs: ReadonlyArray<Heredoc>,
431): string | null {
432 let cursor = start;
433 for (const heredoc of heredocs) {
434 let foundDelimiter = false;
435 while (cursor <= command.length) {
436 const newlineIndex = command.indexOf("\n", cursor);
437 const lineEnd = newlineIndex === -1 ? command.length : newlineIndex;
438 const line = command.slice(cursor, lineEnd).replace(/\r$/u, "");
439 const comparableLine = heredoc.stripTabs ? line.replace(/^\t+/u, "") : line;
440 cursor = newlineIndex === -1 ? command.length : newlineIndex + 1;
441 if (comparableLine === heredoc.delimiter) {
442 foundDelimiter = true;
443 break;
444 }
445 if (newlineIndex === -1) break;
446 }
447 if (!foundDelimiter) return null;
448 }
449​
450 return command.slice(cursor).trim() || null;
452​
453function splitFirstShellCommand(command: string): ShellCommandSplit {
454 let quote: '"' | "'" | null = null;
455 let powerShellHereStringQuote: '"' | "'" | null = null;
456 let escaping = false;
457 let inBackticks = false;
458 let inComment = false;
459 let substitutionDepth = 0;
460 let parameterExpansionDepth = 0;
461 const heredocs: Heredoc[] = [];
462 const comments: ShellCommentRange[] = [];
463 let commentStart = 0;
464 let separatorBeforeHeredocs: ShellSeparator | null = null;
465​
466 for (let index = 0; index < command.length; index += 1) {
467 const character = command[index]!;
468 if (powerShellHereStringQuote !== null) {
469 if (
470 character === powerShellHereStringQuote &&
471 command[index + 1] === "@" &&
472 (index === 0 || command[index - 1] === "\n")
473 ) {
474 powerShellHereStringQuote = null;
475 index += 1;
476 }
477 continue;
478 }
479 if (inComment) {
480 if (character !== "\n") continue;
481 inComment = false;
482 comments.push({ start: commentStart, end: index });
483 }
484 if (escaping) {
485 escaping = false;
486 continue;
487 }
488 if (character === "\\" && quote !== "'") {
489 escaping = true;
490 continue;
491 }
492 if (inBackticks) {
493 if (character === "`") inBackticks = false;
494 continue;
495 }
496 if (quote !== null) {
497 if (character === quote) quote = null;
498 continue;
499 }
500 if (
501 character === "@" &&
502 (command[index + 1] === '"' || command[index + 1] === "'") &&
503 (command[index + 2] === "\n" || (command[index + 2] === "\r" && command[index + 3] === "\n"))
504 ) {
505 powerShellHereStringQuote = command[index + 1] as '"' | "'";
506 index += 1;
507 continue;
508 }
509 if (character === '"' || character === "'") {
510 quote = character;
511 continue;
512 }
513 if (character === "`") {
514 inBackticks = true;
515 continue;
516 }
517 if (
518 character === "#" &&
519 (index === 0 || /\s/u.test(command[index - 1]!) || ";&|(".includes(command[index - 1]!))
520 ) {
521 inComment = true;
522 commentStart = index;
523 continue;
524 }
525 if (character === "$" && command[index + 1] === "{") {
526 parameterExpansionDepth += 1;
527 index += 1;
528 continue;
529 }
530 if (character === "{" && parameterExpansionDepth > 0) {
531 parameterExpansionDepth += 1;
532 continue;
533 }
534 if (character === "}" && parameterExpansionDepth > 0) {
535 parameterExpansionDepth -= 1;
536 continue;
537 }
538 if (character === "(") {
539 substitutionDepth += 1;
540 continue;
541 }
542 if (character === ")" && substitutionDepth > 0) {
543 substitutionDepth -= 1;
544 continue;
545 }
546 if (substitutionDepth > 0 || parameterExpansionDepth > 0) continue;
547​
548 if (character === "<" && command[index + 1] === "<" && command[index + 2] !== "<") {
549 const stripTabs = command[index + 2] === "-";
550 const delimiter = readHeredocDelimiter(command, index + (stripTabs ? 3 : 2), stripTabs);
551 if (delimiter === null) {
552 return { firstCommand: command.trim(), remainingCommand: null, separator: null };
553 }
554 heredocs.push(delimiter.heredoc);
555 index = delimiter.end - 1;
556 continue;
557 }
558​
559 const isDoubleOperator =
560 (character === "&" && command[index + 1] === "&") ||
561 (character === "|" && (command[index + 1] === "|" || command[index + 1] === "&"));
562 const isRedirectionAmpersand =
563 character === "&" &&
564 (command[index - 1] === ">" || command[index - 1] === "<" || command[index + 1] === ">");
565 if ((!isDoubleOperator && !";&|\n".includes(character)) || isRedirectionAmpersand) continue;
566​
567 if (character === "\n" && heredocs.length > 0) {
568 const separator = separatorBeforeHeredocs;
569 const firstCommand = commandWithoutShellComments(
570 command,
571 separator?.index ?? index,
572 comments,
573 ).trimStart();
574 const commandBeforeHeredocs = separator
575 ? command.slice(separator.index + separator.length, index).trim()
576 : "";
577 const commandFollowingHeredocs = commandAfterHeredocs(command, index + 1, heredocs);
578 const remainingCommand = [commandBeforeHeredocs, commandFollowingHeredocs]
579 .filter((part): part is string => Boolean(part))
580 .join("\n");
581 return {
582 firstCommand,
583 remainingCommand: remainingCommand || null,
584 separator: separator
585 ? command.slice(separator.index, separator.index + separator.length)
586 : "\n",
587 };
588 }
589 if (heredocs.length > 0) {
590 separatorBeforeHeredocs ??= {
591 index,
592 length: isDoubleOperator ? 2 : 1,
593 };
594 if (isDoubleOperator) index += 1;
595 continue;
596 }
597​
598 const firstCommand = commandWithoutShellComments(command, index, comments).trimStart();
599 let nextCommandIndex = index + (isDoubleOperator ? 2 : 1);
600 while (/\s/u.test(command[nextCommandIndex] ?? "")) nextCommandIndex += 1;
601 const nextCommand = command.slice(nextCommandIndex).trim();
602 return {
603 firstCommand,
604 remainingCommand: nextCommand || null,
605 separator: isDoubleOperator ? command.slice(index, index + 2) : character,
606 };
607 }
608​
609 if (inComment) comments.push({ start: commentStart, end: command.length });
610 return {
611 firstCommand: commandWithoutShellComments(command, command.length, comments).trim(),
612 remainingCommand: null,
613 separator: null,
614 };
616​
617function commandWithoutLeadingShellComments(command: string): string | null {
618 let remainingCommand = command.trimStart();
619 while (remainingCommand.startsWith("#")) {
620 const newlineIndex = remainingCommand.indexOf("\n");
621 if (newlineIndex === -1) return null;
622 remainingCommand = remainingCommand.slice(newlineIndex + 1).trimStart();
623 }
624 return remainingCommand || null;
626​
627function withoutShellLineContinuations(command: string): string {
628 let normalizedCommand = "";
629 let quote: '"' | "'" | null = null;
630 let escaping = false;
631​
632 for (let index = 0; index < command.length; index += 1) {
633 const character = command[index]!;
634 if (escaping) {
635 normalizedCommand += character;
636 escaping = false;
637 continue;
638 }
639 if (character === "\\" && quote !== "'") {
640 if (command[index + 1] === "\n") {
641 index += 1;
642 continue;
643 }
644 if (command[index + 1] === "\r" && command[index + 2] === "\n") {
645 index += 2;
646 continue;
647 }
648 normalizedCommand += character;
649 escaping = true;
650 continue;
651 }
652 if (quote !== null) {
653 if (character === quote) quote = null;
654 } else if (character === '"' || character === "'") {
655 quote = character;
656 }
657 normalizedCommand += character;
658 }
659​
660 return normalizedCommand;
662​
663function indexAfterShellRedirection(tokens: ReadonlyArray<string>, index: number): number | null {
664 const token = tokens[index];
665 if (!token || /^[<>]\(/u.test(token)) return null;
666 const match = token.match(
667 /^(?:(?:(?:\d+|\*|\{[A-Za-z_][A-Za-z0-9_]*\})?(?:<<<|<<-|<<|<>|>>|>\||<&|>&|<|>))|&>>|&>)(.*)$/u,
668 );
669 if (!match) return null;
670 if (match[1]) return index + 1;
671 return tokens[index + 1] === undefined ? tokens.length + 1 : index + 2;
673​
674function serializeShellTokens(tokens: ReadonlyArray<string>): string {
675 return tokens.map((token) => `'${token.replaceAll("'", "'\\''")}'`).join(" ");
677​
678function transparentWrapperCommandIndex(
679 wrapper: string,
680 tokens: ReadonlyArray<string>,
681 index: number,
682): number | null {
683 if (wrapper === "bundle") {
684 return tokens[index + 1] === "exec" && tokens[index + 2] !== undefined ? index + 2 : null;
685 }
686​
687 if (wrapper === "nohup") {
688 let targetIndex = index + 1;
689 if (tokens[targetIndex] === "--") targetIndex += 1;
690 const target = tokens[targetIndex];
691 return target && !target.startsWith("-") ? targetIndex : null;
692 }
693​
694 if (wrapper === "script") {
695 // BSD `script` takes an output file before the optional command. Requiring
696 // an option and both operands avoids guessing about a plain `script file`.
697 return /^-[adkpqr]+$/u.test(tokens[index + 1] ?? "") && tokens[index + 3] !== undefined
698 ? index + 3
699 : null;
700 }
701​
702 if (wrapper === "arch") {
703 if (/^-(?:arm64|arm64e|i386|x86_64)$/u.test(tokens[index + 1] ?? "")) {
704 return tokens[index + 2] !== undefined ? index + 2 : null;
705 }
706 return tokens[index + 1] === "-arch" && tokens[index + 3] !== undefined ? index + 3 : null;
707 }
708​
709 if (wrapper === "timeout" || wrapper === "gtimeout") {
710 return /^(?:\d+(?:\.\d*)?|\.\d+)[smhd]?$/u.test(tokens[index + 1] ?? "") &&
711 tokens[index + 2] !== undefined
712 ? index + 2
713 : null;
714 }
715​
716 return null;
718​
719function staticProgramName(value: string): string | null {
720 const trimmedValue = value.trim();
721 if (!trimmedValue || /^[A-Za-z][A-Za-z0-9+.-]*:(?![\\/])/u.test(trimmedValue)) return null;
722 const program = trimmedValue.split(/[\\/]/u).at(-1);
723 if (
724 !program ||
725 (/\s/u.test(program) && !/[\\/]/u.test(trimmedValue)) ||
726 NON_PROGRAM_PREFIX_CHARACTERS.includes(program[0] ?? "") ||
727 NON_PROGRAM_SUFFIX_CHARACTERS.includes(program.at(-1) ?? "")
728 ) {
729 return null;
730 }
731 return program;
733​
734function leadingPowerShellLiteral(command: string): string | null {
735 const input = command.trimStart();
736 const quote = input[0];
737 if (quote !== '"' && quote !== "'") return staticProgramName(input.match(/^\S+/u)?.[0] ?? "");
738​
739 let value = "";
740 for (let index = 1; index < input.length; index += 1) {
741 const character = input[index]!;
742 if (character === "`" && input[index + 1] !== undefined) {
743 value += input[index + 1];
744 index += 1;
745 continue;
746 }
747 if (character === quote) {
748 if (quote === "'" && input[index + 1] === "'") {
749 value += "'";
750 index += 1;
751 continue;
752 }
753 return staticProgramName(value);
754 }
755 value += character;
756 }
757 return null;
759​
760function powerShellCallOperatorProgramName(command: string): string | null | undefined {
761 const match = command.match(/^\s*&\s+([\s\S]*)$/u);
762 return match ? leadingPowerShellLiteral(match[1]!) : undefined;
764​
765type PowerShellAssignment = {
766 readonly matched: boolean;
767 readonly program: string | null;
768};
769​
770function powerShellAssignmentProgramName(
771 command: string,
772 depth: number,
773 remainingCommand: string | null,
774 segmentsRemaining: number,
775): PowerShellAssignment {
776 const assignment = command.match(
777 /^\s*\$(?:(env|global|local|script):)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*([\s\S]*)$/iu,
778 );
779 if (!assignment) return { matched: false, program: null };
780​
781 if (assignment[1]?.toLowerCase() === "env") {
782 return {
783 matched: true,
784 program: remainingCommand
785 ? commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1)
786 : null,
787 };
788 }
789​
790 const value = assignment[2]!.trim();
791 // The POSIX-oriented segment splitter does not balance PowerShell arrays or
792 // hashtables. Do not mistake a key after an internal semicolon for a command.
793 if (/^(?:\[ordered\]\s*)?@\s*[{(]/iu.test(value)) {
794 return { matched: true, program: null };
795 }
796 const calledProgram = powerShellCallOperatorProgramName(value);
797 if (calledProgram !== undefined) return { matched: true, program: calledProgram };
798​
799 const directCommand = value.match(/^(?:@?\(\s*)?([A-Za-z][A-Za-z0-9_.-]*)\b/u)?.[1];
800 if (directCommand && !NON_DESCRIPTIVE_SHELL_PROGRAMS.has(directCommand.toLowerCase())) {
801 const parsedCommand = commandProgramNameInternal(value, depth + 1, "shell", segmentsRemaining);
802 return { matched: true, program: parsedCommand ?? directCommand };
803 }
804​
805 return {
806 matched: true,
807 program: remainingCommand
808 ? commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1)
809 : null,
810 };
812​
813type WindowsShellPayload = {
814 readonly matched: boolean;
815 readonly program: string | null;
816};
817​
818function windowsShellPayloadProgramName(
819 shell: string,
820 tokens: ReadonlyArray<string>,
821 start: number,
822 depth: number,
823 remainingCommand: string | null,
824 separator: string | null,
825 segmentsRemaining: number,
826): WindowsShellPayload {
827 const parsePayload = (payload: string | undefined): string | null => {
828 if (!payload) return null;
829 const command =
830 remainingCommand && separator ? `${payload} ${separator} ${remainingCommand}` : payload;
831 return commandProgramNameInternal(command, depth + 1, "shell", segmentsRemaining);
832 };
833​
834 if (shell === "cmd" || shell === "cmd.exe") {
835 for (let index = start; index < tokens.length; index += 1) {
836 const option = tokens[index]!.toLowerCase();
837 if (option !== "/c" && option !== "/k") continue;
838 const payload = tokens[index + 1];
839 return {
840 matched: true,
841 program: parsePayload(payload),
842 };
843 }
844 return { matched: false, program: null };
845 }
846​
847 for (let index = start; index < tokens.length; index += 1) {
848 const option = tokens[index]!.toLowerCase();
849 if (option === "-command" || option === "-c") {
850 const payload = tokens[index + 1];
851 return {
852 matched: true,
853 program: parsePayload(payload),
854 };
855 }
856 if (option === "-file" || option === "-f") {
857 return { matched: true, program: staticProgramName(tokens[index + 1] ?? "") };
858 }
859 if (option === "-encodedcommand" || option === "-enc" || option === "-e") {
860 return { matched: true, program: null };
861 }
862 if (POWERSHELL_OPTIONS_WITH_VALUE.has(option)) {
863 index += 1;
864 continue;
865 }
866 if (POWERSHELL_FLAGS.has(option)) continue;
867 if (!option.startsWith("-")) {
868 return { matched: true, program: staticProgramName(tokens[index]!) };
869 }
870 }
871 return { matched: false, program: null };
873​
874function startProcessProgramName(tokens: ReadonlyArray<string>, start: number): string | null {
875 for (let index = start; index < tokens.length; index += 1) {
876 const token = tokens[index]!;
877 const option = token.toLowerCase();
878 if (option === "-filepath") return staticProgramName(tokens[index + 1] ?? "");
879 if (START_PROCESS_FLAGS.has(option)) continue;
880 if (START_PROCESS_OPTIONS_WITH_VALUE.has(option)) {
881 if (tokens[index + 1] === undefined) return null;
882 index += 1;
883 continue;
884 }
885 if (token.startsWith("-")) return null;
886 return staticProgramName(token);
887 }
888 return null;
890​
891function literalAssignmentProgram(
892 token: string,
893): { readonly name: string; readonly program: string | null } | null {
894 const assignment = token.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/su);
895 if (!assignment) return null;
896 const name = assignment[1]!;
897 let value = assignment[2]!.trim();
898 if (!value || /[$`]/u.test(value)) return { name, program: null };
899​
900 if (value.startsWith("(") && value.endsWith(")")) {
901 const arrayTokens = tokenizeShellCommand(value.slice(1, -1));
902 value = arrayTokens?.[0] ?? "";
903 } else if (/\s/u.test(value) && !/[\\/]/u.test(value)) {
904 return { name, program: null };
905 }
906​
907 return { name, program: staticProgramName(value) };
909​
910function referencedCommandAlias(token: string): string | null {
911 const reference = token.match(
912 /^\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)(?:\[@\])?\})$/u,
913 );
914 return reference?.[1] ?? reference?.[2] ?? null;
916​
917function literalCommandAliasProgramName(command: string): string | null {
918 const aliases = new Map<string, string>();
919 let remainingCommand: string | null = command;
920 let controlFlowDepth = 0;
921​
922 for (let segmentCount = 0; remainingCommand && segmentCount < 64; segmentCount += 1) {
923 const commandWithoutComments = commandWithoutLeadingShellComments(remainingCommand);
924 if (commandWithoutComments === null) return null;
925 const commandSplit = splitFirstShellCommand(commandWithoutComments);
926 const tokens = tokenizeShellCommand(withoutShellLineContinuations(commandSplit.firstCommand));
927 if (tokens === null) return null;
928​
929 let commandIndex = tokens[0] === "do" || tokens[0] === "then" ? 1 : 0;
930 while (commandIndex < tokens.length) {
931 const indexAfterRedirection = indexAfterShellRedirection(tokens, commandIndex);
932 if (indexAfterRedirection !== null && indexAfterRedirection <= tokens.length) {
933 commandIndex = indexAfterRedirection;
934 continue;
935 }
936 if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(tokens[commandIndex] ?? "")) {
937 commandIndex += 1;
938 continue;
939 }
940 break;
941 }
942​
943 const aliasName = referencedCommandAlias(tokens[commandIndex] ?? "");
944 const aliasedProgram = aliasName ? aliases.get(aliasName) : undefined;
945 if (aliasedProgram) return aliasedProgram;
946​
947 const leadingToken = tokens[0];
948 if (leadingToken === "fi" || leadingToken === "done" || leadingToken === "esac") {
949 controlFlowDepth = Math.max(0, controlFlowDepth - 1);
950 }
951 if (
952 leadingToken === "if" ||
953 leadingToken === "for" ||
954 leadingToken === "while" ||
955 leadingToken === "until" ||
956 leadingToken === "select" ||
957 leadingToken === "case"
958 ) {
959 controlFlowDepth += 1;
960 }
961​
962 if (controlFlowDepth === 0 && leadingToken === "unset") {
963 for (const name of tokens.slice(1)) aliases.delete(name);
964 }
965​
966 const assignmentStart = tokens[0] === "export" ? 1 : 0;
967 const assignments = tokens.slice(assignmentStart).map(literalAssignmentProgram);
968 if (
969 controlFlowDepth === 0 &&
970 assignments.length > 0 &&
971 assignments.every((assignment) => assignment !== null)
972 ) {
973 for (const assignment of assignments) {
974 if (assignment.program) aliases.set(assignment.name, assignment.program);
975 else aliases.delete(assignment.name);
976 }
977 }
978​
979 remainingCommand = commandSplit.remainingCommand;
980 }
981​
982 return null;
984​
985function wrappedShellCommandProgramName(
986 wrapper: string,
987 tokens: ReadonlyArray<string>,
988 start: number,
989 depth: number,
990 remainingCommand: string | null,
991 segmentsRemaining: number,
992): string | null {
993 let index = start;
994​
995 if (wrapper === "command") {
996 while (index < tokens.length) {
997 const option = tokens[index]!;
998 if (option === "--") {
999 index += 1;
1000 break;
1002 if (!option.startsWith("-") || option === "-") break;
1003 if (option !== "-p") return null;
1004 index += 1;
1006 } else if (wrapper === "builtin") {
1007 if (tokens[index] === "--") index += 1;
1008 else if (tokens[index]?.startsWith("-")) return null;
1009 } else if (wrapper === "exec") {
1010 while (index < tokens.length) {
1011 const option = tokens[index]!;
1012 if (option === "--") {
1013 index += 1;
1014 break;
1016 if (option === "-a") {
1017 if (tokens[index + 1] === undefined) return null;
1018 index += 2;
1019 continue;
1021 if (/^-a.+/u.test(option) || /^-[cl]+$/u.test(option)) {
1022 index += 1;
1023 continue;
1025 if (option.startsWith("-") && option !== "-") return null;
1026 break;
1029​
1030 const wrappedTokens = tokens.slice(index);
1031 if (wrappedTokens.length === 0) return null;
1032 let targetIndex = 0;
1033 while (targetIndex < wrappedTokens.length) {
1034 const indexAfterRedirection = indexAfterShellRedirection(wrappedTokens, targetIndex);
1035 if (indexAfterRedirection === null || indexAfterRedirection > wrappedTokens.length) break;
1036 targetIndex = indexAfterRedirection;
1038 const target = wrappedTokens[targetIndex];
1039 if (target && /^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(target)) return null;
1040​
1041 const wrappedProgram = commandProgramNameInternal(
1042 serializeShellTokens(wrappedTokens),
1043 depth + 1,
1044 wrapper === "exec" ? "exec" : "shell",
1045 segmentsRemaining,
1046 );
1047 if (wrappedProgram !== null) return wrappedProgram;
1048​
1049 if (
1050 wrapper !== "exec" &&
1051 target &&
1052 target === target.toLowerCase() &&
1053 NON_DESCRIPTIVE_SHELL_PROGRAMS.has(target) &&
1054 !TERMINAL_SHELL_PROGRAMS.has(target) &&
1055 remainingCommand
1056 ) {
1057 return commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1);
1059 return null;
1061​
1062function parseCommandProgramName(
1063 command: string,
1064 depth: number,
1065 context: CommandProgramContext,
1066 segmentsRemaining: number,
1067): string | null {
1068 if (depth >= 8 || segmentsRemaining <= 0) return null;
1069 const commandWithoutComments = commandWithoutLeadingShellComments(command);
1070 if (commandWithoutComments === null) return null;
1071 if (
1072 /^(?:catch|finally|for|foreach|function|if|param|switch|try|while)\s*[{(]/iu.test(
1073 commandWithoutComments,
1075 ) {
1076 return null;
1078 if (/^[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/u.test(commandWithoutComments)) return null;
1079 // `&&` and `||` inside a `[[ ... ]]` expression are not top-level command
1080 // separators. Keep the label conservative instead of scanning the test body.
1081 if (commandWithoutComments.startsWith("[[")) return null;
1082 const commandSplit = splitFirstShellCommand(commandWithoutComments);
1083 if (/^@["'](?:\r?\n)/u.test(commandSplit.firstCommand.trimStart())) {
1084 return commandSplit.remainingCommand
1085 ? commandProgramNameInternal(
1086 commandSplit.remainingCommand,
1087 depth,
1088 "shell",
1089 segmentsRemaining - 1,
1091 : null;
1093 const powerShellAssignment = powerShellAssignmentProgramName(
1094 commandSplit.firstCommand,
1095 depth,
1096 commandSplit.remainingCommand,
1097 segmentsRemaining,
1098 );
1099 if (powerShellAssignment.matched) return powerShellAssignment.program;
1100 const windowsPath = commandSplit.firstCommand.match(
1101 /^\s*((?:\.{1,2}|%[A-Za-z_][A-Za-z0-9_]*%|\$env:[A-Za-z_][A-Za-z0-9_]*)\\\S+)/iu,
1102 )?.[1];
1103 if (windowsPath) return staticProgramName(windowsPath);
1104 const tokens = tokenizeShellCommand(withoutShellLineContinuations(commandSplit.firstCommand));
1105 if (tokens === null) return null;
1106 const firstCharacter = commandSplit.firstCommand.trimStart()[0];
1107 if (
1108 tokens.length === 1 &&
1109 (firstCharacter === '"' || firstCharacter === "'") &&
1110 /[\s()=]/u.test(tokens[0] ?? "") &&
1111 !/[\\/]/u.test(tokens[0] ?? "")
1112 ) {
1113 return commandSplit.remainingCommand
1114 ? commandProgramNameInternal(
1115 commandSplit.remainingCommand,
1116 depth,
1117 context,
1118 segmentsRemaining - 1,
1120 : null;
1122 let index = 0;
1123 let wrapper: CommandWrapper | null = null;
1124 let executionContext = context;
1125 let sawAssignment = false;
1126 let sawRedirection = false;
1127​
1128 while (index < tokens.length) {
1129 const token = tokens[index];
1130 if (!token) return null;
1131 const indexAfterRedirection = indexAfterShellRedirection(tokens, index);
1132 if (indexAfterRedirection !== null) {
1133 if (indexAfterRedirection > tokens.length) return null;
1134 sawRedirection = true;
1135 index = indexAfterRedirection;
1136 continue;
1138 if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(token)) {
1139 sawAssignment = true;
1140 index += 1;
1141 continue;
1143 if (executionContext === "shell" && token === ":") {
1144 return commandSplit.remainingCommand
1145 ? commandProgramNameInternal(
1146 commandSplit.remainingCommand,
1147 depth,
1148 executionContext,
1149 segmentsRemaining - 1,
1151 : null;
1153 if (
1154 NON_PROGRAM_PREFIX_CHARACTERS.includes(token[0] ?? "") &&
1155 !(token.startsWith("$") && token.includes("/"))
1156 ) {
1157 return executionContext === "shell" && token.startsWith("[") && commandSplit.remainingCommand
1158 ? commandProgramNameInternal(
1159 commandSplit.remainingCommand,
1160 depth,
1161 executionContext,
1162 segmentsRemaining - 1,
1164 : null;
1166 const tokenProgram = token.split(/[\\/]/).at(-1);
1167 const isUnqualifiedToken = token === tokenProgram;
1168 if (tokenProgram === "env" || tokenProgram === "sudo") {
1169 wrapper = tokenProgram;
1170 executionContext = "exec";
1171 index += 1;
1172 continue;
1174 if (wrapper !== null && token === "--") {
1175 wrapper = null;
1176 index += 1;
1177 continue;
1179 if (wrapper !== null && token.startsWith("-")) {
1180 if (wrapper === "env" && (token === "-S" || token === "--split-string")) {
1181 const splitCommand = tokens[index + 1];
1182 return splitCommand
1183 ? commandProgramNameInternal(splitCommand, depth + 1, executionContext, segmentsRemaining)
1184 : null;
1186 if (wrapper === "env" && token.startsWith("--split-string=")) {
1187 return commandProgramNameInternal(
1188 token.slice("--split-string=".length),
1189 depth + 1,
1190 executionContext,
1191 segmentsRemaining,
1192 );
1194 if (COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(token)) {
1195 if (tokens[index + 1] === undefined) return null;
1196 index += 2;
1197 continue;
1199 if (COMMAND_WRAPPER_FLAGS[wrapper].has(token)) {
1200 index += 1;
1201 continue;
1203 const equalsIndex = token.indexOf("=");
1204 if (token.startsWith("--") && equalsIndex > 2) {
1205 if (!COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(token.slice(0, equalsIndex))) {
1206 return null;
1208 index += 1;
1209 continue;
1211 if (/^-[A-Za-z].+/.test(token) && !token.startsWith("--")) {
1212 let consumesNextToken = false;
1213 for (const [optionIndex, option] of token.slice(1).split("").entries()) {
1214 const shortOption = `-${option}`;
1215 if (COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(shortOption)) {
1216 consumesNextToken = optionIndex === token.length - 2;
1217 break;
1219 if (!COMMAND_WRAPPER_FLAGS[wrapper].has(shortOption)) return null;
1221 if (consumesNextToken && tokens[index + 1] === undefined) return null;
1222 index += consumesNextToken ? 2 : 1;
1223 continue;
1225 return null;
1227 if (tokenProgram && SHELL_PROGRAMS.has(tokenProgram.replace(/\.exe$/i, "").toLowerCase())) {
1228 const scriptIndex = shellCommandArgumentIndex(tokens, index + 1);
1229 if (scriptIndex !== null) {
1230 const script = tokens[scriptIndex];
1231 return script
1232 ? commandProgramNameInternal(script, depth + 1, "shell", segmentsRemaining)
1233 : null;
1236 const lowerTokenProgram = tokenProgram?.toLowerCase();
1237 if (lowerTokenProgram && WINDOWS_SHELL_PROGRAMS.has(lowerTokenProgram)) {
1238 const payload = windowsShellPayloadProgramName(
1239 lowerTokenProgram,
1240 tokens,
1241 index + 1,
1242 depth,
1243 commandSplit.remainingCommand,
1244 commandSplit.separator,
1245 segmentsRemaining,
1246 );
1247 if (payload.matched) return payload.program;
1249 if (lowerTokenProgram === "start-process") {
1250 const startedProgram = startProcessProgramName(tokens, index + 1);
1251 if (startedProgram !== null) return startedProgram;
1253 if (
1254 executionContext === "shell" &&
1255 isUnqualifiedToken &&
1256 tokenProgram &&
1257 SHELL_PRECOMMAND_MODIFIERS.has(tokenProgram)
1258 ) {
1259 index += 1;
1260 if (tokenProgram === "time" && tokens[index] === "-p") index += 1;
1261 if (tokens[index]?.startsWith("-")) return null;
1262 continue;
1264 if (isUnqualifiedToken && tokenProgram) {
1265 const targetIndex = transparentWrapperCommandIndex(tokenProgram, tokens, index);
1266 if (targetIndex !== null) {
1267 const wrappedProgram = commandProgramNameInternal(
1268 serializeShellTokens(tokens.slice(targetIndex)),
1269 depth + 1,
1270 "exec",
1271 segmentsRemaining,
1272 );
1273 if (wrappedProgram !== null) return wrappedProgram;
1276 if (isUnqualifiedToken && tokenProgram && SHELL_COMMAND_WRAPPERS.has(tokenProgram)) {
1277 return wrappedShellCommandProgramName(
1278 tokenProgram,
1279 tokens,
1280 index + 1,
1281 depth,
1282 commandSplit.remainingCommand,
1283 segmentsRemaining,
1284 );
1286 if (
1287 (executionContext === "shell" ||
1288 (wrapper === "sudo" && tokenProgram && SKIPPABLE_SUDO_PROBES.has(tokenProgram))) &&
1289 isUnqualifiedToken &&
1290 tokenProgram &&
1291 NON_DESCRIPTIVE_SHELL_PROGRAMS.has(tokenProgram) &&
1292 (!TERMINAL_SHELL_PROGRAMS.has(tokenProgram) ||
1293 (tokenProgram === "false" && commandSplit.separator !== "&&")) &&
1294 commandSplit.remainingCommand
1295 ) {
1296 return commandProgramNameInternal(
1297 commandSplit.remainingCommand,
1298 depth,
1299 "shell",
1300 segmentsRemaining - 1,
1301 );
1303 if (
1304 executionContext === "shell" &&
1305 isUnqualifiedToken &&
1306 lowerTokenProgram &&
1307 POWERSHELL_SETUP_PROGRAMS.has(lowerTokenProgram) &&
1308 commandSplit.remainingCommand
1309 ) {
1310 return commandProgramNameInternal(
1311 commandSplit.remainingCommand,
1312 depth,
1313 "shell",
1314 segmentsRemaining - 1,
1315 );
1317 if (
1318 !tokenProgram ||
1319 (isUnqualifiedToken && NON_DESCRIPTIVE_SHELL_PROGRAMS.has(tokenProgram)) ||
1320 NON_PROGRAM_PREFIX_CHARACTERS.includes(tokenProgram[0] ?? "") ||
1321 NON_PROGRAM_SUFFIX_CHARACTERS.includes(tokenProgram.at(-1) ?? "") ||
1322 tokenProgram.endsWith("()") ||
1323 /^[A-Za-z_][A-Za-z0-9_]*\(\)\{$/u.test(tokenProgram)
1324 ) {
1325 return null;
1327 return tokenProgram || null;
1329​
1330 if ((sawAssignment || sawRedirection) && wrapper === null && commandSplit.remainingCommand) {
1331 return commandProgramNameInternal(
1332 commandSplit.remainingCommand,
1333 depth,
1334 executionContext,
1335 segmentsRemaining - 1,
1336 );
1338 return null;
1340​
1341function commandProgramNameInternal(
1342 command: string,
1343 depth: number,
1344 context: CommandProgramContext,
1345 segmentsRemaining = MAX_COMMAND_SEGMENTS,
1346): string | null {
1347 if (segmentsRemaining <= 0) return null;
1348 const calledProgram = powerShellCallOperatorProgramName(command);
1349 if (calledProgram !== undefined) return calledProgram;
1350 return (
1351 parseCommandProgramName(command, depth, context, segmentsRemaining) ??
1352 (context === "shell" ? literalCommandAliasProgramName(command) : null)
1353 );
1355​
1356export function commandProgramName(command: string, depth = 0): string | null {
1357 return commandProgramNameInternal(command, depth, "shell", MAX_COMMAND_SEGMENTS);
1359​
1360// Escape bytes and other control characters render as invisible gaps; display
1361// shows them as Unicode control pictures (ESC becomes ␛) instead. Tab, newline
1362// and carriage return lay out as whitespace, so CRLF scripts stay unmarked.
1363const CONTROL_CHARACTERS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu;
1364​
1365export function commandDisplayText(command: string): string {
1366 return withVisibleControlCharacters(withoutShellWrapper(command));
1368​
1369export function withVisibleControlCharacters(text: string): string {
1370 return text.replace(CONTROL_CHARACTERS, (character) =>
1371 character === "\u007f" ? "␡" : String.fromCharCode(0x2400 + character.charCodeAt(0)),
1372 );
1374​
1375// A wrapper whose quoting does not balance is kept: the script's end cannot be
1376// known, which happens when Codex's secret redaction removes the backslash of
1377// an escaped quote inside `-lc "…"`.
1378function withoutShellWrapper(command: string): string {
1379 const trimmed = command.trim();
1380 const split = splitFirstShellCommand(trimmed);
1381 if (split.remainingCommand !== null) return trimmed;
1382 const tokens = tokenizeShellCommand(trimmed);
1383 const executable = tokens?.[0]?.split(/[\\/]/u).at(-1);
1384 const program = executable?.replace(/\.exe$/iu, "");
1385 if (!tokens || !executable || !program) return trimmed;
1386 const scriptIndex = SHELL_PROGRAMS.has(program)
1387 ? shellCommandArgumentIndex(tokens, 1)
1388 : WINDOWS_SHELL_PROGRAMS.has(executable.toLowerCase())
1389 ? windowsShellScriptIndex(program.toLowerCase(), tokens)
1390 : null;
1391 // Positional arguments can affect the script; keep those invocations intact.
1392 if (scriptIndex === null || scriptIndex !== tokens.length - 1) return trimmed;
1393 return tokens[scriptIndex]?.trim() || trimmed;
1395​
1396function windowsShellScriptIndex(shell: string, tokens: ReadonlyArray<string>): number | null {
1397 for (let index = 1; index < tokens.length; index += 1) {
1398 const option = tokens[index]!.toLowerCase();
1399 if (shell === "cmd") {
1400 if (option === "/c") return index + 1;
1401 if (!option.startsWith("/")) return null;
1402 continue;
1404 if (option === "-command" || option === "-c") return index + 1;
1405 if (POWERSHELL_OPTIONS_WITH_VALUE.has(option)) {
1406 index += 1;
1407 continue;
1409 if (!POWERSHELL_FLAGS.has(option)) return null;
1411 return null;
1413​
1414const POWERSHELL_PROGRAMS = new Set(["powershell", "pwsh"]);
1415​
1416const POWERSHELL_VERBS = new Set(
1417 `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(
1418 " ",
1419 ),
1421​
1422function isPowerShellCmdlet(word: string): boolean {
1423 const cmdlet = /^([A-Z][a-z]+(?:[A-Z][a-z]+)?)-[A-Z][A-Za-z]*$/u.exec(word);
1424 return cmdlet !== null && POWERSHELL_VERBS.has(cmdlet[1]!);
1426​
1427export function commandHighlightLanguage(command: string): "powershell" | "shellscript" {
1428 const program = /^(?:&\s*)?(?:"([^"]*)"|'([^']*)'|(\S+))/u.exec(command.trim());
1429 const name = (program?.[1] ?? program?.[2] ?? program?.[3] ?? "")
1430 .split(/[\\/]/u)
1431 .at(-1)
1432 ?.toLowerCase()
1433 .replace(/\.exe$/u, "");
1434 if (name && POWERSHELL_PROGRAMS.has(name)) return "powershell";
1435 return isPowerShellScript(command) ? "powershell" : "shellscript";
1437​
1438function isPowerShellScript(command: string): boolean {
1439 let rest: string | null = command.trim();
1440 if (/^&\s*\S/u.test(rest)) return true;
1441 for (let segment = 0; rest && segment < MAX_COMMAND_SEGMENTS; segment += 1) {
1442 const { firstCommand, remainingCommand } = splitFirstShellCommand(rest);
1443 const statement = firstCommand.trim();
1444 if (
1445 /^\$(?:env|global|local|script):/iu.test(statement) ||
1446 /^\$[A-Za-z_]\w*\s+=/u.test(statement) ||
1447 isPowerShellCmdlet(statement.match(/^\S+/u)?.[0] ?? "")
1448 ) {
1449 return true;
1451 rest = remainingCommand;
1453 return false;