Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as RcMap from "effect/RcMap";
10import * as Schema from "effect/Schema";
11
12import type {
13 FilesystemBrowseInput,
14 FilesystemBrowseResult,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 ProjectSearchEntriesInput,
18 ProjectSearchEntriesResult,
19} from "@t3tools/contracts";
20import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
21import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
22
23import * as WorkspacePaths from "./WorkspacePaths.ts";
24import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
25
26export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedErrorClass<WorkspaceEntriesWindowsPathUnsupportedError>()(
27 "WorkspaceEntriesWindowsPathUnsupportedError",
28 {
29 cwd: Schema.optional(Schema.String),
30 partialPath: Schema.String,
31 platform: Schema.String,
32 },
33) {
34 override get message(): string {
35 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
36 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
37 }
38}
39
40export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedErrorClass<WorkspaceEntriesCurrentProjectRequiredError>()(
41 "WorkspaceEntriesCurrentProjectRequiredError",
42 {
43 partialPath: Schema.String,
44 },
45) {
46 override get message(): string {
47 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
48 }
49}
50
51export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedErrorClass<WorkspaceEntriesReadDirectoryError>()(
52 "WorkspaceEntriesReadDirectoryError",
53 {
54 cwd: Schema.optional(Schema.String),
55 partialPath: Schema.String,
56 parentPath: Schema.String,
57 cause: Schema.Defect(),
58 },
59) {
60 override get message(): string {
61 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
62 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
63 }
64}
65
66export const WorkspaceEntriesBrowseError = Schema.Union([
67 WorkspaceEntriesWindowsPathUnsupportedError,
68 WorkspaceEntriesCurrentProjectRequiredError,
69 WorkspaceEntriesReadDirectoryError,
70]);
71export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
72
73export const WorkspaceEntriesError = Schema.Union([
74 WorkspacePaths.WorkspaceRootNotExistsError,
75 WorkspacePaths.WorkspaceRootCreateFailedError,
76 WorkspacePaths.WorkspaceRootStatFailedError,
77 WorkspacePaths.WorkspaceRootNotDirectoryError,
78 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
79 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
80 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
81]);
82export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
83
84export class WorkspaceEntries extends Context.Service<
85 WorkspaceEntries,
86 {
87 readonly browse: (
88 input: FilesystemBrowseInput,
89 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
90 readonly list: (
91 input: ProjectListEntriesInput,
92 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
93 readonly search: (
94 input: ProjectSearchEntriesInput,
95 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
96 readonly refresh: (cwd: string) => Effect.Effect<void>;
97 }
98>()("t3/workspace/WorkspaceEntries") {}
99
100function expandHomePath(input: string, path: Path.Path): string {
101 if (input === "~") {
102 return NodeOS.homedir();
103 }
104 if (input.startsWith("~/") || input.startsWith("~\\")) {
105 return path.join(NodeOS.homedir(), input.slice(2));
106 }
107 return input;
108}
109
110const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
111 input: FilesystemBrowseInput,
112 path: Path.Path,
113): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
114 const platform = yield* HostProcessPlatform;
115 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
116 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
117 cwd: input.cwd,
118 partialPath: input.partialPath,
119 platform,
120 });
121 }
122
123 if (!isExplicitRelativePath(input.partialPath)) {
124 return path.resolve(expandHomePath(input.partialPath, path));
125 }
126
127 if (!input.cwd) {
128 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
129 partialPath: input.partialPath,
130 });
131 }
132 return path.resolve(expandHomePath(input.cwd, path), input.partialPath);
133});
134
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
140 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
141 cwd: string,
142 ): Effect.fn.Return<string, WorkspaceEntriesError> {
143 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
144 });
145
146 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
147 function* (cwd) {
148 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
149 Effect.orElseSucceed(() => cwd),
150 );
151 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
152 return;
153 }
154 const recoverRefreshFailure = (
155 cause:
156 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
157 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
158 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
159 ) =>
160 Effect.gen(function* () {
161 yield* Effect.logWarning("Failed to refresh workspace search index", {
162 cwd,
163 cause,
164 });
165 yield* workspaceSearchIndexes.invalidate(normalizedCwd);
166 });
167 yield* Effect.gen(function* () {
168 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
169 yield* searchIndex.refresh();
170 }).pipe(
171 Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
172 Effect.catchTags({
173 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
174 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
175 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
176 }),
177 );
178 },
179 );
180
181 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
182 function* (input) {
183 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
184 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
185 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
186 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
187
188 const dirents = yield* Effect.tryPromise({
189 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
190 catch: (cause) =>
191 new WorkspaceEntriesReadDirectoryError({
192 cwd: input.cwd,
193 partialPath: input.partialPath,
194 parentPath,
195 cause,
196 }),
197 }).pipe(
198 Effect.catchIf(
199 (error) => {
200 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
201 return code === "EACCES" || code === "EPERM";
202 },
203 () => Effect.succeed([]),
204 ),
205 );
206
207 const showHidden = endsWithSeparator || prefix.startsWith(".");
208 const lowerPrefix = prefix.toLowerCase();
209 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
210 for (const dirent of dirents) {
211 if (
212 dirent.isDirectory() &&
213 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
214 (showHidden || !dirent.name.startsWith("."))
215 ) {
216 entries.push({
217 name: dirent.name,
218 fullPath: path.join(parentPath, dirent.name),
219 });
220 }
221 }
222
223 return {
224 parentPath,
225 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
226 };
227 },
228 );
229
230 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
231 function* (input) {
232 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
233 const normalizedQuery = input.query
234 .trim()
235 .toLowerCase()
236 .replace(/^[@./]+/, "");
237 return yield* Effect.gen(function* () {
238 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
239 return yield* searchIndex.search(normalizedQuery, input.limit);
240 }).pipe(Effect.provide(workspaceSearchIndexes.get(normalizedCwd)));
241 },
242 );
243
244 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
245 function* (input) {
246 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
247 return yield* Effect.gen(function* () {
248 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
249 return yield* searchIndex.list();
250 }).pipe(Effect.provide(workspaceSearchIndexes.get(normalizedCwd)));
251 },
252 );
253
254 return WorkspaceEntries.of({ browse, list, refresh, search });
255});
256
257export const layer = Layer.effect(WorkspaceEntries, make).pipe(
258 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
259);