/** * Parse a shell-like command line string into tokens, preserving quotes and * backslash escapes. Always appends the trailing token (which may be empty * when the input ends with an unquoted space). */ export function tokenizeShellLike(input: string): string[] { const tokens: string[] = []; let current = ""; let inSingleQuote = false; let inDoubleQuote = false; let escaped = false; for (let i = 0; i < input.length; i++) { const ch = input[i]; if (escaped) { current += ch; escaped = false; continue; } if (ch === "\\") { escaped = true; current += ch; continue; } if (ch === "'" && !inDoubleQuote) { inSingleQuote = !inSingleQuote; current += ch; continue; } if (ch === '"' && !inSingleQuote) { inDoubleQuote = !inDoubleQuote; current += ch; continue; } if (ch === " " && !inSingleQuote && !inDoubleQuote) { if (current.length > 0) { tokens.push(current); current = ""; } continue; } current += ch; } // Always include the last token (even if empty, to indicate trailing space) tokens.push(current); return tokens; }