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

main
ts 250 lines 8.49 KB
Raw
1 interface OrderableDiffFile {
2 readonly additionLines: ReadonlyArray<string>;
3 readonly deletionLines: ReadonlyArray<string>;
4 }
5
6 type DiffFileTier = "source" | "test" | "generated";
7
8 const GENERATED_FILE_NAMES = new Set([
9 "pnpm-lock.yaml",
10 "yarn.lock",
11 "package-lock.json",
12 "bun.lockb",
13 "Cargo.lock",
14 "go.sum",
15 "composer.lock",
16 "Gemfile.lock",
17 ]);
18 const GENERATED_DIRECTORIES = new Set([
19 "__snapshots__",
20 "__generated__",
21 "dist",
22 "build",
23 "vendor",
24 ]);
25 const TEST_DIRECTORIES = new Set(["__tests__", "tests", "test"]);
26 // `.mts` also ends in `.ts`, so longer extensions come first.
27 const MODULE_EXTENSIONS = [".mts", ".cts", ".mjs", ".cjs", ".tsx", ".jsx", ".ts", ".js"];
28
29 function diffFileTier(path: string): DiffFileTier {
30 const segments = path.split("/");
31 const name = segments.at(-1) ?? "";
32 if (
33 GENERATED_FILE_NAMES.has(name) ||
34 name.endsWith(".snap") ||
35 name.endsWith(".min.js") ||
36 name.endsWith(".min.css") ||
37 /\.generated\./.test(name) ||
38 segments.slice(0, -1).some((segment) => GENERATED_DIRECTORIES.has(segment))
39 ) {
40 return "generated";
41 }
42 if (
43 /\.(?:test|spec)\./.test(name) ||
44 segments.slice(0, -1).some((segment) => TEST_DIRECTORIES.has(segment))
45 ) {
46 return "test";
47 }
48 return "source";
49 }
50
51 function stripExtension(path: string): string {
52 const dot = path.lastIndexOf(".");
53 const slash = path.lastIndexOf("/");
54 return dot > slash ? path.slice(0, dot) : path;
55 }
56
57 function baseName(path: string): string {
58 return stripExtension(path.split("/").at(-1) ?? "");
59 }
60
61 // Import specifiers omit module extensions but keep dotted names such as `b.logic`, so module-map
62 // keys strip only the extensions an import could omit.
63 function stripModuleExtension(path: string): string {
64 const extension = MODULE_EXTENSIONS.find((candidate) => path.endsWith(candidate));
65 return extension === undefined ? path : path.slice(0, -extension.length);
66 }
67
68 function moduleName(path: string): string {
69 return stripModuleExtension(path.split("/").at(-1) ?? "");
70 }
71
72 function resolveRelative(fromPath: string, specifier: string): string {
73 const segments = fromPath.split("/").slice(0, -1);
74 for (const part of specifier.split("/")) {
75 if (part === "." || part === "") continue;
76 if (part === "..") segments.pop();
77 else segments.push(part);
78 }
79 return segments.join("/");
80 }
81
82 const IMPORT_SPECIFIER = /(?:\bfrom|\bimport|\brequire\s*\()\s*\(?\s*["']([^"']+)["']/g;
83
84 function importedPaths(
85 path: string,
86 lines: ReadonlyArray<string>,
87 byModulePath: ReadonlyMap<string, string>,
88 byModuleName: ReadonlyMap<string, string>,
89 ): ReadonlySet<string> {
90 const imported = new Set<string>();
91 for (const line of lines) {
92 IMPORT_SPECIFIER.lastIndex = 0;
93 let match = IMPORT_SPECIFIER.exec(line);
94 while (match !== null) {
95 // Bundler queries such as `?worker` or `?url` name the same file.
96 const specifier = (match[1] ?? "").replace(/\?.*$/, "");
97 const resolved = stripModuleExtension(
98 specifier.startsWith(".") ? resolveRelative(path, specifier) : specifier,
99 );
100 const target =
101 byModulePath.get(resolved) ??
102 byModulePath.get(`${resolved}/index`) ??
103 byModuleName.get(moduleName(resolved));
104 if (target !== undefined && target !== path) imported.add(target);
105 match = IMPORT_SPECIFIER.exec(line);
106 }
107 }
108 return imported;
109 }
110
111 function orderByImports(
112 paths: ReadonlyArray<string>,
113 imports: ReadonlyMap<string, ReadonlySet<string>>,
114 ): Array<string> {
115 const remaining = new Set(paths);
116 const ordered: Array<string> = [];
117 const sorted = [...paths].sort((left, right) => left.localeCompare(right));
118 while (remaining.size > 0) {
119 const candidates = sorted.filter((path) => remaining.has(path));
120 const next =
121 candidates.find((path) =>
122 [...(imports.get(path) ?? [])].every((dependency) => !remaining.has(dependency)),
123 ) ?? candidates[0]!;
124 remaining.delete(next);
125 ordered.push(next);
126 }
127 return ordered;
128 }
129
130 // `a.logic.test.ts` covers `a.logic.ts` while `a.browser.test.ts` covers `a.ts`, so the longest
131 // dotted prefix that names a source file wins.
132 function testedSourcePosition(path: string, sourcePositions: ReadonlyMap<string, number>): number {
133 let name = (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "");
134 while (true) {
135 const position = sourcePositions.get(name);
136 if (position !== undefined) return position;
137 const dot = name.lastIndexOf(".");
138 if (dot <= 0) return Number.MAX_SAFE_INTEGER;
139 name = name.slice(0, dot);
140 }
141 }
142
143 function orderByImportsAndTier<F extends OrderableDiffFile>(
144 files: ReadonlyArray<F>,
145 pathOf: (file: F) => string,
146 ): ReadonlyArray<F> {
147 // A type change (file to symlink) is a delete and an add under one path; keep both.
148 const byPath = new Map<string, F[]>();
149 for (const file of files) {
150 const path = pathOf(file);
151 byPath.set(path, [...(byPath.get(path) ?? []), file]);
152 }
153 const tiers = new Map<string, DiffFileTier>();
154 for (const path of byPath.keys()) tiers.set(path, diffFileTier(path));
155
156 const sourcePaths = [...byPath.keys()].filter((path) => tiers.get(path) === "source");
157 const byModulePath = new Map<string, string>();
158 const ambiguousModuleNames = new Set<string>();
159 const byModuleName = new Map<string, string>();
160 for (const path of sourcePaths) {
161 byModulePath.set(stripModuleExtension(path), path);
162 const name = moduleName(path);
163 if (byModuleName.has(name)) ambiguousModuleNames.add(name);
164 byModuleName.set(name, path);
165 }
166 for (const name of ambiguousModuleNames) byModuleName.delete(name);
167
168 const imports = new Map<string, ReadonlySet<string>>();
169 for (const path of sourcePaths) {
170 const lines = byPath
171 .get(path)!
172 .flatMap((file) => [...file.additionLines, ...file.deletionLines]);
173 imports.set(path, importedPaths(path, lines, byModulePath, byModuleName));
174 }
175 const orderedSource = orderByImports(sourcePaths, imports);
176
177 const sourcePositions = new Map<string, number>();
178 orderedSource.forEach((path, index) => {
179 const base = baseName(path);
180 if (!sourcePositions.has(base)) sourcePositions.set(base, index);
181 });
182 const orderedTests = [...byPath.keys()]
183 .filter((path) => tiers.get(path) === "test")
184 .sort((left, right) => {
185 return (
186 testedSourcePosition(left, sourcePositions) -
187 testedSourcePosition(right, sourcePositions) || left.localeCompare(right)
188 );
189 });
190
191 const orderedGenerated = [...byPath.keys()]
192 .filter((path) => tiers.get(path) === "generated")
193 .sort((left, right) => left.localeCompare(right));
194
195 return [...orderedSource, ...orderedTests, ...orderedGenerated].flatMap((path) =>
196 byPath.get(path)!,
197 );
198 }
199
200 /** Where each file, and each directory (with a trailing slash), first appears in `paths`. */
201 export function diffFileTreePositions(paths: ReadonlyArray<string>): ReadonlyMap<string, number> {
202 const positions = new Map<string, number>();
203 paths.forEach((path, index) => {
204 positions.set(path, index);
205 let directory = "";
206 for (const segment of path.split("/").slice(0, -1)) {
207 directory += `${segment}/`;
208 if (!positions.has(directory)) positions.set(directory, index);
209 }
210 });
211 return positions;
212 }
213
214 function orderLikeTree<F>(files: ReadonlyArray<F>, pathOf: (file: F) => string): ReadonlyArray<F> {
215 const paths = files.map(pathOf);
216 const positions = diffFileTreePositions(paths);
217 const keys = paths.map((path) => {
218 const key: number[] = [];
219 let directory = "";
220 for (const segment of path.split("/").slice(0, -1)) {
221 directory += `${segment}/`;
222 key.push(positions.get(directory)!);
223 }
224 key.push(positions.get(path)!);
225 return key;
226 });
227 return files
228 .map((file, index) => ({ file, key: keys[index]! }))
229 .sort((left, right) => {
230 const length = Math.min(left.key.length, right.key.length);
231 for (let index = 0; index < length; index++) {
232 const difference = left.key[index]! - right.key[index]!;
233 if (difference !== 0) return difference;
234 }
235 return left.key.length - right.key.length;
236 })
237 .map(({ file }) => file);
238 }
239
240 /**
241 * Review order shared by every client: dependencies before dependents, tests after their source,
242 * generated files last, then regrouped so each directory stays contiguous and a file tree built
243 * from `diffFileTreePositions` lists files in the same order.
244 */
245 export function orderDiffFilesForReview<F extends OrderableDiffFile>(
246 files: ReadonlyArray<F>,
247 pathOf: (file: F) => string,
248 ): ReadonlyArray<F> {
249 return orderLikeTree(orderByImportsAndTier(files, pathOf), pathOf);
250 }