Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as RcMap from "effect/RcMap";
9import * as Schema from "effect/Schema";
10
11import type {
12 FilesystemBrowseInput,
13 FilesystemBrowseResult,
14 ProjectEntry,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 ProjectSearchContentsInput,
18 ProjectSearchContentsResult,
19 ProjectSearchEntriesInput,
20 ProjectSearchEntriesResult,
21} from "@t3tools/contracts";
22import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
23import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
24import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
25
26import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
27import * as VcsProcess from "../vcs/VcsProcess.ts";
28import * as WorkspacePaths from "./WorkspacePaths.ts";
29import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
30
31export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
32 "WorkspaceEntriesWindowsPathUnsupportedError",
33 {
34 cwd: Schema.optional(Schema.String),
35 partialPath: Schema.String,
36 platform: Schema.String,
37 },
38) {
39 override get message(): string {
40 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
41 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
42 }
43}
44
45export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
46 "WorkspaceEntriesCurrentProjectRequiredError",
47 {
48 partialPath: Schema.String,
49 },
50) {
51 override get message(): string {
52 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
53 }
54}
55
56export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
57 "WorkspaceEntriesReadDirectoryError",
58 {
59 cwd: Schema.optional(Schema.String),
60 partialPath: Schema.String,
61 parentPath: Schema.String,
62 cause: Schema.Defect(),
63 },
64) {
65 override get message(): string {
66 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
67 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
68 }
69}
70
71export const WorkspaceEntriesBrowseError = Schema.Union([
72 WorkspaceEntriesWindowsPathUnsupportedError,
73 WorkspaceEntriesCurrentProjectRequiredError,
74 WorkspaceEntriesReadDirectoryError,
75]);
76export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
77
78export const WorkspaceEntriesError = Schema.Union([
79 WorkspaceEntriesReadDirectoryError,
80 WorkspacePaths.WorkspaceRootNotExistsError,
81 WorkspacePaths.WorkspaceRootCreateFailedError,
82 WorkspacePaths.WorkspaceRootStatFailedError,
83 WorkspacePaths.WorkspaceRootNotDirectoryError,
84 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
85 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
86 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
87]);
88export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
89
90export class WorkspaceEntries extends Context.Service<
91 WorkspaceEntries,
92 {
93 readonly browse: (
94 input: FilesystemBrowseInput,
95 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
96 readonly list: (
97 input: ProjectListEntriesInput,
98 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
99 readonly search: (
100 input: ProjectSearchEntriesInput,
101 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
102 readonly searchContents: (
103 input: ProjectSearchContentsInput,
104 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
105 readonly refresh: (cwd: string) => Effect.Effect<void>;
106 }
107>()("t3/workspace/WorkspaceEntries") {}
108
109const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
110 input: FilesystemBrowseInput,
111 path: Path.Path,
112): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
113 const platform = yield* HostProcessPlatform;
114 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
115 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
116 cwd: input.cwd,
117 partialPath: input.partialPath,
118 platform,
119 });
120 }
121
122 if (!isExplicitRelativePath(input.partialPath)) {
123 return path.resolve(expandHomePath(input.partialPath));
124 }
125
126 if (!input.cwd) {
127 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
128 partialPath: input.partialPath,
129 });
130 }
131 return path.resolve(expandHomePath(input.cwd), input.partialPath);
132});
133
134/** @public Service construction is part of the canonical Effect module API. */
135export const make = Effect.gen(function* () {
136 const path = yield* Path.Path;
137 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
138 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
139 const vcsProcess = yield* VcsProcess.VcsProcess;
140
141 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
142 cwd: string,
143 ): Effect.fn.Return<string, WorkspaceEntriesError> {
144 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
145 });
146
147 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
148 function* (cwd) {
149 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
150 Effect.orElseSucceed(() => cwd),
151 );
152 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
153 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
154 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
155 continue;
156 }
157 const recoverRefreshFailure = (
158 cause:
159 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
160 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
161 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
162 ) =>
163 Effect.gen(function* () {
164 yield* Effect.logWarning("Failed to refresh workspace search index", {
165 cwd,
166 variant,
167 cause,
168 });
169 yield* workspaceSearchIndexes.invalidate(indexKey);
170 });
171 yield* Effect.gen(function* () {
172 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
173 yield* searchIndex.refresh();
174 }).pipe(
175 Effect.provide(workspaceSearchIndexes.get(indexKey)),
176 Effect.catchTags({
177 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
178 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
179 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
180 }),
181 );
182 }
183 },
184 );
185
186 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
187 function* (input) {
188 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
189 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
190 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
191 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
192
193 const dirents = yield* Effect.tryPromise({
194 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
195 catch: (cause) =>
196 new WorkspaceEntriesReadDirectoryError({
197 cwd: input.cwd,
198 partialPath: input.partialPath,
199 parentPath,
200 cause,
201 }),
202 }).pipe(
203 Effect.catchIf(
204 (error) => {
205 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
206 return code === "EACCES" || code === "EPERM";
207 },
208 () => Effect.succeed([]),
209 ),
210 );
211
212 const showHidden = endsWithSeparator || prefix.startsWith(".");
213 const lowerPrefix = prefix.toLowerCase();
214 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
215 for (const dirent of dirents) {
216 if (
217 dirent.isDirectory() &&
218 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
219 (showHidden || !dirent.name.startsWith("."))
220 ) {
221 entries.push({
222 name: dirent.name,
223 fullPath: path.join(parentPath, dirent.name),
224 });
225 }
226 }
227
228 return {
229 parentPath,
230 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
231 };
232 },
233 );
234
235 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
236 function* (input) {
237 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
238 const normalizedQuery = normalizeSearchQuery(input.query, {
239 trimLeadingPattern: /^[@./]+/,
240 });
241 return yield* Effect.gen(function* () {
242 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
243 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
244 }).pipe(
245 Effect.provide(
246 workspaceSearchIndexes.get(
247 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
248 ),
249 ),
250 );
251 },
252 );
253
254 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
255 "WorkspaceEntries.searchContents",
256 )(function* (input) {
257 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
258 return yield* Effect.gen(function* () {
259 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
260 return yield* searchIndex.searchContents(input);
261 }).pipe(
262 Effect.provide(
263 workspaceSearchIndexes.get(
264 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
265 ),
266 ),
267 );
268 });
269
270 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
271 function* (input) {
272 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
273 if (input.directoryPath !== undefined) {
274 const directoryPath = input.directoryPath;
275 const toError = (cause: unknown) =>
276 new WorkspaceEntriesReadDirectoryError({
277 cwd: normalizedCwd,
278 partialPath: directoryPath,
279 parentPath: path.resolve(normalizedCwd, directoryPath),
280 cause,
281 });
282 const target =
283 directoryPath === ""
284 ? { absolutePath: normalizedCwd, relativePath: "" }
285 : yield* workspacePaths
286 .resolveRelativePathWithinRoot({
287 workspaceRoot: normalizedCwd,
288 relativePath: directoryPath,
289 })
290 .pipe(Effect.mapError(toError));
291 const entries = yield* Effect.tryPromise({
292 try: async () => {
293 const root = await NodeFSP.realpath(normalizedCwd);
294 const directory = await NodeFSP.realpath(target.absolutePath);
295 const relative = path.relative(root, directory);
296 if (
297 relative === ".." ||
298 relative.startsWith(`..${path.sep}`) ||
299 path.isAbsolute(relative) ||
300 relative.split(path.sep).includes(".git") ||
301 target.relativePath.split("/").includes(".git")
302 ) {
303 throw new Error("Directory must be inside the workspace and outside .git.");
304 }
305 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
306 return children.flatMap((child): ProjectEntry[] => {
307 if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];
308 return [
309 {
310 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
311 kind: child.isDirectory() ? "directory" : "file",
312 },
313 ];
314 });
315 },
316 catch: toError,
317 });
318 // Use stdin so large directories cannot exceed the command-line argument limit.
319 // Ignore classification is optional in non-git workspaces or when git is unavailable.
320 const ignored = new Set<string>();
321 for (let offset = 0; offset < entries.length; offset += 1000) {
322 const chunk = entries.slice(offset, offset + 1000);
323 const result = yield* vcsProcess
324 .run({
325 operation: "WorkspaceEntries.list",
326 command: "git",
327 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
328 cwd: normalizedCwd,
329 stdin: `${chunk.map((entry) => entry.path).join("\0")}\0`,
330 allowNonZeroExit: true,
331 timeoutMs: 10_000,
332 maxOutputBytes: 16 * 1024 * 1024,
333 })
334 .pipe(Effect.orElseSucceed(() => undefined));
335 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
336 for (const ignoredPath of result.stdout.split("\0")) ignored.add(ignoredPath);
337 }
338 return {
339 entries: entries.map((entry) =>
340 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
341 ),
342 truncated: false,
343 };
344 }
345 return yield* Effect.gen(function* () {
346 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
347 return yield* searchIndex.list();
348 }).pipe(
349 Effect.provide(
350 workspaceSearchIndexes.get(
351 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
352 ),
353 ),
354 );
355 },
356 );
357
358 return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
359});
360
361export const layer = Layer.effect(WorkspaceEntries, make).pipe(
362 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
363 Layer.provide(VcsProcess.layer),
364);