Open History to see the last commit
1import * as NodeModule from "node:module";
2
3import type {
4 DirItem,
5 DirSearchResult,
6 FileItem,
7 FileFinder as FileFinderType,
8 GrepCursor,
9 MixedItem,
10 MixedSearchResult,
11 Result,
12 SearchResult,
13} from "@ff-labs/fff-node";
14import * as Context from "effect/Context";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as LayerMap from "effect/LayerMap";
18import * as Schema from "effect/Schema";
19
20import type {
21 ProjectEntry,
22 ProjectEntryKind,
23 ProjectListEntriesResult,
24 ProjectSearchContentsInput,
25 ProjectSearchContentsResult,
26 ProjectSearchEntriesResult,
27} from "@t3tools/contracts";
28import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
29
30// fff-node's native library stays external; single-executables require disk packages instead of importing them.
31const requireForFff = NodeModule.createRequire(import.meta.url);
32const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
33
34const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
35const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
36const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
37const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
38const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
39const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
40const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
41
42export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError<WorkspaceSearchIndexCreateFailed>()(
43 "WorkspaceSearchIndexCreateFailed",
44 {
45 cwd: Schema.String,
46 reason: Schema.String,
47 cause: Schema.optional(Schema.Defect()),
48 },
49) {
50 override get message(): string {
51 return `Failed to create the workspace search index for '${this.cwd}'.`;
52 }
53}
54
55export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedError<WorkspaceSearchIndexScanTimedOut>()(
56 "WorkspaceSearchIndexScanTimedOut",
57 {
58 cwd: Schema.String,
59 timeout: Schema.String,
60 },
61) {
62 override get message(): string {
63 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
64 }
65}
66
67export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedError<WorkspaceSearchIndexSearchFailed>()(
68 "WorkspaceSearchIndexSearchFailed",
69 {
70 cwd: Schema.String,
71 queryLength: Schema.Number,
72 pageSize: Schema.Number,
73 reason: Schema.String,
74 cause: Schema.optional(Schema.Defect()),
75 },
76) {
77 override get message(): string {
78 return `Workspace search failed for '${this.cwd}'.`;
79 }
80}
81
82export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedError<WorkspaceSearchIndexRefreshFailed>()(
83 "WorkspaceSearchIndexRefreshFailed",
84 {
85 cwd: Schema.String,
86 reason: Schema.String,
87 cause: Schema.optional(Schema.Defect()),
88 },
89) {
90 override get message(): string {
91 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
92 }
93}
94
95export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<WorkspaceSearchIndexDestroyFailed>()(
96 "WorkspaceSearchIndexDestroyFailed",
97 {
98 cwd: Schema.String,
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
104 }
105}
106
107export class WorkspaceSearchIndex extends Context.Service<
108 WorkspaceSearchIndex,
109 {
110 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
111 readonly search: (
112 query: string,
113 limit: number,
114 kind?: ProjectEntryKind,
115 imageOnly?: boolean,
116 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
117 readonly searchContents: (
118 input: Omit<ProjectSearchContentsInput, "cwd">,
119 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;
120 readonly refresh: () => Effect.Effect<
121 void,
122 WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut
123 >;
124 }
125>()("t3/workspace/WorkspaceSearchIndex") {}
126
127function toPosixPath(input: string): string {
128 return input.replaceAll("\\", "/");
129}
130
131function trimDirectorySeparator(input: string): string {
132 return input.endsWith("/") ? input.slice(0, -1) : input;
133}
134
135function parentPathOf(input: string): string | undefined {
136 const separatorIndex = input.lastIndexOf("/");
137 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
138}
139
140function toProjectEntry(item: MixedItem): ProjectEntry | null {
141 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));
142 if (!normalizedPath) {
143 return null;
144 }
145
146 return {
147 path: normalizedPath,
148 kind: item.type,
149 };
150}
151
152function toFileEntry(item: FileItem): ProjectEntry | null {
153 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
154 return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
155}
156
157function toDirectoryEntry(item: DirItem): ProjectEntry | null {
158 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
159 return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
160}
161
162function mapFileSearchResult(
163 result: SearchResult,
164 limit: number,
165 imageOnly = false,
166): ProjectSearchEntriesResult {
167 const entries = result.items.flatMap((item) => {
168 const entry = toFileEntry(item);
169 return entry && (!imageOnly || isProjectFaviconPath(entry.path)) ? [entry] : [];
170 });
171 return {
172 entries: entries.slice(0, limit),
173 truncated: entries.length > limit || result.totalMatched > result.items.length,
174 };
175}
176
177function mapDirectorySearchResult(
178 result: DirSearchResult,
179 limit: number,
180): ProjectSearchEntriesResult {
181 const entries = result.items.flatMap((item) => {
182 const entry = toDirectoryEntry(item);
183 return entry ? [entry] : [];
184 });
185 const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
186 return {
187 entries: entries.slice(0, limit),
188 truncated: result.totalMatched - rootDirectoryCount > limit,
189 };
190}
191
192function mapMixedSearchResult(
193 result: MixedSearchResult,
194 limit: number,
195): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
196 const entries: ProjectEntry[] = [];
197 for (const item of result.items) {
198 const entry = toProjectEntry(item);
199 if (entry) {
200 entries.push(entry);
201 }
202 if (entries.length >= limit) {
203 break;
204 }
205 }
206
207 const rootDirectoryCount = result.items.some(
208 (item) => item.type === "directory" && item.item.relativePath.length === 0,
209 )
210 ? 1
211 : 0;
212 return {
213 entries,
214 truncated: result.totalMatched - rootDirectoryCount > limit,
215 };
216}
217
218const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
219
220function codePointAt(line: string, index: number): string | undefined {
221 const codePoint = line.codePointAt(index);
222 return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
223}
224
225function codePointBefore(line: string, index: number): string | undefined {
226 if (index <= 0) return undefined;
227 const previousCodeUnit = line.charCodeAt(index - 1);
228 const previousIndex =
229 previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
230 return codePointAt(line, previousIndex);
231}
232
233function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
234 readonly searchQuery: string;
235 readonly regexMode: boolean;
236} {
237 if (input.caseSensitive) {
238 return { searchQuery: input.query, regexMode: input.useRegex };
239 }
240 return input.useRegex
241 ? { searchQuery: `(?i)${input.query}`, regexMode: true }
242 : { searchQuery: input.query.toLowerCase(), regexMode: false };
243}
244
245function mapContentMatchRanges(
246 line: string,
247 byteRanges: ReadonlyArray<readonly [number, number]>,
248): Array<{ readonly start: number; readonly end: number }> {
249 const lineBytes = Buffer.from(line);
250 const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
251 return byteRanges.map(([startByte, endByte]) => ({
252 start: toStringIndex(startByte),
253 end: toStringIndex(endByte),
254 }));
255}
256
257// Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges.
258function isWholeWordRange(
259 line: string,
260 range: { readonly start: number; readonly end: number },
261): boolean {
262 if (range.end <= range.start) return false;
263 const isWord = (character: string | undefined) =>
264 character !== undefined && WORD_CHARACTER.test(character);
265 const leftIsBoundary =
266 range.start === 0 ||
267 !isWord(codePointBefore(line, range.start)) ||
268 !isWord(codePointAt(line, range.start));
269 const rightIsBoundary =
270 range.end >= line.length ||
271 !isWord(codePointAt(line, range.end)) ||
272 !isWord(codePointBefore(line, range.end));
273 return leftIsBoundary && rightIsBoundary;
274}
275
276function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
277 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
278 for (const entry of entries) {
279 let parentPath = parentPathOf(entry.path);
280 while (parentPath) {
281 if (!entryByPath.has(parentPath)) {
282 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
283 }
284 parentPath = parentPathOf(parentPath);
285 }
286 }
287 return [...entryByPath.values()];
288}
289
290const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
291 cwd: string,
292 variant: WorkspaceSearchIndexVariant,
293) {
294 const result = yield* Effect.try({
295 try: () =>
296 FileFinder.create({
297 basePath: cwd,
298 disableMmapCache: true,
299 // Content indexing costs CPU/memory; path-only consumers use the lightweight index.
300 disableContentIndexing: variant !== "content",
301 aiMode: false,
302 enableFsRootScanning: true,
303 enableHomeDirScanning: true,
304 }),
305 catch: (cause) =>
306 new WorkspaceSearchIndexCreateFailed({
307 cwd,
308 reason: "FileFinder.create threw unexpectedly.",
309 cause,
310 }),
311 });
312 if (result.ok) return result.value;
313 return yield* new WorkspaceSearchIndexCreateFailed({
314 cwd,
315 reason: result.error,
316 });
317});
318
319const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
320 cwd: string,
321 finder: FileFinderType,
322 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
323): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
324 const result = yield* Effect.tryPromise({
325 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
326 catch: (cause) =>
327 onFailure({
328 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
329 cause,
330 }),
331 });
332 if (!result.ok) {
333 return yield* Effect.fail(onFailure({ reason: result.error }));
334 }
335 if (!result.value) {
336 return yield* new WorkspaceSearchIndexScanTimedOut({
337 cwd,
338 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
339 });
340 }
341});
342
343export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
344 cwd: string,
345 variant: WorkspaceSearchIndexVariant = "paths",
346) {
347 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
348 Effect.try({
349 try: () => finder.destroy(),
350 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
351 }).pipe(Effect.orDie),
352 );
353 let initialScanTimedOut = false;
354 yield* waitForIndexReady(
355 cwd,
356 finder,
357 ({ reason, cause }) =>
358 new WorkspaceSearchIndexCreateFailed({
359 cwd,
360 reason,
361 cause,
362 }),
363 ).pipe(
364 Effect.catchTags({
365 WorkspaceSearchIndexScanTimedOut: (error) =>
366 variant === "paths"
367 ? Effect.sync(() => {
368 initialScanTimedOut = true;
369 })
370 : Effect.fail(error),
371 }),
372 );
373
374 const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning();
375
376 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
377 query: string,
378 pageSize: number,
379 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
380 execute: () => Result<A>,
381 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
382 const result = yield* Effect.try({
383 try: execute,
384 catch: (cause) =>
385 new WorkspaceSearchIndexSearchFailed({
386 cwd,
387 queryLength: query.length,
388 pageSize,
389 reason: `FileFinder.${operation} threw unexpectedly.`,
390 cause,
391 }),
392 });
393 if (!result.ok) {
394 return yield* new WorkspaceSearchIndexSearchFailed({
395 cwd,
396 queryLength: query.length,
397 pageSize,
398 reason: result.error,
399 });
400 }
401 return result.value;
402 });
403
404 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
405 "WorkspaceSearchIndex.refresh",
406 )(function* () {
407 const result = yield* Effect.try({
408 try: () => finder.scanFiles(),
409 catch: (cause) =>
410 new WorkspaceSearchIndexRefreshFailed({
411 cwd,
412 reason: "FileFinder.scanFiles threw unexpectedly.",
413 cause,
414 }),
415 });
416 if (!result.ok) {
417 return yield* new WorkspaceSearchIndexRefreshFailed({
418 cwd,
419 reason: result.error,
420 });
421 }
422 yield* waitForIndexReady(
423 cwd,
424 finder,
425 ({ reason, cause }) =>
426 new WorkspaceSearchIndexRefreshFailed({
427 cwd,
428 reason,
429 cause,
430 }),
431 );
432 });
433
434 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
435 function* () {
436 const incompleteBeforeQuery = hasIncompleteInitialScan();
437 const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
438 finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
439 );
440 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
441 const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
442 left.path.localeCompare(right.path),
443 );
444 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
445 return {
446 entries,
447 truncated:
448 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
449 };
450 },
451 );
452
453 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
454 "WorkspaceSearchIndex.search",
455 )(function* (query, limit, kind, imageOnly) {
456 const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
457 const incompleteBeforeQuery = hasIncompleteInitialScan();
458 if (kind === "file" || imageOnly) {
459 const result = yield* runSearch(query, pageSize, "fileSearch", () =>
460 finder.fileSearch(query, { pageSize }),
461 );
462 const mapped = mapFileSearchResult(result, limit, imageOnly);
463 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
464 }
465 if (kind === "directory") {
466 const result = yield* runSearch(query, pageSize, "directorySearch", () =>
467 finder.directorySearch(query, { pageSize }),
468 );
469 const mapped = mapDirectorySearchResult(result, limit);
470 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
471 }
472 const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
473 finder.mixedSearch(query, { pageSize }),
474 );
475 const mapped = mapMixedSearchResult(result, limit);
476 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
477 });
478
479 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
480 "WorkspaceSearchIndex.searchContents",
481 )(function* (input) {
482 const { searchQuery, regexMode } = buildContentSearchQuery(input);
483 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
484 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
485 const rawPageSize = input.wholeWord
486 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
487 : input.limit;
488 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
489 let nextCursor: GrepCursor | null = null;
490 let regexFallbackError: string | undefined;
491
492 do {
493 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
494 const result = yield* runSearch(input.query, input.limit, "grep", () =>
495 finder.grep(searchQuery, {
496 mode: regexMode ? "regex" : "plain",
497 smartCase: !input.caseSensitive && !regexMode,
498 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
499 pageSize: rawPageSize,
500 cursor: nextCursor,
501 timeBudgetMs: remainingTimeBudgetMs,
502 }),
503 );
504
505 for (const match of result.items) {
506 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
507 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
508 );
509 if (matchRanges.length === 0) continue;
510 matches.push({
511 path: toPosixPath(match.relativePath),
512 lineNumber: match.lineNumber,
513 lineContent: match.lineContent,
514 matchRanges,
515 });
516 }
517 nextCursor = result.nextCursor;
518 regexFallbackError ??= result.regexFallbackError;
519 } while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);
520
521 return {
522 matches: matches.slice(0, input.limit),
523 truncated: matches.length > input.limit || nextCursor !== null,
524 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
525 };
526 });
527
528 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
529});
530
531export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
532export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
533
534export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
535 `${variant}\n${cwd}`;
536
537function parseWorkspaceSearchIndexKey(key: string): {
538 readonly cwd: string;
539 readonly variant: WorkspaceSearchIndexVariant;
540} {
541 const separatorIndex = key.indexOf("\n");
542 return {
543 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
544 cwd: key.slice(separatorIndex + 1),
545 };
546}
547
548/** @public */
549export const layer = (key: string) => {
550 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
551 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
552};
553
554export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
555 "t3/workspace/WorkspaceSearchIndexMap",
556 {
557 lookup: layer,
558 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
559 },
560) {}