The best way to control Claude Code, Codex and more from any computer or phone

main
ts 115 lines 2.88 KB
Raw
1 export interface ParsedCliArgs {
2 readonly flags: Record<string, string | null>;
3 readonly positionals: string[];
4 }
5
6 export interface ParseCliArgsOptions {
7 readonly booleanFlags?: readonly string[];
8 /** Flags that always take the next token as their value, even one starting with `--`. */
9 readonly valueFlags?: readonly string[];
10 }
11
12 export function tokenizeCliArgs(args?: string): ReadonlyArray<string> {
13 const input = args;
14 if (!input) return [];
15
16 const tokens: string[] = [];
17 let current = "";
18 let quote: "'" | '"' | undefined;
19 let quoted = false;
20
21 for (let index = 0; index < input.length; index++) {
22 const char = input[index];
23 if (char === undefined) continue;
24
25 if (quote) {
26 if (char === quote) {
27 quote = undefined;
28 quoted = true;
29 } else if (char === "\\" && quote === '"') {
30 const next = input[index + 1];
31 if (next !== undefined && ['"', "\\", "$", "`"].includes(next)) {
32 current += next;
33 index++;
34 } else {
35 current += char;
36 }
37 } else {
38 current += char;
39 }
40 continue;
41 }
42
43 if (char === "'" || char === '"') {
44 quote = char;
45 quoted = true;
46 } else if (/[ \t\n\r\f\v]/.test(char)) {
47 if (current || quoted) {
48 tokens.push(current);
49 current = "";
50 quoted = false;
51 }
52 } else if (char === "\\") {
53 const next = input[index + 1];
54 if (next !== undefined && /[\s'"]/.test(next)) {
55 current += next;
56 index++;
57 } else {
58 current += char;
59 }
60 } else {
61 current += char;
62 }
63 }
64
65 if (current || quoted) tokens.push(current);
66 return tokens;
67 }
68
69 export function parseCliArgs(
70 args: string | readonly string[],
71 options?: ParseCliArgsOptions,
72 ): ParsedCliArgs {
73 const tokens = typeof args === "string" ? tokenizeCliArgs(args) : Array.from(args);
74 const booleanSet = options?.booleanFlags ? new Set(options.booleanFlags) : undefined;
75 const valueSet = options?.valueFlags ? new Set(options.valueFlags) : undefined;
76
77 const flags: Record<string, string | null> = {};
78 const positionals: string[] = [];
79
80 for (let i = 0; i < tokens.length; i++) {
81 const token = tokens[i]!;
82
83 if (token === "--") {
84 positionals.push(...tokens.slice(i + 1));
85 break;
86 }
87
88 if (token.startsWith("--")) {
89 const rest = token.slice(2);
90
91 const eqIndex = rest.indexOf("=");
92 if (eqIndex !== -1) {
93 flags[rest.slice(0, eqIndex)] = rest.slice(eqIndex + 1);
94 continue;
95 }
96
97 if (booleanSet?.has(rest)) {
98 flags[rest] = null;
99 continue;
100 }
101
102 const next = tokens[i + 1];
103 if (next !== undefined && (valueSet?.has(rest) || !next.startsWith("--"))) {
104 flags[rest] = next;
105 i++;
106 } else {
107 flags[rest] = null;
108 }
109 } else {
110 positionals.push(token);
111 }
112 }
113
114 return { flags, positionals };
115 }