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

WorkspaceSearchIndex.ts

1,412 lines52.4 KB

1// @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child
2import * as NodeFSP from "node:fs/promises";
3import * as NodeModule from "node:module";
4​
5import type {
6 DirItem,
7 FileItem,
8 FileFinder as FileFinderType,
9 GrepCursor,
10 MixedItem,
11 Result,
12 WatchEvent,
13 WatchUnsubscribe,
14} from "@ff-labs/fff-node";
15import * as Clock from "effect/Clock";
16import * as Context from "effect/Context";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as LayerMap from "effect/LayerMap";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as Schema from "effect/Schema";
25​
26import type {
27 ProjectEntry,
28 ProjectEntryKind,
29 ProjectListEntriesResult,
30 ProjectSearchContentsInput,
31 ProjectSearchContentsResult,
32 ProjectSearchEntriesResult,
33} from "@t3tools/contracts";
34import * as HostProcess from "@t3tools/shared/HostProcess";
35import { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
36import { scoreSubsequenceMatch } from "@t3tools/shared/searchRanking";
37​
38import * as VcsProcess from "../vcs/VcsProcess.ts";
39import { type IgnoreDecision, type IgnoreFile, parseIgnoreFile } from "./IgnorePatterns.ts";
40​
41// fff-node's native library stays external; single-executables require disk packages instead of importing them.
42const requireForFff = NodeModule.createRequire(import.meta.url);
43const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
44​
45// A glob intersects existing extension constraints; fff ORs bare `*.ext` constraints together.
46const IMAGE_SEARCH_CONSTRAINT = `**/*.{${PROJECT_FAVICON_EXTENSIONS.map((extension) =>
47 extension.slice(1).replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`),
48).join(",")}}`;
49​
50// fff 0.11 disables filename fallback above this match count per base/overflow segment.
51const FFF_FILENAME_FALLBACK_MAX_MATCHES = 15_000;
52​
53const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
54const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
55const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
56const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
57export const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
58const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
59const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
60const GIT_GREP_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
61// fff's lineContent cap; matches past it are reported without ranges.
62const CONTENT_LINE_MAX_LENGTH = 512;
63const SYMLINK_SCAN_CONCURRENCY = 16;
64// A scan no watcher can invalidate is reused this long, so typing does not rescan every folder.
65const UNWATCHED_SYMLINK_SCAN_TTL_MS = 2_000;
66// A rescan that outlasts this leaves the read on the previous scan.
67const SYMLINK_RESCAN_WAIT = "5 millis";
68// Each page is a synchronous native call; small pages let searches run between them.
69const SYMLINK_DIRECTORY_PAGE_SIZE = 1_000;
70​
71export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError<WorkspaceSearchIndexCreateFailed>()(
72 "WorkspaceSearchIndexCreateFailed",
73 {
74 cwd: Schema.String,
75 reason: Schema.String,
76 cause: Schema.optional(Schema.Defect()),
77 },
78) {
79 override get message(): string {
80 return `Failed to create the workspace search index for '${this.cwd}'.`;
81 }
83​
84export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedError<WorkspaceSearchIndexScanTimedOut>()(
85 "WorkspaceSearchIndexScanTimedOut",
86 {
87 cwd: Schema.String,
88 timeout: Schema.String,
89 },
90) {
91 override get message(): string {
92 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
93 }
95​
96export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedError<WorkspaceSearchIndexSearchFailed>()(
97 "WorkspaceSearchIndexSearchFailed",
98 {
99 cwd: Schema.String,
100 queryLength: Schema.Number,
101 pageSize: Schema.Number,
102 reason: Schema.String,
103 cause: Schema.optional(Schema.Defect()),
104 },
105) {
106 override get message(): string {
107 return `Workspace search failed for '${this.cwd}'.`;
108 }
110​
111export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedError<WorkspaceSearchIndexRefreshFailed>()(
112 "WorkspaceSearchIndexRefreshFailed",
113 {
114 cwd: Schema.String,
115 reason: Schema.String,
116 cause: Schema.optional(Schema.Defect()),
117 },
118) {
119 override get message(): string {
120 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
121 }
123​
124export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<WorkspaceSearchIndexDestroyFailed>()(
125 "WorkspaceSearchIndexDestroyFailed",
126 {
127 cwd: Schema.String,
128 cause: Schema.Defect(),
129 },
130) {
131 override get message(): string {
132 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
133 }
135​
136export class WorkspaceSearchIndex extends Context.Service<
137 WorkspaceSearchIndex,
138 {
139 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
140 readonly search: (
141 query: string,
142 limit: number,
143 kind?: ProjectEntryKind,
144 imageOnly?: boolean,
145 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
146 readonly searchContents: (
147 input: Omit<ProjectSearchContentsInput, "cwd">,
148 ) => Effect.Effect<
149 ProjectSearchContentsResult,
150 WorkspaceSearchIndexScanTimedOut | WorkspaceSearchIndexSearchFailed
151 >;
152 readonly refresh: () => Effect.Effect<void, WorkspaceSearchIndexRefreshFailed>;
153 }
154>()("t3/workspace/WorkspaceSearchIndex") {}
155​
156// Only the host separator becomes `/`: on POSIX `\` is a file name character.
157function toPosixPath(input: string, hostIsWindows: boolean): string {
158 return hostIsWindows ? input.replaceAll("\\", "/") : input;
160​
161function trimDirectorySeparator(input: string): string {
162 return input.endsWith("/") ? input.slice(0, -1) : input;
164​
165function parentPathOf(input: string): string | undefined {
166 const separatorIndex = input.lastIndexOf("/");
167 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
169​
170function toProjectEntry(item: MixedItem, hostIsWindows: boolean): ProjectEntry | null {
171 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath, hostIsWindows));
172 if (!normalizedPath) {
173 return null;
174 }
175​
176 return {
177 path: normalizedPath,
178 kind: item.type,
179 };
181​
182function toFileEntry(item: FileItem, hostIsWindows: boolean): ProjectEntry | null {
183 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
184 return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
186​
187function toDirectoryEntry(item: DirItem, hostIsWindows: boolean): ProjectEntry | null {
188 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
189 return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
191​
192function isLoneFuzzyPath(query: string): boolean {
193 const trimmed = query.trim();
194 return (
195 !/\s/u.test(trimmed) &&
196 (trimmed.startsWith("/") || (trimmed.endsWith("/") && !/^[*!\\]/u.test(trimmed)))
197 );
199​
200type SearchPage<I> = { readonly items: ReadonlyArray<I>; readonly totalMatched: number };
201​
202function mapFileSearchResult(
203 result: SearchPage<FileItem>,
204 limit: number,
205 hostIsWindows: boolean,
206 imageOnly = false,
207): ProjectSearchEntriesResult {
208 const entries = result.items.flatMap((item) => {
209 const entry = toFileEntry(item, hostIsWindows);
210 return entry && (!imageOnly || isProjectFaviconPath(entry.path)) ? [entry] : [];
211 });
212 return {
213 entries: entries.slice(0, limit),
214 truncated: entries.length > limit || result.totalMatched > result.items.length,
215 };
217​
218function mapDirectorySearchResult(
219 result: SearchPage<DirItem>,
220 limit: number,
221 hostIsWindows: boolean,
222): ProjectSearchEntriesResult {
223 const entries = result.items.flatMap((item) => {
224 const entry = toDirectoryEntry(item, hostIsWindows);
225 return entry ? [entry] : [];
226 });
227 const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
228 return {
229 entries: entries.slice(0, limit),
230 truncated: result.totalMatched - rootDirectoryCount > limit,
231 };
233​
234function mapMixedSearchResult(
235 result: SearchPage<MixedItem>,
236 limit: number,
237 hostIsWindows: boolean,
238): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
239 const entries: ProjectEntry[] = [];
240 for (const item of result.items) {
241 const entry = toProjectEntry(item, hostIsWindows);
242 if (entry) {
243 entries.push(entry);
244 }
245 if (entries.length >= limit) {
246 break;
247 }
248 }
249​
250 const rootDirectoryCount = result.items.some(
251 (item) => item.type === "directory" && item.item.relativePath.length === 0,
252 )
253 ? 1
254 : 0;
255 return {
256 entries,
257 truncated: result.totalMatched - rootDirectoryCount > limit,
258 };
260​
261const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
262​
263function codePointAt(line: string, index: number): string | undefined {
264 const codePoint = line.codePointAt(index);
265 return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
267​
268function codePointBefore(line: string, index: number): string | undefined {
269 if (index <= 0) return undefined;
270 const previousCodeUnit = line.charCodeAt(index - 1);
271 const previousIndex =
272 previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
273 return codePointAt(line, previousIndex);
275​
276function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
277 readonly searchQuery: string;
278 readonly regexMode: boolean;
279} {
280 if (input.caseSensitive) {
281 return { searchQuery: input.query, regexMode: input.useRegex };
282 }
283 return input.useRegex
284 ? { searchQuery: `(?i)${input.query}`, regexMode: true }
285 : { searchQuery: input.query.toLowerCase(), regexMode: false };
287​
288function mapContentMatchRanges(
289 line: string,
290 byteRanges: ReadonlyArray<readonly [number, number]>,
291): Array<{ readonly start: number; readonly end: number }> {
292 const lineBytes = Buffer.from(line);
293 const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
294 return byteRanges.map(([startByte, endByte]) => ({
295 start: toStringIndex(startByte),
296 end: toStringIndex(endByte),
297 }));
299​
300function escapeRegExp(input: string): string {
301 return input.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
303​
304// Git before 2.55 reports wrong `--column` values for every match after a line's first, so
305// later matches are found by their text, searching on from the end of the previous one.
306function locateRegexMatches(
307 line: string,
308 matches: { readonly column: number; readonly texts: ReadonlyArray<string> } | undefined,
309): Array<readonly [number, number]> {
310 if (!matches) return [];
311 const lineBytes = Buffer.from(line);
312 const ranges: Array<readonly [number, number]> = [];
313 let start = matches.column - 1;
314 for (const text of matches.texts) {
315 const textBytes = Buffer.from(text);
316 if (ranges.length > 0) start = lineBytes.indexOf(textBytes, ranges.at(-1)![1]);
317 if (start < 0) break;
318 ranges.push([start, start + textBytes.length]);
319 }
320 return ranges;
322​
323// `git grep -z` records: NUL-separated fields, one record per line; a truncated last line is dropped.
324function parseGitGrepRecords(
325 stdout: string,
326 fieldCount: number,
327 truncated: boolean,
328): Array<Array<string>> {
329 const lines = stdout.split("\n");
330 if (truncated || lines.at(-1) === "") lines.pop();
331 const records: Array<Array<string>> = [];
332 for (const line of lines) {
333 const fields = line.split("\0");
334 if (fields.length < fieldCount) continue;
335 // Only the last field (the line or match text) can contain NUL bytes.
336 records.push([...fields.slice(0, fieldCount - 1), fields.slice(fieldCount - 1).join("\0")]);
337 }
338 return records;
340​
341// Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges.
342function isWholeWordRange(
343 line: string,
344 range: { readonly start: number; readonly end: number },
345): boolean {
346 if (range.end <= range.start) return false;
347 const isWord = (character: string | undefined) =>
348 character !== undefined && WORD_CHARACTER.test(character);
349 const leftIsBoundary =
350 range.start === 0 ||
351 !isWord(codePointBefore(line, range.start)) ||
352 !isWord(codePointAt(line, range.start));
353 const rightIsBoundary =
354 range.end >= line.length ||
355 !isWord(codePointAt(line, range.end)) ||
356 !isWord(codePointBefore(line, range.end));
357 return leftIsBoundary && rightIsBoundary;
359​
360function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
361 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
362 for (const entry of entries) {
363 let parentPath = parentPathOf(entry.path);
364 while (parentPath) {
365 if (!entryByPath.has(parentPath)) {
366 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
367 }
368 parentPath = parentPathOf(parentPath);
369 }
370 }
371 return [...entryByPath.values()];
373​
374interface ScannedDirectory {
375 readonly directory: string;
376 readonly links: ReadonlyArray<ProjectEntry>;
377 /** Every symlink in the folder, including ones dropped for leaving the workspace. */
378 readonly linkPaths: ReadonlyArray<string>;
379 /** A nested repository (or the workspace's own), whose ignore rules own what is below it. */
380 readonly isRepository: boolean;
381 readonly ignoreFile: string | undefined;
383​
384const joinEntryPath = (directory: string, name: string) =>
385 directory ? `${directory}/${name}` : name;
386​
387/**
388 * fff skips symlinks, and `followSymlinks` drops file links, dedupes folder links, and walks out
389 * of the workspace. So links are read from the folders fff already indexed (ignore rules applied),
390 * without descending into them, and kept only when they resolve inside the workspace.
391 */
392const scanDirectory = Effect.fn("WorkspaceSearchIndex.scanDirectory")(function* (
393 fileSystem: FileSystem.FileSystem,
394 path: Path.Path,
395 cwd: string,
396 root: string,
397 directory: string,
398) {
399 // Effect's readDirectory returns bare names; one lstat per child would cost far more.
400 const children = yield* Effect.promise(() =>
401 NodeFSP.readdir(path.join(cwd, directory), { withFileTypes: true }).catch(() => []),
402 );
403 const links: ProjectEntry[] = [];
404 const linkPaths: string[] = [];
405 let isRepository = false;
406 let ignoreFile: string | undefined;
407 for (const child of children) {
408 if (child.name === ".git") isRepository = true;
409 if (child.name === ".ignore" && child.isFile()) {
410 ignoreFile = yield* fileSystem
411 .readFileString(path.join(cwd, directory, child.name))
412 .pipe(Effect.orElseSucceed(() => undefined));
413 }
414 if (!child.isSymbolicLink()) continue;
415 const entryPath = joinEntryPath(directory, child.name);
416 linkPaths.push(entryPath);
417 const absolutePath = path.join(cwd, entryPath);
418 const target = yield* Effect.all([
419 fileSystem.realPath(absolutePath),
420 fileSystem.stat(absolutePath),
421 ]).pipe(Effect.orElseSucceed(() => undefined));
422 if (!target) continue;
423 const relative = path.relative(root, target[0]);
424 if (
425 relative === ".." ||
426 relative.startsWith(`..${path.sep}`) ||
427 path.isAbsolute(relative) ||
428 relative.split(path.sep).includes(".git") ||
429 (target[1].type !== "Directory" && target[1].type !== "File")
430 ) {
431 continue;
432 }
433 links.push({ path: entryPath, kind: target[1].type === "Directory" ? "directory" : "file" });
434 }
435 return { directory, links, linkPaths, isRepository, ignoreFile } satisfies ScannedDirectory;
436});
437​
438/** Whether `entryPath` is `directory` itself or below it. */
439const isWithin = (entryPath: string, directory: string) =>
440 directory === "" || entryPath.startsWith(`${directory}/`);
441​
442/**
443 * fff reads `.ignore` files alongside git's rules, and like ripgrep the nearest one that matches
444 * decides, ahead of any `.gitignore`. `ignoreFiles` is ordered deepest folder first.
445 */
446function decideByIgnoreFiles(
447 entry: ProjectEntry,
448 ignoreFiles: ReadonlyArray<{ readonly directory: string; readonly file: IgnoreFile }>,
449): IgnoreDecision | undefined {
450 for (const { directory, file } of ignoreFiles) {
451 if (!isWithin(entry.path, directory) || entry.path === directory) continue;
452 const relative = directory ? entry.path.slice(directory.length + 1) : entry.path;
453 // Like git and ripgrep, a link is never a folder to a folder-only rule, whatever it targets.
454 const decision = file.decide(relative, false);
455 if (decision) return decision;
456 }
457 return undefined;
459​
460/** Places each symlink before the first index result that matches the query less closely. */
461function mergeSymlinkMatches(
462 indexed: ProjectSearchEntriesResult,
463 linkPaths: ReadonlySet<string>,
464 symlinks: ReadonlyArray<ProjectEntry>,
465 query: string,
466 limit: number,
467): ProjectSearchEntriesResult {
468 if (linkPaths.size === 0) return indexed;
469 // fff's watcher indexes links created after its scan, under a kind of its own choosing, so a
470 // path it already returned takes the link's kind (or drops out of a kind-filtered search).
471 const symlinkByPath = new Map(symlinks.map((entry) => [entry.path, entry]));
472 const score = (entry: ProjectEntry) =>
473 scoreSubsequenceMatch(entry.path.toLowerCase(), query) ?? Number.POSITIVE_INFINITY;
474 const indexedPaths = new Set(indexed.entries.map((entry) => entry.path));
475 const pending = symlinks
476 .flatMap((entry) => {
477 const entryScore = score(entry);
478 return Number.isFinite(entryScore) && !indexedPaths.has(entry.path)
479 ? [{ entry, score: entryScore }]
480 : [];
481 })
482 .toSorted((left, right) => left.score - right.score);
483 const entries: ProjectEntry[] = [];
484 let nextPending = 0;
485 for (const indexedEntry of indexed.entries) {
486 const entry = linkPaths.has(indexedEntry.path)
487 ? symlinkByPath.get(indexedEntry.path)
488 : indexedEntry;
489 if (!entry) continue;
490 const entryScore = score(entry);
491 while (nextPending < pending.length && pending[nextPending]!.score < entryScore) {
492 entries.push(pending[nextPending++]!.entry);
493 }
494 entries.push(entry);
495 }
496 for (; nextPending < pending.length; nextPending += 1) entries.push(pending[nextPending]!.entry);
497 return {
498 entries: entries.slice(0, limit),
499 truncated: indexed.truncated || entries.length > limit,
500 };
502​
503// fff applies .gitignore files only; Git also ignores paths from .git/info/exclude and the global excludes file.
504const listGitIgnoredPaths = Effect.fn("WorkspaceSearchIndex.listGitIgnoredPaths")(function* (
505 vcsProcess: VcsProcess.VcsProcess["Service"],
506 cwd: string,
507 hostIsWindows: boolean,
508) {
509 const result = yield* vcsProcess
510 .run({
511 operation: "WorkspaceSearchIndex.listGitIgnoredPaths",
512 command: "git",
513 args: [
514 "-c",
515 "core.fsmonitor=false",
516 "ls-files",
517 "--others",
518 "--ignored",
519 "--exclude-standard",
520 "--directory",
521 "-z",
522 ],
523 cwd,
524 allowNonZeroExit: true,
525 timeoutMs: 10_000,
526 maxOutputBytes: 16 * 1024 * 1024,
527 })
528 .pipe(Effect.orElseSucceed(() => undefined));
529 if (!result || result.exitCode !== 0 || result.stdoutTruncated) return [];
530 // Folders keep their trailing `/`.
531 return result.stdout
532 .split("\0")
533 .filter((entry) => entry.length > 0)
534 .map((entry) => toPosixPath(entry, hostIsWindows));
535});
536​
537function mixedItemPath(item: MixedItem): string {
538 return item.item.relativePath;
540​
541function isIgnoredPath(
542 ignoredPaths: ReadonlySet<string>,
543 relativePath: string,
544 hostIsWindows: boolean,
545): boolean {
546 if (ignoredPaths.size === 0) return false;
547 let candidate: string | undefined = trimDirectorySeparator(
548 toPosixPath(relativePath, hostIsWindows),
549 );
550 while (candidate) {
551 if (ignoredPaths.has(candidate)) return true;
552 candidate = parentPathOf(candidate);
553 }
554 return false;
556​
557const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
558 cwd: string,
559 variant: WorkspaceSearchIndexVariant,
560) {
561 const result = yield* Effect.try({
562 try: () =>
563 FileFinder.create({
564 basePath: cwd,
565 disableMmapCache: true,
566 // Content indexing costs CPU/memory; path-only consumers use the lightweight index.
567 disableContentIndexing: variant !== "content",
568 aiMode: false,
569 }),
570 catch: (cause) =>
571 new WorkspaceSearchIndexCreateFailed({
572 cwd,
573 reason: "FileFinder.create threw unexpectedly.",
574 cause,
575 }),
576 });
577 if (result.ok) return result.value;
578 return yield* new WorkspaceSearchIndexCreateFailed({
579 cwd,
580 reason: result.error,
581 });
582});
583​
584const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
585 cwd: string,
586 finder: FileFinderType,
587 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
588): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
589 const result = yield* Effect.tryPromise({
590 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
591 catch: (cause) =>
592 onFailure({
593 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
594 cause,
595 }),
596 });
597 if (!result.ok) {
598 return yield* Effect.fail(onFailure({ reason: result.error }));
599 }
600 if (!result.value) {
601 return yield* new WorkspaceSearchIndexScanTimedOut({
602 cwd,
603 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
604 });
605 }
606});
607​
608export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
609 cwd: string,
610 variant: WorkspaceSearchIndexVariant = "paths",
611) {
612 const hostIsWindows = yield* HostProcess.isWindows;
613 const fileSystem = yield* FileSystem.FileSystem;
614 const path = yield* Path.Path;
615 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
616 Effect.try({
617 try: () => finder.destroy(),
618 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
619 }).pipe(Effect.orDie),
620 );
621 let initialScanTimedOut = false;
622 // The content index reads every file, which takes minutes where antivirus scans each open,
623 // so content searches do not wait for it; git grep answers until it is ready.
624 let contentIndexPending = variant === "content";
625 const vcsProcess = yield* VcsProcess.VcsProcess;
626​
627 /** The nearest `.ignore` with a pattern matching `relativePath` itself decides. */
628 const makeIgnoreFileDecider = () => {
629 const ignoreFiles = new Map<string, IgnoreFile | undefined>();
630 const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* (
631 directory: string,
632 ) {
633 if (ignoreFiles.has(directory)) return ignoreFiles.get(directory);
634 const contents = yield* fileSystem
635 .readFileString(path.join(cwd, directory, ".ignore"))
636 .pipe(Effect.option);
637 const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined;
638 ignoreFiles.set(directory, file);
639 return file;
640 });
641 return Effect.fn("WorkspaceSearchIndex.decideByIgnoreFile")(function* (
642 relativePath: string,
643 isFolder: boolean,
644 ) {
645 const segments = relativePath.split("/");
646 for (let ancestor = segments.length - 1; ancestor >= 0; ancestor -= 1) {
647 const directory = segments.slice(0, ancestor).join("/");
648 const file = yield* readIgnoreFile(directory);
649 const relative = directory ? relativePath.slice(directory.length + 1) : relativePath;
650 const decision = file?.decide(relative, isFolder);
651 if (decision) return decision;
652 }
653 return undefined;
654 });
655 };
656​
657 // Like ripgrep and fff, a `.ignore` that re-includes a path overrules Git's ignore rules for it.
658 const loadIgnoredPaths = Effect.fn("WorkspaceSearchIndex.loadIgnoredPaths")(function* () {
659 const decide = makeIgnoreFileDecider();
660 const ignored = new Set<string>();
661 for (const entry of yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows)) {
662 const relativePath = trimDirectorySeparator(entry);
663 if ((yield* decide(relativePath, entry.endsWith("/"))) !== "included") {
664 ignored.add(relativePath);
665 }
666 }
667 return ignored;
668 });
669 let ignoredPaths = yield* loadIgnoredPaths();
670 if (variant === "paths") {
671 yield* waitForIndexReady(
672 cwd,
673 finder,
674 ({ reason, cause }) =>
675 new WorkspaceSearchIndexCreateFailed({
676 cwd,
677 reason,
678 cause,
679 }),
680 ).pipe(
681 Effect.catchTags({
682 WorkspaceSearchIndexScanTimedOut: () =>
683 Effect.sync(() => {
684 initialScanTimedOut = true;
685 }),
686 }),
687 );
688 }
689​
690 // fff's isScanning takes the picker lock too, so progress is read off the JS thread.
691 const isScanning = Effect.promise(async () => {
692 try {
693 const progress = await finder.getScanProgressAsync();
694 return !progress.ok || progress.value.isScanning;
695 } catch {
696 return true;
697 }
698 });
699 const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false));
700​
701 const isContentIndexReady = Effect.fn("WorkspaceSearchIndex.isContentIndexReady")(function* () {
702 if (!contentIndexPending) return true;
703 const progress = yield* Effect.promise(() =>
704 finder.getScanProgressAsync().catch(() => undefined),
705 );
706 if (progress?.ok && !progress.value.isScanning && progress.value.isWarmupComplete) {
707 contentIndexPending = false;
708 }
709 return !contentIndexPending;
710 });
711​
712 const runGitGrep = Effect.fn("WorkspaceSearchIndex.runGitGrep")(function* (
713 pattern: string,
714 options: {
715 readonly regexMode: boolean;
716 readonly ignoreCase: boolean;
717 readonly maxMatchesPerFile: number;
718 readonly onlyMatching: boolean;
719 },
720 ) {
721 return yield* vcsProcess
722 .run({
723 operation: "WorkspaceSearchIndex.gitGrep",
724 command: "git",
725 args: [
726 "-c",
727 "core.quotePath=false",
728 "-c",
729 "core.fsmonitor=false",
730 "grep",
731 "--untracked",
732 "--no-color",
733 "-I",
734 "-n",
735 "-z",
736 "-m",
737 String(options.maxMatchesPerFile),
738 ...(options.onlyMatching ? ["-o", "--column"] : []),
739 ...(options.ignoreCase ? ["-i"] : []),
740 options.regexMode ? "-P" : "-F",
741 "-e",
742 pattern,
743 ],
744 cwd,
745 allowNonZeroExit: true,
746 // Defender scanning fff's warmup reads slows git too; a late answer beats a failure.
747 timeoutMs: 30_000,
748 maxOutputBytes: GIT_GREP_MAX_OUTPUT_BYTES,
749 outputMode: "truncate",
750 appendTruncationMarker: false,
751 })
752 .pipe(Effect.option);
753 });
754​
755 // fff leaves out what `.ignore` files exclude, which git cannot evaluate; the nearest
756 // `.ignore` that matches a path or one of its folders decides, as in decideByIgnoreFiles.
757 const makeIgnoreFileFilter = () => {
758 const decide = makeIgnoreFileDecider();
759 return Effect.fn("WorkspaceSearchIndex.isExcludedByIgnoreFiles")(function* (
760 relativePath: string,
761 ) {
762 const segments = relativePath.split("/");
763 for (let depth = 1; depth <= segments.length; depth += 1) {
764 const candidate = segments.slice(0, depth).join("/");
765 if ((yield* decide(candidate, depth < segments.length)) === "ignored") return true;
766 }
767 return false;
768 });
769 };
770​
771 // fff's grep before its content index is ready opens every file itself, as slowly as the build.
772 // None when git cannot search this folder (not a repository, git missing, no PCRE for a regex).
773 const searchContentsWithGit = Effect.fn("WorkspaceSearchIndex.searchContentsWithGit")(function* (
774 input: Omit<ProjectSearchContentsInput, "cwd">,
775 ): Effect.fn.Return<Option.Option<ProjectSearchContentsResult>> {
776 const options = {
777 ignoreCase: !input.caseSensitive,
778 maxMatchesPerFile: CONTENT_SEARCH_MAX_MATCHES_PER_FILE,
779 onlyMatching: false,
780 };
781 let regexMode = input.useRegex;
782 let regexFallbackError: string | undefined;
783 let result = yield* runGitGrep(input.query, { ...options, regexMode });
784 if (regexMode && Option.isSome(result) && result.value.exitCode === 128) {
785 if (/USE_LIBPCRE|Perl-compatible/i.test(result.value.stderr)) return Option.none();
786 // fff searches an invalid pattern as a literal and reports why.
787 regexFallbackError = result.value.stderr.trim().split("\n")[0] || "Invalid regex";
788 regexMode = false;
789 result = yield* runGitGrep(input.query, { ...options, regexMode });
790 }
791 if (Option.isNone(result) || result.value.exitCode > 1) return Option.none();
792​
793 // Per line: the first match's byte column and every match's text, in order.
794 const regexMatches = new Map<string, { readonly column: number; readonly texts: string[] }>();
795 let rangesTruncated = false;
796 if (regexMode) {
797 // Ranges come from git too: running the user's pattern in JS could backtrack without bound.
798 const ranges = yield* runGitGrep(input.query, { ...options, regexMode, onlyMatching: true });
799 // Without ranges, whole-word filtering would drop every hit and report no matches.
800 if (Option.isNone(ranges) || ranges.value.exitCode > 1) return Option.none();
801 rangesTruncated = ranges.value.stdoutTruncated;
802 if (ranges.value.exitCode === 0) {
803 for (const record of parseGitGrepRecords(
804 ranges.value.stdout,
805 4,
806 ranges.value.stdoutTruncated,
807 )) {
808 const [relativePath, lineNumber, column, text] = record as [
809 string,
810 string,
811 string,
812 string,
813 ];
814 const key = `${relativePath}\0${lineNumber}`;
815 const lineMatches = regexMatches.get(key);
816 if (lineMatches) lineMatches.texts.push(text);
817 else regexMatches.set(key, { column: Number(column), texts: [text] });
818 }
819 }
820 }
821 const literal = regexMode
822 ? undefined
823 : new RegExp(escapeRegExp(input.query), input.caseSensitive ? "gu" : "giu");
824​
825 const isExcludedByIgnoreFiles = makeIgnoreFileFilter();
826 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
827 let rangesCutOff = false;
828 for (const record of parseGitGrepRecords(
829 result.value.stdout,
830 3,
831 result.value.stdoutTruncated,
832 )) {
833 const [relativePath, lineNumber, rawLine] = record as [string, string, string];
834 if (yield* isExcludedByIgnoreFiles(relativePath)) continue;
835 const key = `${relativePath}\0${lineNumber}`;
836 // Lines past the cut-off of a truncated ranges run have no ranges; stop there instead.
837 if (rangesTruncated && !regexMatches.has(key)) {
838 rangesCutOff = true;
839 break;
840 }
841 const lineContent = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).slice(
842 0,
843 CONTENT_LINE_MAX_LENGTH,
844 );
845 const matchRanges = (
846 literal
847 ? Array.from(lineContent.matchAll(literal), (match) => ({
848 start: match.index,
849 end: match.index + match[0].length,
850 }))
851 : mapContentMatchRanges(
852 lineContent,
853 locateRegexMatches(lineContent, regexMatches.get(key)),
854 )
855 ).filter(
856 (range) =>
857 range.end <= lineContent.length &&
858 (!input.wholeWord || isWholeWordRange(lineContent, range)),
859 );
860 if (input.wholeWord && matchRanges.length === 0) continue;
861 matches.push({
862 path: relativePath,
863 lineNumber: Number(lineNumber),
864 lineContent,
865 matchRanges,
866 });
867 if (matches.length > input.limit) break;
868 }
869 return Option.some({
870 matches: matches.slice(0, input.limit),
871 truncated: matches.length > input.limit || result.value.stdoutTruncated || rangesCutOff,
872 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
873 });
874 });
875​
876 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
877 query: string,
878 pageSize: number,
879 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
880 execute: () => Promise<Result<A>>,
881 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
882 // fff's searches wait on its picker lock, which its watcher can hold for minutes.
883 const result = yield* Effect.tryPromise({
884 try: execute,
885 catch: (cause) =>
886 new WorkspaceSearchIndexSearchFailed({
887 cwd,
888 queryLength: query.length,
889 pageSize,
890 reason: `FileFinder.${operation} rejected unexpectedly.`,
891 cause,
892 }),
893 });
894 if (!result.ok) {
895 return yield* new WorkspaceSearchIndexSearchFailed({
896 cwd,
897 queryLength: query.length,
898 pageSize,
899 reason: result.error,
900 });
901 }
902 return result.value;
903 });
904​
905 const root = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
906​
907 const listIndexedDirectories = Effect.fn("WorkspaceSearchIndex.listIndexedDirectories")(
908 function* () {
909 const directories: string[] = [];
910 // fff's pageIndex is an offset into the results, not a page number.
911 for (let pageIndex = 0; ; pageIndex += SYMLINK_DIRECTORY_PAGE_SIZE) {
912 const result = yield* Effect.promise(async () => {
913 try {
914 return await finder.directorySearchAsync("", {
915 pageIndex,
916 pageSize: SYMLINK_DIRECTORY_PAGE_SIZE,
917 });
918 } catch {
919 return undefined;
920 }
921 });
922 if (!result?.ok) return directories;
923 for (const item of result.value.items) {
924 const directory = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
925 if (directory) directories.push(directory);
926 }
927 if (result.value.items.length < SYMLINK_DIRECTORY_PAGE_SIZE) return directories;
928 }
929 },
930 );
931​
932 /** Ignore rules belong to the repository that owns a path, so each one answers for its own. */
933 const listGitIgnored = Effect.fn("WorkspaceSearchIndex.listGitIgnored")(function* (
934 repository: string,
935 entries: ReadonlyArray<ProjectEntry>,
936 ) {
937 const relativePaths = entries.map((entry) =>
938 repository ? entry.path.slice(repository.length + 1) : entry.path,
939 );
940 const repositoryCwd = path.join(cwd, repository);
941 const result = yield* vcsProcess
942 .run({
943 operation: "WorkspaceSearchIndex.listGitIgnored",
944 command: "git",
945 // fff applies ignore rules to tracked paths too, so the index is not consulted.
946 args: ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "-z", "--stdin"],
947 cwd: repositoryCwd,
948 stdin: `${relativePaths.join("\0")}\0`,
949 allowNonZeroExit: true,
950 timeoutMs: 10_000,
951 maxOutputBytes: 16 * 1024 * 1024,
952 })
953 .pipe(Effect.orElseSucceed(() => undefined));
954 // Exit 1 means nothing matched.
955 if (result?.exitCode === 1) return [];
956 if (result?.exitCode !== 0 || result.stdoutTruncated) {
957 // Outside git no rules apply (git exits before reading stdin, so the cause is lost).
958 // Any other failure hides the repository's links rather than leaking ones it ignores.
959 const insideRepository = yield* vcsProcess
960 .run({
961 operation: "WorkspaceSearchIndex.listGitIgnored",
962 command: "git",
963 args: ["rev-parse", "--git-dir"],
964 cwd: repositoryCwd,
965 timeoutMs: 10_000,
966 })
967 .pipe(
968 Effect.as(true),
969 Effect.orElseSucceed(() => false),
970 );
971 return insideRepository ? entries.map((entry) => entry.path) : [];
972 }
973 return result.stdout
974 .split("\0")
975 .filter(Boolean)
976 .map((relativePath) => (repository ? `${repository}/${relativePath}` : relativePath));
977 });
978​
979 const scanSymlinkEntries = Effect.fn("WorkspaceSearchIndex.scanSymlinkEntries")(function* () {
980 const indexComplete = !(yield* isScanning);
981 const directories = yield* listIndexedDirectories();
982 const scanned = yield* Effect.forEach(
983 ["", ...directories],
984 (directory) => scanDirectory(fileSystem, path, cwd, root, directory),
985 { concurrency: SYMLINK_SCAN_CONCURRENCY },
986 );
987 const candidates = scanned.flatMap((directory) => directory.links);
988 const linkPaths = new Set(scanned.flatMap((directory) => directory.linkPaths));
989 if (candidates.length === 0) return { entries: candidates, linkPaths, indexComplete };
990​
991 const ignoreFiles = scanned
992 .flatMap(({ directory, ignoreFile }) =>
993 ignoreFile === undefined ? [] : [{ directory, file: parseIgnoreFile(ignoreFile) }],
994 )
995 .toSorted((left, right) => right.directory.length - left.directory.length);
996 const decisions = new Map(
997 candidates.map((entry) => [entry.path, decideByIgnoreFiles(entry, ignoreFiles)]),
998 );
999 const repositories = [
1000 "",
1001 ...scanned.flatMap(({ directory, isRepository }) =>
1002 isRepository && directory ? [directory] : [],
1003 ),
1004 ].toSorted((left, right) => right.length - left.length);
1005 const entriesByRepository = Map.groupBy(
1006 candidates.filter((entry) => decisions.get(entry.path) === undefined),
1007 (entry) =>
1008 repositories.find(
1009 (repository) => isWithin(entry.path, repository) && entry.path !== repository,
1010 ) ?? "",
1011 );
1012 const ignored = new Set(
1013 (yield* Effect.forEach(
1014 entriesByRepository,
1015 ([repository, entries]) => listGitIgnored(repository, entries),
1016 { concurrency: 4 },
1017 )).flat(),
1018 );
1019 return {
1020 entries: candidates.filter((entry) =>
1021 decisions.get(entry.path) === undefined
1022 ? !ignored.has(entry.path)
1023 : decisions.get(entry.path) === "included",
1024 ),
1025 linkPaths,
1026 indexComplete,
1027 };
1028 });
1029​
1030 // One scan runs at a time and outlives the reads that started it. Only the first read waits for
1031 // it in full: after that a change or expiry marks the result stale, and reads wait briefly for
1032 // the rescan before answering from the last finished one, so file churn cannot stall search.
1033 type SymlinkScan = Effect.Success<ReturnType<typeof scanSymlinkEntries>>;
1034 let lastSymlinkScan: SymlinkScan | undefined;
1035 let lastSymlinkScanExpiresAt: number | undefined;
1036 let pendingSymlinkScan: Deferred.Deferred<SymlinkScan> | undefined;
1037 let symlinkScanStale = false;
1038 let knownLinkPaths: ReadonlySet<string> = new Set();
1039 const invalidateSymlinkScan = () => {
1040 symlinkScanStale = true;
1041 };
1042 const isKnownLink = (absolutePath: string) =>
1043 [cwd, root].some((base) =>
1044 knownLinkPaths.has(toPosixPath(path.relative(base, absolutePath), hostIsWindows)),
1045 );
1046 const onWatchBatch = (events: ReadonlyArray<WatchEvent>) => {
1047 // fff reports a link replaced in place as `modified`, so edits to known links count too.
1048 const editsOnly = events.every(
1049 (event) =>
1050 event.kind === "modified" &&
1051 !/(^|[\\/])\.(git)?ignore$/.test(event.path) &&
1052 !isKnownLink(event.path),
1053 );
1054 if (!editsOnly) invalidateSymlinkScan();
1055 };
1056 // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so
1057 // each read retries until one is in place. Subscribing waits on fff's picker lock, which its
1058 // watcher holds while it indexes a new folder, so it runs off the JS thread.
1059 let unwatch: WatchUnsubscribe | undefined;
1060 yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.()));
1061 const ensureWatching = Effect.fn("WorkspaceSearchIndex.ensureWatching")(function* () {
1062 if (unwatch) return true;
1063 const result = yield* Effect.promise(() =>
1064 finder.watchAsync(onWatchBatch).catch(() => undefined),
1065 );
1066 if (result?.ok) unwatch = result.value;
1067 return unwatch !== undefined;
1068 });
1069 const indexScope = yield* Effect.scope;
1070 const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () {
1071 symlinkScanStale = false;
1072 const done = yield* Deferred.make<SymlinkScan>();
1073 pendingSymlinkScan = done;
1074 yield* Effect.gen(function* () {
1075 // Subscribing before the scan starts means no change during it goes unseen.
1076 const watched = yield* ensureWatching();
1077 const result = yield* scanSymlinkEntries();
1078 lastSymlinkScan = result;
1079 knownLinkPaths = result.linkPaths;
1080 // Without a watcher, or before fff has seen every folder, the result is kept only briefly.
1081 lastSymlinkScanExpiresAt =
1082 watched && result.indexComplete
1083 ? undefined
1084 : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS;
1085 return result;
1086 }).pipe(
1087 Effect.onExit((exit) =>
1088 Effect.sync(() => {
1089 pendingSymlinkScan = undefined;
1090 }).pipe(Effect.andThen(Deferred.done(done, exit))),
1091 ),
1092 Effect.forkIn(indexScope),
1093 );
1094 return done;
1095 });
1096 const listSymlinkEntries = Effect.fn("WorkspaceSearchIndex.listSymlinkEntries")(function* () {
1097 if (
1098 lastSymlinkScanExpiresAt !== undefined &&
1099 (yield* Clock.currentTimeMillis) >= lastSymlinkScanExpiresAt
1100 ) {
1101 symlinkScanStale = true;
1103 const pending =
1104 pendingSymlinkScan ??
1105 (lastSymlinkScan === undefined || symlinkScanStale ? yield* startSymlinkScan() : undefined);
1106 let result = lastSymlinkScan;
1107 if (pending && result === undefined) {
1108 result = yield* Deferred.await(pending);
1109 } else if (pending) {
1110 const fresh = yield* Deferred.await(pending).pipe(Effect.timeoutOption(SYMLINK_RESCAN_WAIT));
1111 if (Option.isSome(fresh)) result = fresh.value;
1113 if (result === undefined)
1114 return yield* Effect.die("The symlink scan finished without a result.");
1115 return {
1116 // Git's ignore rules hide a link the same way searchVisible hides the files it indexes.
1117 entries: result.entries.filter(
1118 (entry) => !isIgnoredPath(ignoredPaths, entry.path, hostIsWindows),
1119 ),
1120 linkPaths: result.linkPaths,
1121 };
1122 });
1123​
1124 // Grows the first page until hidden entries can no longer crowd visible ones out of it.
1125 const searchVisible = Effect.fn("WorkspaceSearchIndex.searchVisible")(function* <I, Metadata>(
1126 query: string,
1127 pageSize: number,
1128 operation: "directorySearch" | "fileSearch" | "mixedSearch",
1129 execute: (pageSize: number) => Promise<Result<SearchPage<I> & Metadata>>,
1130 pathOf: (item: I) => string,
1131 ): Effect.fn.Return<SearchPage<I> & Metadata, WorkspaceSearchIndexSearchFailed> {
1132 let size = pageSize;
1133 while (true) {
1134 const fetchSize = size;
1135 const result = yield* runSearch(query, fetchSize, operation, () => execute(fetchSize));
1136 if (ignoredPaths.size === 0) return result;
1137 const items = result.items.filter(
1138 (item) => !isIgnoredPath(ignoredPaths, pathOf(item), hostIsWindows),
1139 );
1140 if (
1141 items.length >= pageSize ||
1142 result.items.length >= result.totalMatched ||
1143 fetchSize >= WORKSPACE_INDEX_PAGE_SIZE
1144 ) {
1145 return {
1146 ...result,
1147 items,
1148 totalMatched: result.totalMatched - (result.items.length - items.length),
1149 };
1151 size = Math.min(WORKSPACE_INDEX_PAGE_SIZE, fetchSize * 4);
1153 });
1154​
1155 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
1156 "WorkspaceSearchIndex.refresh",
1157 )(function* () {
1158 // scanFiles waits on fff's picker lock, which its watcher can hold for seconds.
1159 const result = yield* Effect.tryPromise({
1160 try: () => finder.scanFilesAsync(),
1161 catch: (cause) =>
1162 new WorkspaceSearchIndexRefreshFailed({
1163 cwd,
1164 reason: "FileFinder.scanFilesAsync rejected unexpectedly.",
1165 cause,
1166 }),
1167 });
1168 if (!result.ok) {
1169 return yield* new WorkspaceSearchIndexRefreshFailed({
1170 cwd,
1171 reason: result.error,
1172 });
1174 // A rescan that outlasts the wait keeps running, and the finder answers
1175 // from its previous index until it finishes, so the index stays usable.
1176 yield* waitForIndexReady(
1177 cwd,
1178 finder,
1179 ({ reason, cause }) =>
1180 new WorkspaceSearchIndexRefreshFailed({
1181 cwd,
1182 reason,
1183 cause,
1184 }),
1185 ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void }));
1186 ignoredPaths = yield* loadIgnoredPaths();
1187 invalidateSymlinkScan();
1188 });
1189​
1190 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
1191 function* () {
1192 const incompleteBeforeQuery = yield* hasIncompleteInitialScan();
1193 const result = yield* searchVisible(
1194 "",
1195 WORKSPACE_INDEX_PAGE_SIZE,
1196 "mixedSearch",
1197 (pageSize) => finder.mixedSearchAsync("", { pageSize }),
1198 mixedItemPath,
1199 );
1200 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES, hostIsWindows);
1201 const symlinks = yield* listSymlinkEntries();
1202 // fff's watcher can index a link the scan rejected; only accepted links are listed.
1203 const indexed = mapped.entries.filter((entry) => !symlinks.linkPaths.has(entry.path));
1204 const sortedEntries = withDirectoryAncestors([...indexed, ...symlinks.entries]).toSorted(
1205 (left, right) => left.path.localeCompare(right.path),
1206 );
1207 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
1208 return {
1209 entries,
1210 truncated:
1211 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
1212 };
1213 },
1214 );
1215​
1216 const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* (
1217 query: string,
1218 limit: number,
1219 kind: ProjectEntryKind | undefined,
1220 imageOnly: boolean | undefined,
1221 ) {
1222 const { entries: allSymlinks, linkPaths } = yield* listSymlinkEntries();
1223 const symlinks = allSymlinks.filter((entry) =>
1224 imageOnly
1225 ? entry.kind === "file" && isProjectFaviconPath(entry.path)
1226 : kind === undefined || entry.kind === kind,
1227 );
1228 // Index results that are filtered-out links get dropped in the merge, so fetch past them.
1229 const indexLimit = limit + linkPaths.size - symlinks.length;
1230 const pageSize = Math.max(1, indexLimit + 1);
1231 const merge = (indexed: ProjectSearchEntriesResult) =>
1232 mergeSymlinkMatches(indexed, linkPaths, symlinks, query, limit);
1233 if (kind === "file" || imageOnly) {
1234 const searchFiles = (fileQuery: string, size: number) =>
1235 searchVisible(
1236 query,
1237 size,
1238 "fileSearch",
1239 (fetchSize) => finder.fileSearchAsync(fileQuery, { pageSize: fetchSize }),
1240 (item: FileItem) => item.relativePath,
1241 );
1242 // Adding a constraint changes fff's lone-path parse; offset pages can skip tied matches.
1243 if (imageOnly && isLoneFuzzyPath(query)) {
1244 const result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE);
1245 return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, true));
1247 let result = yield* searchFiles(
1248 imageOnly ? `${query} ${IMAGE_SEARCH_CONSTRAINT}` : query,
1249 pageSize,
1250 );
1251 if (
1252 imageOnly &&
1253 query.trim() &&
1254 result.totalFiles > FFF_FILENAME_FALLBACK_MAX_MATCHES &&
1255 result.totalMatched > 0
1256 ) {
1257 const unfiltered = yield* runSearch(query, 1, "fileSearch", () =>
1258 finder.fileSearchAsync(query, { pageSize: 1 }),
1259 );
1260 if (unfiltered.totalMatched > FFF_FILENAME_FALLBACK_MAX_MATCHES) {
1261 result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE);
1264 return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, imageOnly));
1266 if (kind === "directory") {
1267 const result = yield* searchVisible(
1268 query,
1269 pageSize,
1270 "directorySearch",
1271 (size) => finder.directorySearchAsync(query, { pageSize: size }),
1272 (item) => item.relativePath,
1273 );
1274 return merge(mapDirectorySearchResult(result, indexLimit, hostIsWindows));
1276 const result = yield* searchVisible(
1277 query,
1278 pageSize,
1279 "mixedSearch",
1280 (size) => finder.mixedSearchAsync(query, { pageSize: size }),
1281 mixedItemPath,
1282 );
1283 return merge(mapMixedSearchResult(result, indexLimit, hostIsWindows));
1284 });
1285​
1286 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
1287 "WorkspaceSearchIndex.search",
1288 )(function* (rawQuery, limit, kind, imageOnly) {
1289 // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy
1290 // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths.
1291 // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working.
1292 const query = rawQuery.replaceAll("[", "");
1293 const incompleteBeforeQuery = yield* hasIncompleteInitialScan();
1294 let mapped = yield* searchNames(query, limit, kind, imageOnly);
1295 if (mapped.entries.length === 0 && query.includes("{")) {
1296 mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly);
1298 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
1299 });
1300​
1301 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
1302 "WorkspaceSearchIndex.searchContents",
1303 )(function* (input) {
1304 if (!(yield* isContentIndexReady())) {
1305 const gitResult = yield* searchContentsWithGit(input);
1306 if (Option.isSome(gitResult)) return gitResult.value;
1307 yield* waitForIndexReady(
1308 cwd,
1309 finder,
1310 ({ reason, cause }) =>
1311 new WorkspaceSearchIndexSearchFailed({
1312 cwd,
1313 queryLength: input.query.length,
1314 pageSize: input.limit,
1315 reason,
1316 cause,
1317 }),
1318 );
1319 contentIndexPending = false;
1321 let { searchQuery, regexMode } = buildContentSearchQuery(input);
1322 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
1323 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
1324 const rawPageSize = input.wholeWord
1325 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
1326 : input.limit;
1327 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
1328 let nextCursor: GrepCursor | null = null;
1329 let regexFallbackError: string | undefined;
1330 let retryLiterally = false;
1331​
1332 do {
1333 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
1334 const result = yield* runSearch(input.query, input.limit, "grep", () =>
1335 finder.grepAsync(searchQuery, {
1336 mode: regexMode ? "regex" : "plain",
1337 smartCase: !input.caseSensitive && !regexMode,
1338 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
1339 pageSize: rawPageSize,
1340 cursor: nextCursor,
1341 timeBudgetMs: remainingTimeBudgetMs,
1342 }),
1343 );
1344 // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix.
1345 retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined;
1346 if (retryLiterally) {
1347 regexFallbackError = result.regexFallbackError;
1348 ({ searchQuery, regexMode } = buildContentSearchQuery({ ...input, useRegex: false }));
1349 continue;
1351​
1352 for (const match of result.items) {
1353 if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue;
1354 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
1355 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
1356 );
1357 // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.
1358 if (input.wholeWord && matchRanges.length === 0) continue;
1359 matches.push({
1360 path: toPosixPath(match.relativePath, hostIsWindows),
1361 lineNumber: match.lineNumber,
1362 lineContent: match.lineContent,
1363 matchRanges,
1364 });
1366 nextCursor = result.nextCursor;
1367 regexFallbackError ??= result.regexFallbackError;
1368 } while (
1369 retryLiterally ||
1370 (matches.length < input.limit && nextCursor !== null && performance.now() < deadline)
1371 );
1372​
1373 return {
1374 matches: matches.slice(0, input.limit),
1375 truncated: matches.length > input.limit || nextCursor !== null,
1376 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
1377 };
1378 });
1379​
1380 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
1381});
1382​
1383export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
1384export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
1385​
1386export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
1387 `${variant}\n${cwd}`;
1388​
1389function parseWorkspaceSearchIndexKey(key: string): {
1390 readonly cwd: string;
1391 readonly variant: WorkspaceSearchIndexVariant;
1392} {
1393 const separatorIndex = key.indexOf("\n");
1394 return {
1395 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
1396 cwd: key.slice(separatorIndex + 1),
1397 };
1399​
1400/** @public */
1401export const layer = (key: string) => {
1402 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
1403 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
1405​
1406export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
1407 "t3/workspace/WorkspaceSearchIndexMap",
1409 lookup: layer,
1410 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
1411 },
1412) {}