Open History to see the last commit
1export function isWindowsDrivePath(value: string): boolean {
2 return /^[a-zA-Z]:([/\\]|$)/.test(value);
3}
4
5export 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 */
14export 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. */
19export function isWslSharePath(value: string): boolean {
20 return /^[\\/]{2}(?:[?.][\\/]UNC[\\/])?wsl(?:\.localhost|\$)[\\/]/i.test(value.trim());
21}
22
23export function isWindowsAbsolutePath(value: string): boolean {
24 return isUncPath(value) || isWindowsDrivePath(value);
25}
26
27export 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
38function 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
43function 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
56export function normalizeProjectPathForDispatch(value: string): string {
57 return trimTrailingPathSeparators(value.trim());
58}
59
60export 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
68export function normalizeFileMetadataPath(value: string): string {
69 const trimmed = value.trim();
70 return isWindowsDrivePath(trimmed) || isUncPath(trimmed)
71 ? normalizeProjectPathForComparison(trimmed)
72 : trimTrailingPathSeparators(value);
73}
74
75// Windows refuses these as file names, with or without an extension.
76const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
77
78// Latin letters NFKD leaves whole (ł, ø, ß) or splits with a spacing mark (Ŀ, ʼn).
79const LATIN_FOLDS: Record<string, string> = {
80 Ŀ: "L",
81 ŀ: "l",
82 ʼn: "n",
83 Đ: "D",
84 đ: "d",
85 Ð: "D",
86 ð: "d",
87 ß: "ss",
88 ẞ: "SS",
89 Ł: "L",
90 ł: "l",
91 Ø: "O",
92 ø: "o",
93 Æ: "AE",
94 æ: "ae",
95 Œ: "OE",
96 œ: "oe",
97 Þ: "TH",
98 þ: "th",
99 Ħ: "H",
100 ħ: "h",
101 ı: "i",
102 ĸ: "q",
103 Ŋ: "N",
104 ŋ: "n",
105 Ŧ: "T",
106 ŧ: "t",
107};
108const LATIN_FOLD_PATTERN = new RegExp(`[${Object.keys(LATIN_FOLDS).join("")}]`, "g");
109
110/** Folds accented Latin letters to ASCII ("tìm" -> "tim"); other scripts pass through. */
111export function foldLatinDiacritics(text: string): string {
112 return text
113 .replace(LATIN_FOLD_PATTERN, (letter) => LATIN_FOLDS[letter] ?? letter)
114 .normalize("NFKD")
115 .replace(/[\u0300-\u036f]/g, "");
116}
117
118export function newProjectFolderName(name: string): string {
119 const slug = foldLatinDiacritics(name)
120 .toLowerCase()
121 .replace(/[^a-z0-9]+/g, "-")
122 .replace(/^-+/, "")
123 .slice(0, 64)
124 .replace(/-+$/, "");
125 if (slug.length === 0) return "project";
126 return WINDOWS_RESERVED_NAME.test(slug) ? `${slug}-project` : slug;
127}
128
129const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
130
131/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
132export function stripSlashPrefixedWindowsDrive(path: string): string {
133 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
134}
135
136export function isPosixAbsolutePath(path: string): boolean {
137 return (
138 path.startsWith("/") && !isNetworkPath(path) && !SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path)
139 );
140}
141
142export function fileBasename(path: string): string {
143 const isPosix = isPosixAbsolutePath(path);
144 const trimmed = path.replace(isPosix ? /\/+$/ : /[/\\]+$/, "");
145 if (trimmed.length === 0) return path;
146 const separatorIndex = isPosix
147 ? trimmed.lastIndexOf("/")
148 : Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
149 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
150}
151
152/** A path's last segment composed to NFC for display: macOS stores many names in NFD. */
153export function fileDisplayName(path: string): string {
154 return fileBasename(path).normalize("NFC");
155}
156
157export function workspaceRelativeFilePath(
158 path: string,
159 workspaceRoot: string | null | undefined,
160): string | null {
161 if (!workspaceRoot) return null;
162 const caseInsensitive =
163 isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) ||
164 (isNetworkPath(workspaceRoot) && isUncPath(path));
165 const normalizedPath = caseInsensitive
166 ? stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"))
167 : path;
168 const normalizedRoot = (
169 caseInsensitive
170 ? stripSlashPrefixedWindowsDrive(workspaceRoot.replaceAll("\\", "/"))
171 : workspaceRoot
172 ).replace(/\/+$/, "");
173 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
174 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
175 if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";
176 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
177 const relativePath = normalizedPath.slice(normalizedRoot.length + 1).replace(/^\/+/, "");
178 // `/repo/../x` starts with the root but escapes it; the server rejects that as a workspace path.
179 let depth = 0;
180 for (const segment of relativePath.split("/")) {
181 if (segment === "..") depth -= 1;
182 else if (segment.length > 0 && segment !== ".") depth += 1;
183 if (depth < 0) return null;
184 }
185 return relativePath;
186}
187
188export function isAbsolutePath(value: string): boolean {
189 return value.startsWith("/") || isWindowsAbsolutePath(value);
190}
191
192/** Both ~/ and ~\ home prefixes are expanded by the destination server. */
193export function isHostPath(value: string): boolean {
194 return isAbsolutePath(value) || value.startsWith("~/") || value.startsWith("~\\");
195}
196
197// Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`.
198// Explorer's `"C:\"` ends in a backslash, so Windows paths are matched before shell escapes are.
199const QUOTED_PATH_AT_END =
200 /(?:'((?:[^']|'\\'')+)'|"([a-zA-Z]:[^"]*|\\\\[^"]*)"|"((?:[^"\\]|\\[\s\S])+)")\s*$/;
201const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g;
202// Inside POSIX double quotes a backslash only escapes these; `"\q"` keeps its backslash.
203const DOUBLE_QUOTED_ESCAPE = /\\(["\\$`])/g;
204
205// Folder browsers only navigate `~/` home paths, so a pasted `~\` path is not a replacement.
206function isPastedFolderPath(value: string): boolean {
207 return isAbsolutePath(value) || value.startsWith("~/");
208}
209
210/**
211 * What a folder box holds after a change. A full path pasted into it replaces the box, even after
212 * the text already there, because `~/'/a b'` would create that nested folder.
213 */
214export function resolvePastedPath(previous: string, next: string): string {
215 const isTyping = next.startsWith(previous)
216 ? next.length === previous.length + 1
217 : previous.startsWith(next);
218 if (isTyping) return next;
219
220 const match = QUOTED_PATH_AT_END.exec(next);
221 // Text before the quote that wasn't in the box is a search, not a folder to paste after.
222 if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) {
223 const quoted =
224 match[1]?.replaceAll("'\\''", "'") ??
225 match[2] ??
226 match[3]?.replace(DOUBLE_QUOTED_ESCAPE, "$1") ??
227 "";
228 if (isPastedFolderPath(quoted)) return quoted;
229 }
230
231 // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder.
232 const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous);
233 const path = afterFolder ? next.slice(previous.length) : next;
234 if (!isPastedFolderPath(path)) return next;
235 // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths.
236 return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1");
237}
238
239export function resolveWorkspaceFilePath(path: string, workspaceRoot: string): string {
240 if (isAbsolutePath(path) || path.startsWith("~/") || path.startsWith("~\\")) return path;
241 const isWindows = isWindowsAbsolutePath(workspaceRoot);
242 const base = workspaceRoot.replace(isWindows ? /[/\\]+$/ : /\/+$/, "");
243 return isWindows ? `${base}\\${path.replaceAll("/", "\\")}` : `${base}/${path}`;
244}