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

WorkspaceSearchIndex.ts

1,388 lines51.5 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;
57const 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 new Set<string>();
530 return new Set(
531 result.stdout
532 .split("\0")
533 .filter((entry) => entry.length > 0)
534 .map((entry) => trimDirectorySeparator(toPosixPath(entry, hostIsWindows))),
535 );
536});
537​
538function mixedItemPath(item: MixedItem): string {
539 return item.item.relativePath;
541​
542function isIgnoredPath(
543 ignoredPaths: ReadonlySet<string>,
544 relativePath: string,
545 hostIsWindows: boolean,
546): boolean {
547 if (ignoredPaths.size === 0) return false;
548 let candidate: string | undefined = trimDirectorySeparator(
549 toPosixPath(relativePath, hostIsWindows),
550 );
551 while (candidate) {
552 if (ignoredPaths.has(candidate)) return true;
553 candidate = parentPathOf(candidate);
554 }
555 return false;
557​
558const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
559 cwd: string,
560 variant: WorkspaceSearchIndexVariant,
561) {
562 const result = yield* Effect.try({
563 try: () =>
564 FileFinder.create({
565 basePath: cwd,
566 disableMmapCache: true,
567 // Content indexing costs CPU/memory; path-only consumers use the lightweight index.
568 disableContentIndexing: variant !== "content",
569 aiMode: false,
570 }),
571 catch: (cause) =>
572 new WorkspaceSearchIndexCreateFailed({
573 cwd,
574 reason: "FileFinder.create threw unexpectedly.",
575 cause,
576 }),
577 });
578 if (result.ok) return result.value;
579 return yield* new WorkspaceSearchIndexCreateFailed({
580 cwd,
581 reason: result.error,
582 });
583});
584​
585const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
586 cwd: string,
587 finder: FileFinderType,
588 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
589): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
590 const result = yield* Effect.tryPromise({
591 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
592 catch: (cause) =>
593 onFailure({
594 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
595 cause,
596 }),
597 });
598 if (!result.ok) {
599 return yield* Effect.fail(onFailure({ reason: result.error }));
600 }
601 if (!result.value) {
602 return yield* new WorkspaceSearchIndexScanTimedOut({
603 cwd,
604 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
605 });
606 }
607});
608​
609export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
610 cwd: string,
611 variant: WorkspaceSearchIndexVariant = "paths",
612) {
613 const hostIsWindows = yield* HostProcess.isWindows;
614 const fileSystem = yield* FileSystem.FileSystem;
615 const path = yield* Path.Path;
616 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
617 Effect.try({
618 try: () => finder.destroy(),
619 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
620 }).pipe(Effect.orDie),
621 );
622 let initialScanTimedOut = false;
623 // The content index reads every file, which takes minutes where antivirus scans each open,
624 // so content searches do not wait for it; git grep answers until it is ready.
625 let contentIndexPending = variant === "content";
626 const vcsProcess = yield* VcsProcess.VcsProcess;
627 let ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows);
628 if (variant === "paths") {
629 yield* waitForIndexReady(
630 cwd,
631 finder,
632 ({ reason, cause }) =>
633 new WorkspaceSearchIndexCreateFailed({
634 cwd,
635 reason,
636 cause,
637 }),
638 ).pipe(
639 Effect.catchTags({
640 WorkspaceSearchIndexScanTimedOut: () =>
641 Effect.sync(() => {
642 initialScanTimedOut = true;
643 }),
644 }),
645 );
646 }
647​
648 // fff's isScanning takes the picker lock too, so progress is read off the JS thread.
649 const isScanning = Effect.promise(async () => {
650 try {
651 const progress = await finder.getScanProgressAsync();
652 return !progress.ok || progress.value.isScanning;
653 } catch {
654 return true;
655 }
656 });
657 const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false));
658​
659 const isContentIndexReady = Effect.fn("WorkspaceSearchIndex.isContentIndexReady")(function* () {
660 if (!contentIndexPending) return true;
661 const progress = yield* Effect.promise(() =>
662 finder.getScanProgressAsync().catch(() => undefined),
663 );
664 if (progress?.ok && !progress.value.isScanning && progress.value.isWarmupComplete) {
665 contentIndexPending = false;
666 }
667 return !contentIndexPending;
668 });
669​
670 const runGitGrep = Effect.fn("WorkspaceSearchIndex.runGitGrep")(function* (
671 pattern: string,
672 options: {
673 readonly regexMode: boolean;
674 readonly ignoreCase: boolean;
675 readonly maxMatchesPerFile: number;
676 readonly onlyMatching: boolean;
677 },
678 ) {
679 return yield* vcsProcess
680 .run({
681 operation: "WorkspaceSearchIndex.gitGrep",
682 command: "git",
683 args: [
684 "-c",
685 "core.quotePath=false",
686 "-c",
687 "core.fsmonitor=false",
688 "grep",
689 "--untracked",
690 "--no-color",
691 "-I",
692 "-n",
693 "-z",
694 "-m",
695 String(options.maxMatchesPerFile),
696 ...(options.onlyMatching ? ["-o", "--column"] : []),
697 ...(options.ignoreCase ? ["-i"] : []),
698 options.regexMode ? "-P" : "-F",
699 "-e",
700 pattern,
701 ],
702 cwd,
703 allowNonZeroExit: true,
704 // Defender scanning fff's warmup reads slows git too; a late answer beats a failure.
705 timeoutMs: 30_000,
706 maxOutputBytes: GIT_GREP_MAX_OUTPUT_BYTES,
707 outputMode: "truncate",
708 appendTruncationMarker: false,
709 })
710 .pipe(Effect.option);
711 });
712​
713 // fff leaves out what `.ignore` files exclude, which git cannot evaluate; the nearest
714 // `.ignore` that matches a path or one of its folders decides, as in decideByIgnoreFiles.
715 const makeIgnoreFileFilter = () => {
716 const ignoreFiles = new Map<string, IgnoreFile | undefined>();
717 const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* (
718 directory: string,
719 ) {
720 if (ignoreFiles.has(directory)) return ignoreFiles.get(directory);
721 const contents = yield* fileSystem
722 .readFileString(path.join(cwd, directory, ".ignore"))
723 .pipe(Effect.option);
724 const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined;
725 ignoreFiles.set(directory, file);
726 return file;
727 });
728 return Effect.fn("WorkspaceSearchIndex.isExcludedByIgnoreFiles")(function* (
729 relativePath: string,
730 ) {
731 const segments = relativePath.split("/");
732 for (let depth = 1; depth <= segments.length; depth += 1) {
733 const candidate = segments.slice(0, depth).join("/");
734 for (let ancestor = depth - 1; ancestor >= 0; ancestor -= 1) {
735 const directory = segments.slice(0, ancestor).join("/");
736 const file = yield* readIgnoreFile(directory);
737 const relative = directory ? candidate.slice(directory.length + 1) : candidate;
738 const decision = file?.decide(relative, depth < segments.length);
739 if (decision === "ignored") return true;
740 if (decision === "included") break;
741 }
742 }
743 return false;
744 });
745 };
746​
747 // fff's grep before its content index is ready opens every file itself, as slowly as the build.
748 // None when git cannot search this folder (not a repository, git missing, no PCRE for a regex).
749 const searchContentsWithGit = Effect.fn("WorkspaceSearchIndex.searchContentsWithGit")(function* (
750 input: Omit<ProjectSearchContentsInput, "cwd">,
751 ): Effect.fn.Return<Option.Option<ProjectSearchContentsResult>> {
752 const options = {
753 ignoreCase: !input.caseSensitive,
754 maxMatchesPerFile: CONTENT_SEARCH_MAX_MATCHES_PER_FILE,
755 onlyMatching: false,
756 };
757 let regexMode = input.useRegex;
758 let regexFallbackError: string | undefined;
759 let result = yield* runGitGrep(input.query, { ...options, regexMode });
760 if (regexMode && Option.isSome(result) && result.value.exitCode === 128) {
761 if (/USE_LIBPCRE|Perl-compatible/i.test(result.value.stderr)) return Option.none();
762 // fff searches an invalid pattern as a literal and reports why.
763 regexFallbackError = result.value.stderr.trim().split("\n")[0] || "Invalid regex";
764 regexMode = false;
765 result = yield* runGitGrep(input.query, { ...options, regexMode });
766 }
767 if (Option.isNone(result) || result.value.exitCode > 1) return Option.none();
768​
769 // Per line: the first match's byte column and every match's text, in order.
770 const regexMatches = new Map<string, { readonly column: number; readonly texts: string[] }>();
771 let rangesTruncated = false;
772 if (regexMode) {
773 // Ranges come from git too: running the user's pattern in JS could backtrack without bound.
774 const ranges = yield* runGitGrep(input.query, { ...options, regexMode, onlyMatching: true });
775 // Without ranges, whole-word filtering would drop every hit and report no matches.
776 if (Option.isNone(ranges) || ranges.value.exitCode > 1) return Option.none();
777 rangesTruncated = ranges.value.stdoutTruncated;
778 if (ranges.value.exitCode === 0) {
779 for (const record of parseGitGrepRecords(
780 ranges.value.stdout,
781 4,
782 ranges.value.stdoutTruncated,
783 )) {
784 const [relativePath, lineNumber, column, text] = record as [
785 string,
786 string,
787 string,
788 string,
789 ];
790 const key = `${relativePath}\0${lineNumber}`;
791 const lineMatches = regexMatches.get(key);
792 if (lineMatches) lineMatches.texts.push(text);
793 else regexMatches.set(key, { column: Number(column), texts: [text] });
794 }
795 }
796 }
797 const literal = regexMode
798 ? undefined
799 : new RegExp(escapeRegExp(input.query), input.caseSensitive ? "gu" : "giu");
800​
801 const isExcludedByIgnoreFiles = makeIgnoreFileFilter();
802 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
803 let rangesCutOff = false;
804 for (const record of parseGitGrepRecords(
805 result.value.stdout,
806 3,
807 result.value.stdoutTruncated,
808 )) {
809 const [relativePath, lineNumber, rawLine] = record as [string, string, string];
810 if (yield* isExcludedByIgnoreFiles(relativePath)) continue;
811 const key = `${relativePath}\0${lineNumber}`;
812 // Lines past the cut-off of a truncated ranges run have no ranges; stop there instead.
813 if (rangesTruncated && !regexMatches.has(key)) {
814 rangesCutOff = true;
815 break;
816 }
817 const lineContent = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).slice(
818 0,
819 CONTENT_LINE_MAX_LENGTH,
820 );
821 const matchRanges = (
822 literal
823 ? Array.from(lineContent.matchAll(literal), (match) => ({
824 start: match.index,
825 end: match.index + match[0].length,
826 }))
827 : mapContentMatchRanges(
828 lineContent,
829 locateRegexMatches(lineContent, regexMatches.get(key)),
830 )
831 ).filter(
832 (range) =>
833 range.end <= lineContent.length &&
834 (!input.wholeWord || isWholeWordRange(lineContent, range)),
835 );
836 if (input.wholeWord && matchRanges.length === 0) continue;
837 matches.push({
838 path: relativePath,
839 lineNumber: Number(lineNumber),
840 lineContent,
841 matchRanges,
842 });
843 if (matches.length > input.limit) break;
844 }
845 return Option.some({
846 matches: matches.slice(0, input.limit),
847 truncated: matches.length > input.limit || result.value.stdoutTruncated || rangesCutOff,
848 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
849 });
850 });
851​
852 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
853 query: string,
854 pageSize: number,
855 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
856 execute: () => Promise<Result<A>>,
857 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
858 // fff's searches wait on its picker lock, which its watcher can hold for minutes.
859 const result = yield* Effect.tryPromise({
860 try: execute,
861 catch: (cause) =>
862 new WorkspaceSearchIndexSearchFailed({
863 cwd,
864 queryLength: query.length,
865 pageSize,
866 reason: `FileFinder.${operation} rejected unexpectedly.`,
867 cause,
868 }),
869 });
870 if (!result.ok) {
871 return yield* new WorkspaceSearchIndexSearchFailed({
872 cwd,
873 queryLength: query.length,
874 pageSize,
875 reason: result.error,
876 });
877 }
878 return result.value;
879 });
880​
881 const root = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
882​
883 const listIndexedDirectories = Effect.fn("WorkspaceSearchIndex.listIndexedDirectories")(
884 function* () {
885 const directories: string[] = [];
886 // fff's pageIndex is an offset into the results, not a page number.
887 for (let pageIndex = 0; ; pageIndex += SYMLINK_DIRECTORY_PAGE_SIZE) {
888 const result = yield* Effect.promise(async () => {
889 try {
890 return await finder.directorySearchAsync("", {
891 pageIndex,
892 pageSize: SYMLINK_DIRECTORY_PAGE_SIZE,
893 });
894 } catch {
895 return undefined;
896 }
897 });
898 if (!result?.ok) return directories;
899 for (const item of result.value.items) {
900 const directory = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows));
901 if (directory) directories.push(directory);
902 }
903 if (result.value.items.length < SYMLINK_DIRECTORY_PAGE_SIZE) return directories;
904 }
905 },
906 );
907​
908 /** Ignore rules belong to the repository that owns a path, so each one answers for its own. */
909 const listGitIgnored = Effect.fn("WorkspaceSearchIndex.listGitIgnored")(function* (
910 repository: string,
911 entries: ReadonlyArray<ProjectEntry>,
912 ) {
913 const relativePaths = entries.map((entry) =>
914 repository ? entry.path.slice(repository.length + 1) : entry.path,
915 );
916 const repositoryCwd = path.join(cwd, repository);
917 const result = yield* vcsProcess
918 .run({
919 operation: "WorkspaceSearchIndex.listGitIgnored",
920 command: "git",
921 // fff applies ignore rules to tracked paths too, so the index is not consulted.
922 args: ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "-z", "--stdin"],
923 cwd: repositoryCwd,
924 stdin: `${relativePaths.join("\0")}\0`,
925 allowNonZeroExit: true,
926 timeoutMs: 10_000,
927 maxOutputBytes: 16 * 1024 * 1024,
928 })
929 .pipe(Effect.orElseSucceed(() => undefined));
930 // Exit 1 means nothing matched.
931 if (result?.exitCode === 1) return [];
932 if (result?.exitCode !== 0 || result.stdoutTruncated) {
933 // Outside git no rules apply (git exits before reading stdin, so the cause is lost).
934 // Any other failure hides the repository's links rather than leaking ones it ignores.
935 const insideRepository = yield* vcsProcess
936 .run({
937 operation: "WorkspaceSearchIndex.listGitIgnored",
938 command: "git",
939 args: ["rev-parse", "--git-dir"],
940 cwd: repositoryCwd,
941 timeoutMs: 10_000,
942 })
943 .pipe(
944 Effect.as(true),
945 Effect.orElseSucceed(() => false),
946 );
947 return insideRepository ? entries.map((entry) => entry.path) : [];
948 }
949 return result.stdout
950 .split("\0")
951 .filter(Boolean)
952 .map((relativePath) => (repository ? `${repository}/${relativePath}` : relativePath));
953 });
954​
955 const scanSymlinkEntries = Effect.fn("WorkspaceSearchIndex.scanSymlinkEntries")(function* () {
956 const indexComplete = !(yield* isScanning);
957 const directories = yield* listIndexedDirectories();
958 const scanned = yield* Effect.forEach(
959 ["", ...directories],
960 (directory) => scanDirectory(fileSystem, path, cwd, root, directory),
961 { concurrency: SYMLINK_SCAN_CONCURRENCY },
962 );
963 const candidates = scanned.flatMap((directory) => directory.links);
964 const linkPaths = new Set(scanned.flatMap((directory) => directory.linkPaths));
965 if (candidates.length === 0) return { entries: candidates, linkPaths, indexComplete };
966​
967 const ignoreFiles = scanned
968 .flatMap(({ directory, ignoreFile }) =>
969 ignoreFile === undefined ? [] : [{ directory, file: parseIgnoreFile(ignoreFile) }],
970 )
971 .toSorted((left, right) => right.directory.length - left.directory.length);
972 const decisions = new Map(
973 candidates.map((entry) => [entry.path, decideByIgnoreFiles(entry, ignoreFiles)]),
974 );
975 const repositories = [
976 "",
977 ...scanned.flatMap(({ directory, isRepository }) =>
978 isRepository && directory ? [directory] : [],
979 ),
980 ].toSorted((left, right) => right.length - left.length);
981 const entriesByRepository = Map.groupBy(
982 candidates.filter((entry) => decisions.get(entry.path) === undefined),
983 (entry) =>
984 repositories.find(
985 (repository) => isWithin(entry.path, repository) && entry.path !== repository,
986 ) ?? "",
987 );
988 const ignored = new Set(
989 (yield* Effect.forEach(
990 entriesByRepository,
991 ([repository, entries]) => listGitIgnored(repository, entries),
992 { concurrency: 4 },
993 )).flat(),
994 );
995 return {
996 entries: candidates.filter((entry) =>
997 decisions.get(entry.path) === undefined
998 ? !ignored.has(entry.path)
999 : decisions.get(entry.path) === "included",
1000 ),
1001 linkPaths,
1002 indexComplete,
1003 };
1004 });
1005​
1006 // One scan runs at a time and outlives the reads that started it. Only the first read waits for
1007 // it in full: after that a change or expiry marks the result stale, and reads wait briefly for
1008 // the rescan before answering from the last finished one, so file churn cannot stall search.
1009 type SymlinkScan = Effect.Success<ReturnType<typeof scanSymlinkEntries>>;
1010 let lastSymlinkScan: SymlinkScan | undefined;
1011 let lastSymlinkScanExpiresAt: number | undefined;
1012 let pendingSymlinkScan: Deferred.Deferred<SymlinkScan> | undefined;
1013 let symlinkScanStale = false;
1014 let knownLinkPaths: ReadonlySet<string> = new Set();
1015 const invalidateSymlinkScan = () => {
1016 symlinkScanStale = true;
1017 };
1018 const isKnownLink = (absolutePath: string) =>
1019 [cwd, root].some((base) =>
1020 knownLinkPaths.has(toPosixPath(path.relative(base, absolutePath), hostIsWindows)),
1021 );
1022 const onWatchBatch = (events: ReadonlyArray<WatchEvent>) => {
1023 // fff reports a link replaced in place as `modified`, so edits to known links count too.
1024 const editsOnly = events.every(
1025 (event) =>
1026 event.kind === "modified" &&
1027 !/(^|[\\/])\.(git)?ignore$/.test(event.path) &&
1028 !isKnownLink(event.path),
1029 );
1030 if (!editsOnly) invalidateSymlinkScan();
1031 };
1032 // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so
1033 // each read retries until one is in place. Subscribing waits on fff's picker lock, which its
1034 // watcher holds while it indexes a new folder, so it runs off the JS thread.
1035 let unwatch: WatchUnsubscribe | undefined;
1036 yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.()));
1037 const ensureWatching = Effect.fn("WorkspaceSearchIndex.ensureWatching")(function* () {
1038 if (unwatch) return true;
1039 const result = yield* Effect.promise(() =>
1040 finder.watchAsync(onWatchBatch).catch(() => undefined),
1041 );
1042 if (result?.ok) unwatch = result.value;
1043 return unwatch !== undefined;
1044 });
1045 const indexScope = yield* Effect.scope;
1046 const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () {
1047 symlinkScanStale = false;
1048 const done = yield* Deferred.make<SymlinkScan>();
1049 pendingSymlinkScan = done;
1050 yield* Effect.gen(function* () {
1051 // Subscribing before the scan starts means no change during it goes unseen.
1052 const watched = yield* ensureWatching();
1053 const result = yield* scanSymlinkEntries();
1054 lastSymlinkScan = result;
1055 knownLinkPaths = result.linkPaths;
1056 // Without a watcher, or before fff has seen every folder, the result is kept only briefly.
1057 lastSymlinkScanExpiresAt =
1058 watched && result.indexComplete
1059 ? undefined
1060 : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS;
1061 return result;
1062 }).pipe(
1063 Effect.onExit((exit) =>
1064 Effect.sync(() => {
1065 pendingSymlinkScan = undefined;
1066 }).pipe(Effect.andThen(Deferred.done(done, exit))),
1067 ),
1068 Effect.forkIn(indexScope),
1069 );
1070 return done;
1071 });
1072 const listSymlinkEntries = Effect.fn("WorkspaceSearchIndex.listSymlinkEntries")(function* () {
1073 if (
1074 lastSymlinkScanExpiresAt !== undefined &&
1075 (yield* Clock.currentTimeMillis) >= lastSymlinkScanExpiresAt
1076 ) {
1077 symlinkScanStale = true;
1079 const pending =
1080 pendingSymlinkScan ??
1081 (lastSymlinkScan === undefined || symlinkScanStale ? yield* startSymlinkScan() : undefined);
1082 let result = lastSymlinkScan;
1083 if (pending && result === undefined) {
1084 result = yield* Deferred.await(pending);
1085 } else if (pending) {
1086 const fresh = yield* Deferred.await(pending).pipe(Effect.timeoutOption(SYMLINK_RESCAN_WAIT));
1087 if (Option.isSome(fresh)) result = fresh.value;
1089 if (result === undefined)
1090 return yield* Effect.die("The symlink scan finished without a result.");
1091 return {
1092 // Git's ignore rules hide a link the same way searchVisible hides the files it indexes.
1093 entries: result.entries.filter(
1094 (entry) => !isIgnoredPath(ignoredPaths, entry.path, hostIsWindows),
1095 ),
1096 linkPaths: result.linkPaths,
1097 };
1098 });
1099​
1100 // Grows the first page until hidden entries can no longer crowd visible ones out of it.
1101 const searchVisible = Effect.fn("WorkspaceSearchIndex.searchVisible")(function* <I, Metadata>(
1102 query: string,
1103 pageSize: number,
1104 operation: "directorySearch" | "fileSearch" | "mixedSearch",
1105 execute: (pageSize: number) => Promise<Result<SearchPage<I> & Metadata>>,
1106 pathOf: (item: I) => string,
1107 ): Effect.fn.Return<SearchPage<I> & Metadata, WorkspaceSearchIndexSearchFailed> {
1108 let size = pageSize;
1109 while (true) {
1110 const fetchSize = size;
1111 const result = yield* runSearch(query, fetchSize, operation, () => execute(fetchSize));
1112 if (ignoredPaths.size === 0) return result;
1113 const items = result.items.filter(
1114 (item) => !isIgnoredPath(ignoredPaths, pathOf(item), hostIsWindows),
1115 );
1116 if (
1117 items.length >= pageSize ||
1118 result.items.length >= result.totalMatched ||
1119 fetchSize >= WORKSPACE_INDEX_PAGE_SIZE
1120 ) {
1121 return {
1122 ...result,
1123 items,
1124 totalMatched: result.totalMatched - (result.items.length - items.length),
1125 };
1127 size = Math.min(WORKSPACE_INDEX_PAGE_SIZE, fetchSize * 4);
1129 });
1130​
1131 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
1132 "WorkspaceSearchIndex.refresh",
1133 )(function* () {
1134 // scanFiles waits on fff's picker lock, which its watcher can hold for seconds.
1135 const result = yield* Effect.tryPromise({
1136 try: () => finder.scanFilesAsync(),
1137 catch: (cause) =>
1138 new WorkspaceSearchIndexRefreshFailed({
1139 cwd,
1140 reason: "FileFinder.scanFilesAsync rejected unexpectedly.",
1141 cause,
1142 }),
1143 });
1144 if (!result.ok) {
1145 return yield* new WorkspaceSearchIndexRefreshFailed({
1146 cwd,
1147 reason: result.error,
1148 });
1150 // A rescan that outlasts the wait keeps running, and the finder answers
1151 // from its previous index until it finishes, so the index stays usable.
1152 yield* waitForIndexReady(
1153 cwd,
1154 finder,
1155 ({ reason, cause }) =>
1156 new WorkspaceSearchIndexRefreshFailed({
1157 cwd,
1158 reason,
1159 cause,
1160 }),
1161 ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void }));
1162 ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows);
1163 invalidateSymlinkScan();
1164 });
1165​
1166 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
1167 function* () {
1168 const incompleteBeforeQuery = yield* hasIncompleteInitialScan();
1169 const result = yield* searchVisible(
1170 "",
1171 WORKSPACE_INDEX_PAGE_SIZE,
1172 "mixedSearch",
1173 (pageSize) => finder.mixedSearchAsync("", { pageSize }),
1174 mixedItemPath,
1175 );
1176 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES, hostIsWindows);
1177 const symlinks = yield* listSymlinkEntries();
1178 // fff's watcher can index a link the scan rejected; only accepted links are listed.
1179 const indexed = mapped.entries.filter((entry) => !symlinks.linkPaths.has(entry.path));
1180 const sortedEntries = withDirectoryAncestors([...indexed, ...symlinks.entries]).toSorted(
1181 (left, right) => left.path.localeCompare(right.path),
1182 );
1183 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
1184 return {
1185 entries,
1186 truncated:
1187 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
1188 };
1189 },
1190 );
1191​
1192 const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* (
1193 query: string,
1194 limit: number,
1195 kind: ProjectEntryKind | undefined,
1196 imageOnly: boolean | undefined,
1197 ) {
1198 const { entries: allSymlinks, linkPaths } = yield* listSymlinkEntries();
1199 const symlinks = allSymlinks.filter((entry) =>
1200 imageOnly
1201 ? entry.kind === "file" && isProjectFaviconPath(entry.path)
1202 : kind === undefined || entry.kind === kind,
1203 );
1204 // Index results that are filtered-out links get dropped in the merge, so fetch past them.
1205 const indexLimit = limit + linkPaths.size - symlinks.length;
1206 const pageSize = Math.max(1, indexLimit + 1);
1207 const merge = (indexed: ProjectSearchEntriesResult) =>
1208 mergeSymlinkMatches(indexed, linkPaths, symlinks, query, limit);
1209 if (kind === "file" || imageOnly) {
1210 const searchFiles = (fileQuery: string, size: number) =>
1211 searchVisible(
1212 query,
1213 size,
1214 "fileSearch",
1215 (fetchSize) => finder.fileSearchAsync(fileQuery, { pageSize: fetchSize }),
1216 (item: FileItem) => item.relativePath,
1217 );
1218 // Adding a constraint changes fff's lone-path parse; offset pages can skip tied matches.
1219 if (imageOnly && isLoneFuzzyPath(query)) {
1220 const result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE);
1221 return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, true));
1223 let result = yield* searchFiles(
1224 imageOnly ? `${query} ${IMAGE_SEARCH_CONSTRAINT}` : query,
1225 pageSize,
1226 );
1227 if (
1228 imageOnly &&
1229 query.trim() &&
1230 result.totalFiles > FFF_FILENAME_FALLBACK_MAX_MATCHES &&
1231 result.totalMatched > 0
1232 ) {
1233 const unfiltered = yield* runSearch(query, 1, "fileSearch", () =>
1234 finder.fileSearchAsync(query, { pageSize: 1 }),
1235 );
1236 if (unfiltered.totalMatched > FFF_FILENAME_FALLBACK_MAX_MATCHES) {
1237 result = yield* searchFiles(query, WORKSPACE_INDEX_PAGE_SIZE);
1240 return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, imageOnly));
1242 if (kind === "directory") {
1243 const result = yield* searchVisible(
1244 query,
1245 pageSize,
1246 "directorySearch",
1247 (size) => finder.directorySearchAsync(query, { pageSize: size }),
1248 (item) => item.relativePath,
1249 );
1250 return merge(mapDirectorySearchResult(result, indexLimit, hostIsWindows));
1252 const result = yield* searchVisible(
1253 query,
1254 pageSize,
1255 "mixedSearch",
1256 (size) => finder.mixedSearchAsync(query, { pageSize: size }),
1257 mixedItemPath,
1258 );
1259 return merge(mapMixedSearchResult(result, indexLimit, hostIsWindows));
1260 });
1261​
1262 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
1263 "WorkspaceSearchIndex.search",
1264 )(function* (rawQuery, limit, kind, imageOnly) {
1265 // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy
1266 // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths.
1267 // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working.
1268 const query = rawQuery.replaceAll("[", "");
1269 const incompleteBeforeQuery = yield* hasIncompleteInitialScan();
1270 let mapped = yield* searchNames(query, limit, kind, imageOnly);
1271 if (mapped.entries.length === 0 && query.includes("{")) {
1272 mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly);
1274 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
1275 });
1276​
1277 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
1278 "WorkspaceSearchIndex.searchContents",
1279 )(function* (input) {
1280 if (!(yield* isContentIndexReady())) {
1281 const gitResult = yield* searchContentsWithGit(input);
1282 if (Option.isSome(gitResult)) return gitResult.value;
1283 yield* waitForIndexReady(
1284 cwd,
1285 finder,
1286 ({ reason, cause }) =>
1287 new WorkspaceSearchIndexSearchFailed({
1288 cwd,
1289 queryLength: input.query.length,
1290 pageSize: input.limit,
1291 reason,
1292 cause,
1293 }),
1294 );
1295 contentIndexPending = false;
1297 let { searchQuery, regexMode } = buildContentSearchQuery(input);
1298 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
1299 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
1300 const rawPageSize = input.wholeWord
1301 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
1302 : input.limit;
1303 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
1304 let nextCursor: GrepCursor | null = null;
1305 let regexFallbackError: string | undefined;
1306 let retryLiterally = false;
1307​
1308 do {
1309 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
1310 const result = yield* runSearch(input.query, input.limit, "grep", () =>
1311 finder.grepAsync(searchQuery, {
1312 mode: regexMode ? "regex" : "plain",
1313 smartCase: !input.caseSensitive && !regexMode,
1314 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
1315 pageSize: rawPageSize,
1316 cursor: nextCursor,
1317 timeBudgetMs: remainingTimeBudgetMs,
1318 }),
1319 );
1320 // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix.
1321 retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined;
1322 if (retryLiterally) {
1323 regexFallbackError = result.regexFallbackError;
1324 ({ searchQuery, regexMode } = buildContentSearchQuery({ ...input, useRegex: false }));
1325 continue;
1327​
1328 for (const match of result.items) {
1329 if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue;
1330 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
1331 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
1332 );
1333 // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.
1334 if (input.wholeWord && matchRanges.length === 0) continue;
1335 matches.push({
1336 path: toPosixPath(match.relativePath, hostIsWindows),
1337 lineNumber: match.lineNumber,
1338 lineContent: match.lineContent,
1339 matchRanges,
1340 });
1342 nextCursor = result.nextCursor;
1343 regexFallbackError ??= result.regexFallbackError;
1344 } while (
1345 retryLiterally ||
1346 (matches.length < input.limit && nextCursor !== null && performance.now() < deadline)
1347 );
1348​
1349 return {
1350 matches: matches.slice(0, input.limit),
1351 truncated: matches.length > input.limit || nextCursor !== null,
1352 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
1353 };
1354 });
1355​
1356 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
1357});
1358​
1359export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
1360export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
1361​
1362export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
1363 `${variant}\n${cwd}`;
1364​
1365function parseWorkspaceSearchIndexKey(key: string): {
1366 readonly cwd: string;
1367 readonly variant: WorkspaceSearchIndexVariant;
1368} {
1369 const separatorIndex = key.indexOf("\n");
1370 return {
1371 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
1372 cwd: key.slice(separatorIndex + 1),
1373 };
1375​
1376/** @public */
1377export const layer = (key: string) => {
1378 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
1379 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
1381​
1382export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
1383 "t3/workspace/WorkspaceSearchIndexMap",
1385 lookup: layer,
1386 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
1387 },
1388) {}