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

path.ts

211 lines7.3 KB

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