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

WorkspaceEntries.test.ts

703 lines27.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it, afterEach, describe, expect } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import { vi } from "vite-plus/test";
11​
12import * as ServerConfig from "../config.ts";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import * as VcsProcess from "../vcs/VcsProcess.ts";
15import * as WorkspaceEntries from "./WorkspaceEntries.ts";
16import * as WorkspacePaths from "./WorkspacePaths.ts";
17​
18vi.mock("node:fs/promises", async (importOriginal) => {
19 const actual = await importOriginal<typeof import("node:fs/promises")>();
20 return { ...actual, readdir: vi.fn(actual.readdir) };
21});
22​
23const layerTest = Layer.empty.pipe(
24 Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
25 Layer.provideMerge(WorkspacePaths.layer),
26 Layer.provideMerge(VcsProcess.layer),
27 Layer.provide(
28 ServerConfig.ServerConfig.layerTest(process.cwd(), {
29 prefix: "t3-workspace-entries-test-",
30 }),
31 ),
32 Layer.provideMerge(NodeServices.layer),
33);
34​
35const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
36 const fileSystem = yield* FileSystem.FileSystem;
37 const dir = yield* fileSystem.makeTempDirectoryScoped({
38 prefix: opts?.prefix ?? "t3code-workspace-entries-",
39 });
40 if (opts?.git) {
41 yield* git(dir, ["init"]);
42 }
43 return dir;
44});
45​
46function writeTextFile(
47 cwd: string,
48 relativePath: string,
49 contents = "",
50): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
51 return Effect.gen(function* () {
52 const fileSystem = yield* FileSystem.FileSystem;
53 const path = yield* Path.Path;
54 const absolutePath = path.join(cwd, relativePath);
55 yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
56 yield* fileSystem.writeFileString(absolutePath, contents);
57 });
59​
60const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
61 Effect.gen(function* () {
62 const process = yield* VcsProcess.VcsProcess;
63 const result = yield* process.run({
64 operation: "WorkspaceEntries.test.git",
65 command: "git",
66 cwd,
67 args,
68 ...(env ? { env } : {}),
69 timeoutMs: 10_000,
70 });
71 return result.stdout.trim();
72 });
73​
74const searchWorkspaceEntries = (input: {
75 cwd: string;
76 query: string;
77 limit: number;
78 kind?: "file" | "directory";
79}) =>
80 Effect.gen(function* () {
81 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
82 return yield* workspaceEntries.search(input);
83 });
84​
85const appendSeparator = (input: string) =>
86 Effect.map(HostProcess.Platform, (platform) =>
87 input.endsWith("/") || input.endsWith("\\")
88 ? input
89 : `${input}${platform === "win32" ? "\\" : "/"}`,
90 );
91​
92it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
93 afterEach(() => {
94 vi.restoreAllMocks();
95 });
96​
97 describe("list", () => {
98 it.effect("lists immediate children including ignored and empty directories", () =>
99 Effect.gen(function* () {
100 const cwd = yield* makeTempDir({ git: true });
101 const fileSystem = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 yield* writeTextFile(cwd, "tracked.txt");
104 yield* git(cwd, ["add", "tracked.txt"]);
105 yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env\ntracked.txt\n");
106 yield* writeTextFile(cwd, ".env", "secret=value");
107 yield* writeTextFile(cwd, "node_modules/pkg/index.js");
108 yield* writeTextFile(cwd, "src/index.ts");
109 yield* fileSystem.makeDirectory(path.join(cwd, "empty"));
110​
111 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
112 const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });
113 expect(root.entries).toEqual(
114 expect.arrayContaining([
115 { path: ".env", kind: "file", ignored: true },
116 { path: "node_modules", kind: "directory", ignored: true },
117 { path: "src", kind: "directory" },
118 { path: "empty", kind: "directory" },
119 { path: "tracked.txt", kind: "file" },
120 ]),
121 );
122 expect(root.entries.some((entry) => entry.path.includes("/"))).toBe(false);
123 expect(root.entries.some((entry) => entry.path === ".git")).toBe(false);
124 expect(root.truncated).toBe(false);
125 expect(yield* workspaceEntries.list({ cwd, directoryPath: "node_modules/pkg" })).toEqual({
126 entries: [{ path: "node_modules/pkg/index.js", kind: "file", ignored: true }],
127 truncated: false,
128 });
129 expect(yield* workspaceEntries.list({ cwd, directoryPath: "empty" })).toEqual({
130 entries: [],
131 truncated: false,
132 });
133 }),
134 );
135​
136 it.effect("lists symlinks as what they point to, hiding ones that cannot be opened", () =>
137 Effect.gen(function* () {
138 const platform = yield* HostProcess.Platform;
139 if (platform === "win32") return;
140 const cwd = yield* makeTempDir({ git: true });
141 const outside = yield* makeTempDir();
142 const fileSystem = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 yield* writeTextFile(cwd, "real.txt");
145 yield* writeTextFile(cwd, "realdir/nested.txt");
146 yield* writeTextFile(outside, "outside.txt");
147 yield* fileSystem.symlink("real.txt", path.join(cwd, "link.txt"));
148 yield* fileSystem.symlink("realdir", path.join(cwd, "linkdir"));
149 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
150 yield* fileSystem.symlink(".git", path.join(cwd, "git-link"));
151 yield* fileSystem.symlink("missing", path.join(cwd, "dangling"));
152​
153 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
154 const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });
155 expect(root.entries.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
156 { path: "link.txt", kind: "file" },
157 { path: "linkdir", kind: "directory" },
158 { path: "real.txt", kind: "file" },
159 { path: "realdir", kind: "directory" },
160 ]);
161 expect(yield* workspaceEntries.list({ cwd, directoryPath: "linkdir" })).toEqual({
162 entries: [{ path: "linkdir/nested.txt", kind: "file" }],
163 truncated: false,
164 });
165 }),
166 );
167​
168 it.effect("hides folder links that lead back to a folder on the listed path", () =>
169 // "Expand all folders" loads every folder it expands, so a link that loops would
170 // keep nesting the same entries without end.
171 Effect.gen(function* () {
172 const platform = yield* HostProcess.Platform;
173 if (platform === "win32") return;
174 const cwd = yield* makeTempDir();
175 const fileSystem = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177 yield* writeTextFile(cwd, "a/file.txt");
178 yield* writeTextFile(cwd, "b/file.txt");
179 yield* fileSystem.symlink(".", path.join(cwd, "self"));
180 yield* fileSystem.symlink("..", path.join(cwd, "a/up"));
181 yield* fileSystem.symlink("../b", path.join(cwd, "a/to-b"));
182 yield* fileSystem.symlink("../a", path.join(cwd, "b/to-a"));
183​
184 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
185 const paths = (directoryPath: string) =>
186 workspaceEntries
187 .list({ cwd, directoryPath })
188 .pipe(Effect.map(({ entries }) => entries.map((entry) => entry.path).toSorted()));
189 expect(yield* paths("")).toEqual(["a", "b"]);
190 // A link into a sibling folder is fine on its own...
191 expect(yield* paths("a")).toEqual(["a/file.txt", "a/to-b"]);
192 // ...but once followed, the sibling's link back is hidden.
193 expect(yield* paths("a/to-b")).toEqual(["a/to-b/file.txt"]);
194 }),
195 );
196​
197 it.effect("resolves a folder of many symlinks in bounded batches", () =>
198 Effect.gen(function* () {
199 const platform = yield* HostProcess.Platform;
200 if (platform === "win32") return;
201 const cwd = yield* makeTempDir();
202 const fileSystem = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 // Shaped like a pnpm `node_modules`: one link per package into `.pnpm`.
205 const directoryPath = [...Array.from({ length: 80 }, () => "nested"), "node_modules"].join(
206 "/",
207 );
208 const packages = Array.from({ length: 200 }, (_, index) => `pkg-${index}`);
209 yield* Effect.forEach(
210 packages,
211 (name) =>
212 Effect.gen(function* () {
213 yield* writeTextFile(cwd, `${directoryPath}/.pnpm/${name}/index.js`);
214 yield* fileSystem.symlink(`.pnpm/${name}`, path.join(cwd, directoryPath, name));
215 }),
216 { concurrency: 32, discard: true },
217 );
218 const realpath = NodeFSP.realpath;
219 let inFlight = 0;
220 let maxInFlight = 0;
221 vi.spyOn(NodeFSP, "realpath").mockImplementation((async (target: string) => {
222 maxInFlight = Math.max(maxInFlight, ++inFlight);
223 try {
224 return await realpath(target);
225 } finally {
226 inFlight--;
227 }
228 }) as typeof NodeFSP.realpath);
229​
230 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
231 const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });
232 expect(entries.map((entry) => entry.path).toSorted()).toEqual(
233 [
234 `${directoryPath}/.pnpm`,
235 ...packages.map((name) => `${directoryPath}/${name}`),
236 ].toSorted(),
237 );
238 expect(entries.every((entry) => entry.kind === "directory")).toBe(true);
239 expect(maxInFlight).toBeLessThanOrEqual(64);
240 }),
241 );
242​
243 it.effect("labels the children of wide folders exactly as git does for each child", () =>
244 Effect.gen(function* () {
245 // Above 1,000 children, listing first asks whether the whole folder is ignored.
246 const cwd = yield* makeTempDir({ git: true });
247 const fileSystem = yield* FileSystem.FileSystem;
248 const path = yield* Path.Path;
249 const platform = yield* HostProcess.Platform;
250 yield* writeTextFile(
251 cwd,
252 ".gitignore",
253 "node_modules/\ndist/\n\\[id\\]/\n*.map\nfoo\n!foo/\n",
254 );
255 yield* Effect.forEach(
256 [
257 "node_modules",
258 "dist",
259 "[id]",
260 "src",
261 ...(platform !== "win32" ? [":foo"] : []),
262 ].flatMap((directory) =>
263 Array.from({ length: 1001 }, (_, index) => `${directory}/pkg-${index}.js`),
264 ),
265 (relativePath) => writeTextFile(cwd, relativePath),
266 { concurrency: 32, discard: true },
267 );
268 for (const relativePath of [
269 "dist/kept.js",
270 "dist/vendored/index.js",
271 "i/page.tsx",
272 "[id]/page.tsx",
273 "src/bundle.map",
274 ]) {
275 yield* writeTextFile(cwd, relativePath);
276 }
277 yield* git(cwd, ["add", "-f", "dist/kept.js", "dist/vendored/index.js", "i/page.tsx"]);
278 if (platform !== "win32") {
279 yield* fileSystem.symlink(path.join(cwd, "src"), path.join(cwd, "node_modules/link"));
280 }
281​
282 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
283 for (const { directoryPath, ignored, except } of [
284 { directoryPath: "node_modules", ignored: true, except: [] },
285 { directoryPath: "dist", ignored: true, except: ["dist/kept.js", "dist/vendored"] },
286 // git reads `[id]/page.tsx` as a pathspec, which matches the tracked `i/page.tsx`.
287 { directoryPath: "[id]", ignored: true, except: ["[id]/page.tsx"] },
288 { directoryPath: "src", ignored: false, except: ["src/bundle.map"] },
289 ...(platform !== "win32"
290 ? [
291 // git refuses to classify paths beyond a symlink, so nothing there is labelled.
292 { directoryPath: "node_modules/link", ignored: false, except: [] },
293 // Leading : is pathspec magic; Git sees foo/pkg-0.js, unignored by !foo/.
294 { directoryPath: ":foo", ignored: false, except: [] },
295 ]
296 : []),
297 ]) {
298 const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });
299 expect(entries.length, directoryPath).toBeGreaterThan(1000);
300 expect(
301 entries
302 .filter((entry) => (entry.ignored === true) !== ignored)
303 .map((entry) => entry.path)
304 .toSorted(),
305 directoryPath,
306 ).toEqual(except);
307 }
308 }),
309 );
310​
311 it.effect("lists a host folder and its parent, each from its own root", () =>
312 Effect.gen(function* () {
313 const parent = yield* makeTempDir();
314 const path = yield* Path.Path;
315 yield* writeTextFile(parent, "linked/notes.md");
316 yield* writeTextFile(parent, "sibling/readme.md");
317 const linked = path.join(parent, "linked");
318​
319 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
320 expect(yield* workspaceEntries.list({ cwd: linked, directoryPath: "" })).toEqual({
321 entries: [{ path: "notes.md", kind: "file" }],
322 truncated: false,
323 });
324 const up = yield* workspaceEntries.list({ cwd: parent, directoryPath: "" });
325 expect(up.entries.map((entry) => entry.path).toSorted()).toEqual(["linked", "sibling"]);
326 const escape = yield* workspaceEntries
327 .list({ cwd: linked, directoryPath: "../sibling" })
328 .pipe(Effect.flip);
329 expect(escape._tag).toBe("WorkspaceEntriesReadDirectoryError");
330 }),
331 );
332​
333 it.effect(
334 "rejects directory traversal, git internals, and symlinks outside the workspace",
335 () =>
336 Effect.gen(function* () {
337 const cwd = yield* makeTempDir();
338 const outside = yield* makeTempDir();
339 const fileSystem = yield* FileSystem.FileSystem;
340 const path = yield* Path.Path;
341 yield* writeTextFile(cwd, ".git/HEAD");
342 const platform = yield* HostProcess.Platform;
343 if (platform !== "win32") yield* fileSystem.symlink(outside, path.join(cwd, "external"));
344 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
345 for (const directoryPath of [
346 "../",
347 outside,
348 ".git",
349 "missing",
350 ...(platform !== "win32" ? ["external"] : []),
351 ]) {
352 const error = yield* workspaceEntries.list({ cwd, directoryPath }).pipe(Effect.flip);
353 expect(error._tag).toBe("WorkspaceEntriesReadDirectoryError");
354 }
355 }),
356 );
357​
358 it.effect("includes images and other binary files in non-git workspace indexes", () =>
359 Effect.gen(function* () {
360 const cwd = yield* makeTempDir();
361 const imagePaths = ["photo.png", "photo.jpg", "photo.jpeg"];
362 const binaryPaths = [...imagePaths, "document.pdf", "archive.zip", "data.bin"];
363 for (const filePath of binaryPaths) {
364 yield* writeTextFile(cwd, filePath, "\0binary contents\n");
365 }
366 yield* writeTextFile(cwd, "notes.txt", "plain text\n");
367​
368 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
369 const expectedPaths = [...binaryPaths, "notes.txt"].toSorted();
370 const listed = yield* workspaceEntries.list({ cwd });
371 expect(listed.entries.map((entry) => entry.path).toSorted()).toEqual(expectedPaths);
372 expect(listed.truncated).toBe(false);
373​
374 const searched = yield* workspaceEntries.search({
375 cwd,
376 query: "",
377 limit: 100,
378 kind: "file",
379 });
380 expect(searched.entries.map((entry) => entry.path).toSorted()).toEqual(expectedPaths);
381 expect(searched.truncated).toBe(false);
382​
383 const images = yield* workspaceEntries.search({
384 cwd,
385 query: "",
386 limit: 100,
387 imageOnly: true,
388 });
389 expect(images.entries.map((entry) => entry.path).toSorted()).toEqual(imagePaths.toSorted());
390 expect(images.truncated).toBe(false);
391 }),
392 );
393 });
394​
395 describe("listIgnoredFiles", () => {
396 it.effect("lists ignored files with sizes and skips wholly ignored folders", () =>
397 Effect.gen(function* () {
398 const cwd = yield* makeTempDir({ git: true });
399 yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env*\n");
400 yield* writeTextFile(cwd, ".env", "A=1");
401 yield* writeTextFile(cwd, "apps/web/index.ts", "y");
402 yield* git(cwd, ["add", "apps/web/index.ts"]);
403 yield* writeTextFile(cwd, "apps/web/.env.local", "B=22");
404 yield* writeTextFile(cwd, "node_modules/pkg/index.js", "x");
405​
406 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
407 expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
408 files: [
409 { path: ".env", byteLength: 3 },
410 { path: "apps/web/.env.local", byteLength: 4 },
411 ],
412 truncated: false,
413 });
414 }),
415 );
416 });
417​
418 describe("search", () => {
419 it.effect("applies the file filter before limiting search results", () =>
420 Effect.gen(function* () {
421 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-file-limit-" });
422 yield* writeTextFile(cwd, "src/index.ts");
423 yield* writeTextFile(cwd, "src/internal.ts");
424​
425 const result = yield* searchWorkspaceEntries({
426 cwd,
427 query: "src",
428 limit: 1,
429 kind: "file",
430 });
431​
432 // Native ranking can put either matching file first.
433 expect(result.entries).toHaveLength(1);
434 expect(result.entries[0]?.kind).toBe("file");
435 expect(["src/index.ts", "src/internal.ts"]).toContain(result.entries[0]?.path);
436 expect(result.truncated).toBe(true);
437 }),
438 );
439​
440 it.effect("excludes gitignored paths for git repositories", () =>
441 Effect.gen(function* () {
442 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
443 yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
444 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
445 yield* writeTextFile(cwd, "ignored.txt", "ignore me");
446 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
447 yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
448​
449 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
450 const paths = result.entries.map((entry) => entry.path);
451​
452 expect(paths).toContain("src");
453 expect(paths).toContain("src/keep.ts");
454 expect(paths).not.toContain("ignored.txt");
455 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
456 expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false);
457 }),
458 );
459​
460 it.effect("excludes tracked paths that match ignore rules", () =>
461 Effect.gen(function* () {
462 const cwd = yield* makeTempDir({
463 prefix: "t3code-workspace-tracked-gitignore-",
464 git: true,
465 });
466 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
467 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
468 yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
469 yield* writeTextFile(cwd, ".gitignore", ".convex/\n");
470​
471 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
472 const paths = result.entries.map((entry) => entry.path);
473​
474 expect(paths).toContain("src");
475 expect(paths).toContain("src/keep.ts");
476 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
477 }),
478 );
479 });
480​
481 describe("searchContents", () => {
482 it.effect("returns content matches with file paths, line numbers, and ranges", () =>
483 Effect.gen(function* () {
484 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-search-" });
485 yield* writeTextFile(
486 cwd,
487 "src/shapes.ts",
488 "export const square = 4;\nexport const Square = 16;\nexport const squareSize = 8;\n",
489 );
490 yield* writeTextFile(cwd, "src/other.ts", "const circle = true;\n");
491​
492 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
493 const result = yield* workspaceEntries.searchContents({
494 cwd,
495 query: "Square",
496 limit: 100,
497 caseSensitive: false,
498 wholeWord: true,
499 useRegex: false,
500 });
501​
502 expect(result.matches.map((match) => [match.path, match.lineNumber])).toEqual([
503 ["src/shapes.ts", 1],
504 ["src/shapes.ts", 2],
505 ]);
506 expect(result.matches[0]?.matchRanges).toEqual([{ start: 13, end: 19 }]);
507 expect(result.truncated).toBe(false);
508 }),
509 );
510​
511 it.effect("honors case sensitivity and gitignore rules", () =>
512 Effect.gen(function* () {
513 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-ignore-", git: true });
514 yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n");
515 yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n");
516 yield* writeTextFile(cwd, "ignored.txt", "Square\n");
517​
518 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
519 const result = yield* workspaceEntries.searchContents({
520 cwd,
521 query: "Square",
522 limit: 100,
523 caseSensitive: true,
524 wholeWord: false,
525 useRegex: false,
526 });
527​
528 expect(result.matches).toHaveLength(1);
529 expect(result.matches[0]).toMatchObject({ path: "src/keep.ts", lineNumber: 2 });
530 }),
531 );
532​
533 it.effect("finds later whole-word matches in a file after rejected raw matches", () =>
534 Effect.gen(function* () {
535 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" });
536 yield* writeTextFile(cwd, "src/words.ts", `${"afoo\n".repeat(10)}foo\n`);
537​
538 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
539 const result = yield* workspaceEntries.searchContents({
540 cwd,
541 query: "foo",
542 limit: 1,
543 caseSensitive: true,
544 wholeWord: true,
545 useRegex: false,
546 });
547​
548 expect(result.matches).toEqual([
549 expect.objectContaining({
550 path: "src/words.ts",
551 lineNumber: 11,
552 matchRanges: [{ start: 0, end: 3 }],
553 }),
554 ]);
555 }),
556 );
557​
558 it.effect("treats astral-plane letters as whole word characters", () =>
559 Effect.gen(function* () {
560 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-astral-word-" });
561 yield* writeTextFile(cwd, "src/words.ts", "𐐀foo foo foo𐐀\n");
562​
563 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
564 const result = yield* workspaceEntries.searchContents({
565 cwd,
566 query: "foo",
567 limit: 100,
568 caseSensitive: true,
569 wholeWord: true,
570 useRegex: false,
571 });
572​
573 expect(result.matches).toEqual([
574 expect.objectContaining({
575 path: "src/words.ts",
576 lineNumber: 1,
577 matchRanges: [{ start: 6, end: 9 }],
578 }),
579 ]);
580 }),
581 );
582​
583 it.effect("matches punctuation-edged whole-word queries including adjacent occurrences", () =>
584 Effect.gen(function* () {
585 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-punctuation-" });
586 yield* writeTextFile(cwd, "src/words.ts", "-foo- -foo- -foo-\n");
587​
588 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
589 const result = yield* workspaceEntries.searchContents({
590 cwd,
591 query: "-foo-",
592 limit: 100,
593 caseSensitive: true,
594 wholeWord: true,
595 useRegex: false,
596 });
597​
598 expect(result.matches).toHaveLength(1);
599 expect(result.matches[0]).toMatchObject({
600 path: "src/words.ts",
601 lineNumber: 1,
602 matchRanges: [
603 { start: 0, end: 5 },
604 { start: 6, end: 11 },
605 { start: 12, end: 17 },
606 ],
607 });
608 }),
609 );
610​
611 it.effect("caps matches per file so one dense file cannot fill the page", () =>
612 Effect.gen(function* () {
613 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" });
614 yield* writeTextFile(cwd, "src/dense.ts", "needle\n".repeat(300));
615 yield* writeTextFile(cwd, "src/other.ts", "needle\n");
616​
617 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
618 const result = yield* workspaceEntries.searchContents({
619 cwd,
620 query: "needle",
621 limit: 500,
622 caseSensitive: true,
623 wholeWord: false,
624 useRegex: false,
625 });
626​
627 const byPath = new Map<string, number>();
628 for (const match of result.matches) {
629 byPath.set(match.path, (byPath.get(match.path) ?? 0) + 1);
630 }
631 expect(byPath.get("src/dense.ts")).toBe(100);
632 expect(byPath.get("src/other.ts")).toBe(1);
633 }),
634 );
635​
636 it.effect("preserves regex escapes during case-insensitive searches", () =>
637 Effect.gen(function* () {
638 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-" });
639 yield* writeTextFile(cwd, "src/shapes.ts", "Square\nsquare\n");
640​
641 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
642 const result = yield* workspaceEntries.searchContents({
643 cwd,
644 query: "\\SQUARE",
645 limit: 100,
646 caseSensitive: false,
647 wholeWord: false,
648 useRegex: true,
649 });
650​
651 expect(result.matches.map((match) => match.lineNumber)).toEqual([1, 2]);
652 }),
653 );
654​
655 it.effect("maps multi-byte lines to string-indexed ranges", () =>
656 Effect.gen(function* () {
657 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
658 yield* writeTextFile(cwd, "src/notes.ts", 'const label = "héllo wörld";\n');
659​
660 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
661 const result = yield* workspaceEntries.searchContents({
662 cwd,
663 query: "wörld",
664 limit: 100,
665 caseSensitive: true,
666 wholeWord: false,
667 useRegex: false,
668 });
669​
670 expect(result.matches).toHaveLength(1);
671 const match = result.matches[0]!;
672 const range = match.matchRanges[0]!;
673 expect(match.lineContent.slice(range.start, range.end)).toBe("wörld");
674 }),
675 );
676 });
677​
678 describe("browse", () => {
679 it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
680 Effect.gen(function* () {
681 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
682 const path = yield* Path.Path;
683 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
684 yield* writeTextFile(cwd, ".config/settings.json", "{}");
685 yield* writeTextFile(cwd, "config/settings.json", "{}");
686 const cwdWithSeparator = yield* appendSeparator(cwd);
687​
688 const directoryResult = yield* workspaceEntries.browse({
689 partialPath: cwdWithSeparator,
690 });
691 const hiddenPrefixResult = yield* workspaceEntries.browse({
692 partialPath: `${cwdWithSeparator}.c`,
693 });
694​
695 expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
696 expect(hiddenPrefixResult).toEqual({
697 parentPath: cwd,
698 entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
699 });
700 }),
701 );
702 });
703});