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