@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 216 lines 7.55 KB
Raw
1 export function isWindowsDrivePath(value: string): boolean {
2 return /^[a-zA-Z]:([/\\]|$)/.test(value);
3 }
4
5 export function isUncPath(value: string): boolean {
6 return value.startsWith("\\\\");
7 }
8
9 /**
10 * Windows treats `/` and `\` alike, so any two leading separators name a UNC
11 * or device path. Touching one makes Windows sign in to that host with the
12 * user's NTLM credentials, so agent-authored paths must not reach one.
13 */
14 export function isNetworkPath(value: string): boolean {
15 return /^[\\/]{2}/.test(value);
16 }
17
18 /** A `\\wsl.localhost\<distro>` or `\\wsl$\<distro>` share: a WSL distro's files seen from Windows over 9P. */
19 export function isWslSharePath(value: string): boolean {
20 return /^[\\/]{2}(?:[?.][\\/]UNC[\\/])?wsl(?:\.localhost|\$)[\\/]/i.test(value.trim());
21 }
22
23 export function isWindowsAbsolutePath(value: string): boolean {
24 return isUncPath(value) || isWindowsDrivePath(value);
25 }
26
27 export function isExplicitRelativePath(value: string): boolean {
28 return (
29 value === "." ||
30 value === ".." ||
31 value.startsWith("./") ||
32 value.startsWith("../") ||
33 value.startsWith(".\\") ||
34 value.startsWith("..\\")
35 );
36 }
37
38 function isRootPath(value: string): boolean {
39 // Bare C: means the current directory on C, not its root; require the drive separator.
40 return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]$/.test(value);
41 }
42
43 function trimTrailingPathSeparators(value: string): string {
44 if (value.length === 0 || isRootPath(value)) {
45 return value;
46 }
47 const trimmed = value.startsWith("/")
48 ? value.replace(/\/+$/g, "")
49 : value.replace(/[\\/]+$/g, "");
50 if (trimmed.length === 0) {
51 return value;
52 }
53 return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
54 }
55
56 export function normalizeProjectPathForDispatch(value: string): string {
57 return trimTrailingPathSeparators(value.trim());
58 }
59
60 export function normalizeProjectPathForComparison(value: string): string {
61 const normalized = normalizeProjectPathForDispatch(value);
62 if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {
63 return normalized.replaceAll("/", "\\").toLowerCase();
64 }
65 return normalized;
66 }
67
68 // Windows refuses these as file names, with or without an extension.
69 const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
70
71 // Latin letters NFKD leaves whole (ł, ø, ß) or splits with a spacing mark (Ŀ, ʼn).
72 const LATIN_FOLDS: Record<string, string> = {
73 Ŀ: "L",
74 ŀ: "l",
75 ʼn: "n",
76 Đ: "D",
77 đ: "d",
78 Ð: "D",
79 ð: "d",
80 ß: "ss",
81 ẞ: "SS",
82 Ł: "L",
83 ł: "l",
84 Ø: "O",
85 ø: "o",
86 Æ: "AE",
87 æ: "ae",
88 Œ: "OE",
89 œ: "oe",
90 Þ: "TH",
91 þ: "th",
92 Ħ: "H",
93 ħ: "h",
94 ı: "i",
95 ĸ: "q",
96 Ŋ: "N",
97 ŋ: "n",
98 Ŧ: "T",
99 ŧ: "t",
100 };
101 const LATIN_FOLD_PATTERN = new RegExp(`[${Object.keys(LATIN_FOLDS).join("")}]`, "g");
102
103 /** Folds accented Latin letters to ASCII ("tìm" -> "tim"); other scripts pass through. */
104 export function foldLatinDiacritics(text: string): string {
105 return text
106 .replace(LATIN_FOLD_PATTERN, (letter) => LATIN_FOLDS[letter] ?? letter)
107 .normalize("NFKD")
108 .replace(/[\u0300-\u036f]/g, "");
109 }
110
111 export function newProjectFolderName(name: string): string {
112 const slug = foldLatinDiacritics(name)
113 .toLowerCase()
114 .replace(/[^a-z0-9]+/g, "-")
115 .replace(/^-+/, "")
116 .slice(0, 64)
117 .replace(/-+$/, "");
118 if (slug.length === 0) return "project";
119 return WINDOWS_RESERVED_NAME.test(slug) ? `${slug}-project` : slug;
120 }
121
122 const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
123
124 /** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
125 export function stripSlashPrefixedWindowsDrive(path: string): string {
126 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
127 }
128
129 export function fileBasename(path: string): string {
130 const trimmed = path.replace(/[/\\]+$/, "");
131 if (trimmed.length === 0) return path;
132 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
133 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
134 }
135
136 export function workspaceRelativeFilePath(
137 path: string,
138 workspaceRoot: string | null | undefined,
139 ): string | null {
140 if (!workspaceRoot) return null;
141 const caseInsensitive =
142 isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) ||
143 (isNetworkPath(workspaceRoot) && isUncPath(path));
144 const normalizedPath = caseInsensitive
145 ? stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"))
146 : path;
147 const normalizedRoot = (
148 caseInsensitive
149 ? stripSlashPrefixedWindowsDrive(workspaceRoot.replaceAll("\\", "/"))
150 : workspaceRoot
151 ).replace(/\/+$/, "");
152 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
153 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
154 if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";
155 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
156 const relativePath = normalizedPath.slice(normalizedRoot.length + 1);
157 // `/repo/../x` starts with the root but escapes it; the server rejects that as a workspace path.
158 let depth = 0;
159 for (const segment of relativePath.split("/")) {
160 if (segment === "..") depth -= 1;
161 else if (segment.length > 0 && segment !== ".") depth += 1;
162 if (depth < 0) return null;
163 }
164 return relativePath;
165 }
166
167 export function isAbsolutePath(value: string): boolean {
168 return value.startsWith("/") || isWindowsAbsolutePath(value);
169 }
170
171 /** Both ~/ and ~\ home prefixes are expanded by the destination server. */
172 export function isHostPath(value: string): boolean {
173 return isAbsolutePath(value) || value.startsWith("~/") || value.startsWith("~\\");
174 }
175
176 // Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`.
177 const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/;
178 const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g;
179
180 // Folder browsers only navigate `~/` home paths, so a pasted `~\` path is not a replacement.
181 function isPastedFolderPath(value: string): boolean {
182 return isAbsolutePath(value) || value.startsWith("~/");
183 }
184
185 /**
186 * What a folder box holds after a change. A full path pasted into it replaces the box, even after
187 * the text already there, because `~/'/a b'` would create that nested folder.
188 */
189 export function resolvePastedPath(previous: string, next: string): string {
190 const isTyping = next.startsWith(previous)
191 ? next.length === previous.length + 1
192 : previous.startsWith(next);
193 if (isTyping) return next;
194
195 const match = QUOTED_PATH_AT_END.exec(next);
196 // Text before the quote that wasn't in the box is a search, not a folder to paste after.
197 if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) {
198 const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? "";
199 if (isPastedFolderPath(quoted)) return quoted;
200 }
201
202 // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder.
203 const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous);
204 const path = afterFolder ? next.slice(previous.length) : next;
205 if (!isPastedFolderPath(path)) return next;
206 // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths.
207 return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1");
208 }
209
210 export function resolveWorkspaceFilePath(path: string, workspaceRoot: string): string {
211 if (isAbsolutePath(path) || path.startsWith("~/") || path.startsWith("~\\")) return path;
212 const base = workspaceRoot.replace(/[/\\]+$/, "");
213 return isWindowsAbsolutePath(workspaceRoot)
214 ? `${base}\\${path.replaceAll("/", "\\")}`
215 : `${base}/${path}`;
216 }