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

WorkspaceFileSystem.ts

514 lines18.8 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeFSP from "node:fs/promises";
4​
5import type {
6 FilesystemEntryMetadata,
7 FilesystemGetMetadataInput,
8 FilesystemGetMetadataResult,
9 ProjectReadFileInput,
10 ProjectReadFileResult,
11 ProjectWriteFileInput,
12 ProjectWriteFileResult,
13} from "@t3tools/contracts";
14import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22​
23import * as KnownWorkspaces from "./KnownWorkspaces.ts";
24import * as WorkspaceEntries from "./WorkspaceEntries.ts";
25import * as WorkspacePaths from "./WorkspacePaths.ts";
26import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
27​
28const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
29​
30// Windows also reaches `.git` through trailing dots or spaces, a `:` stream
31// suffix, or the 8.3 short name `GIT~1`. Names compare upcased, as NTFS does.
32const isGitMetadataName = (segment: string) => {
33 const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
34 return name === ".GIT" || name === "GIT~1";
35};
36​
37export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
38 "WorkspaceFileSystemOperationError",
39 {
40 workspaceRoot: Schema.String,
41 relativePath: Schema.String,
42 resolvedPath: Schema.String,
43 operationPath: Schema.String,
44 operation: Schema.Literals([
45 "realpath-workspace-root",
46 "realpath-target",
47 "open",
48 "stat",
49 "read",
50 "close",
51 "make-directory",
52 "write-file",
53 ]),
54 cause: Schema.Defect(),
55 },
56) {
57 override get message(): string {
58 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
59 }
61​
62export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
63 "WorkspaceFilePathEscapeError",
64 {
65 workspaceRoot: Schema.String,
66 relativePath: Schema.String,
67 resolvedWorkspaceRoot: Schema.String,
68 resolvedPath: Schema.String,
69 },
70) {
71 override get message(): string {
72 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
73 }
75​
76export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
77 "WorkspacePathNotFileError",
78 {
79 workspaceRoot: Schema.String,
80 relativePath: Schema.String,
81 resolvedPath: Schema.String,
82 },
83) {
84 override get message(): string {
85 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
86 }
88​
89export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
90 "WorkspaceBinaryFileError",
91 {
92 workspaceRoot: Schema.String,
93 relativePath: Schema.String,
94 resolvedPath: Schema.String,
95 },
96) {
97 override get message(): string {
98 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
99 }
101​
102export const WorkspaceFileSystemError = Schema.Union([
103 WorkspaceFileSystemOperationError,
104 WorkspaceFilePathEscapeError,
105 WorkspacePathNotFileError,
106 WorkspaceBinaryFileError,
107]);
108export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
109​
110export class WorkspaceFileSystem extends Context.Service<
111 WorkspaceFileSystem,
112 {
113 readonly getMetadata: (
114 input: FilesystemGetMetadataInput,
115 ) => Effect.Effect<FilesystemGetMetadataResult>;
116​
117 readonly readFile: (
118 input: ProjectReadFileInput,
119 ) => Effect.Effect<
120 ProjectReadFileResult,
121 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
122 >;
123 /** Writes inside a known workspace only. */
124 readonly writeFile: (
125 input: ProjectWriteFileInput,
126 ) => Effect.Effect<
127 ProjectWriteFileResult,
128 | WorkspaceFileSystemError
129 | WorkspacePaths.WorkspacePathOutsideRootError
130 | KnownWorkspaces.UnknownWorkspaceError
131 >;
132 }
133>()("t3/workspace/WorkspaceFileSystem") {}
134​
135/** @public Service construction is part of the canonical Effect module API. */
136export const make = Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
140 const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
141 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
142​
143 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
144 const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
145 if (!path.isAbsolute(expandedPath)) return null;
146 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
147 if (stat._tag === "None") return null;
148 if (stat.value.type === "Directory") return { kind: "directory" } as const;
149 if (stat.value.type !== "File") return { kind: "other" } as const;
150 let mimeType: string | undefined;
151 if (path.extname(expandedPath) === "" && stat.value.size > 0) {
152 mimeType = yield* Effect.tryPromise({
153 try: async () => {
154 const handle = await NodeFSP.open(
155 expandedPath,
156 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
157 );
158 try {
159 if (!(await handle.stat()).isFile()) return undefined;
160 const buffer = Buffer.alloc(512);
161 const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
162 return fileHeaderMimeType(buffer.subarray(0, bytesRead));
163 } finally {
164 await handle.close();
165 }
166 },
167 catch: () => undefined,
168 }).pipe(Effect.catch(() => Effect.succeed(undefined)));
169 }
170 return {
171 kind: "file",
172 byteLength: Number(stat.value.size),
173 ...(mimeType === undefined ? {} : { mimeType }),
174 } satisfies FilesystemEntryMetadata;
175 });
176​
177 const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
178 "WorkspaceFileSystem.getMetadata",
179 )(function* (input) {
180 const paths = [...new Set(input.paths)];
181 const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
182 const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
183 return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
184 });
185​
186 /** Both paths must already be real paths. */
187 const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
188 const relative = path.relative(realWorkspaceRoot, realPath);
189 return !(
190 relative.startsWith(`..${path.sep}`) ||
191 relative === ".." ||
192 path.isAbsolute(relative)
193 );
194 };
195​
196 /**
197 * Git runs config and hooks from its own folders, so a write never lands in one:
198 * a `.git` entry, or a repository folder under another name such as `.bare`.
199 * Folders are checked upward to a linked worktree's top, which holds a `.git`
200 * file, since worktrees can sit inside a bare repository. `absolutePath` must
201 * be normalized.
202 */
203 const isInGitFolder = async (absolutePath: string) => {
204 if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
205 for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
206 const [head, commondir, objects, refs, dotGit] = await Promise.all(
207 ["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
208 NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
209 // Any other failure leaves the folder unknown, so the write is refused.
210 if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
211 throw error;
212 }),
213 ),
214 );
215 // What git reads as a repository: HEAD, plus objects and refs here or in
216 // the folder a `commondir` file names, as in a linked worktree's git folder.
217 if (head && (commondir || (objects && refs))) return true;
218 if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
219 }
220 };
221​
222 /**
223 * Workspace-relative paths must stay inside the root, symlinks included. An
224 * absolute path reads a host file in place, such as a report an agent wrote to a
225 * temp directory; it gets no root check.
226 */
227 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
228 input: ProjectReadFileInput,
229 ) {
230 const requestedPath = input.relativePath.trim();
231 if (path.isAbsolute(requestedPath)) {
232 const realTargetPath = yield* Effect.tryPromise({
233 try: () => NodeFSP.realpath(requestedPath),
234 catch: (cause) =>
235 new WorkspaceFileSystemOperationError({
236 workspaceRoot: input.cwd,
237 relativePath: input.relativePath,
238 resolvedPath: requestedPath,
239 operationPath: requestedPath,
240 operation: "realpath-target",
241 cause,
242 }),
243 });
244 return { relativePath: requestedPath, realTargetPath };
245 }
246​
247 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
248 workspaceRoot: input.cwd,
249 relativePath: input.relativePath,
250 });
251​
252 const realWorkspaceRoot = yield* Effect.tryPromise({
253 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
254 catch: (cause) =>
255 new WorkspaceFileSystemOperationError({
256 workspaceRoot: input.cwd,
257 relativePath: input.relativePath,
258 resolvedPath: target.absolutePath,
259 operationPath: input.cwd,
260 operation: "realpath-workspace-root",
261 cause,
262 }),
263 });
264 const realTargetPath = yield* Effect.tryPromise({
265 try: () => NodeFSP.realpath(target.absolutePath),
266 catch: (cause) =>
267 new WorkspaceFileSystemOperationError({
268 workspaceRoot: input.cwd,
269 relativePath: input.relativePath,
270 resolvedPath: target.absolutePath,
271 operationPath: target.absolutePath,
272 operation: "realpath-target",
273 cause,
274 }),
275 });
276 if (!isInsideRealRoot(realWorkspaceRoot, realTargetPath)) {
277 return yield* new WorkspaceFilePathEscapeError({
278 workspaceRoot: input.cwd,
279 relativePath: input.relativePath,
280 resolvedWorkspaceRoot: realWorkspaceRoot,
281 resolvedPath: realTargetPath,
282 });
283 }
284 return { relativePath: target.relativePath, realTargetPath };
285 });
286​
287 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
288 "WorkspaceFileSystem.readFile",
289 )(function* (input) {
290 const target = yield* resolveReadTarget(input);
291 const realTargetPath = target.realTargetPath;
292​
293 return yield* Effect.acquireUseRelease(
294 Effect.tryPromise({
295 // Non-blocking so a FIFO cannot hang the open; the stat below rejects
296 // it. Regular files ignore the flag. Windows lacks it.
297 try: () =>
298 NodeFSP.open(
299 realTargetPath,
300 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
301 ),
302 catch: (cause) =>
303 new WorkspaceFileSystemOperationError({
304 workspaceRoot: input.cwd,
305 relativePath: input.relativePath,
306 resolvedPath: realTargetPath,
307 operationPath: realTargetPath,
308 operation: "open",
309 cause,
310 }),
311 }),
312 (handle) =>
313 Effect.gen(function* () {
314 const stat = yield* Effect.tryPromise({
315 try: () => handle.stat(),
316 catch: (cause) =>
317 new WorkspaceFileSystemOperationError({
318 workspaceRoot: input.cwd,
319 relativePath: input.relativePath,
320 resolvedPath: realTargetPath,
321 operationPath: realTargetPath,
322 operation: "stat",
323 cause,
324 }),
325 });
326 if (!stat.isFile()) {
327 return yield* new WorkspacePathNotFileError({
328 workspaceRoot: input.cwd,
329 relativePath: input.relativePath,
330 resolvedPath: realTargetPath,
331 });
332 }
333​
334 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
335 const buffer = Buffer.alloc(bytesToRead);
336 const { bytesRead } = yield* Effect.tryPromise({
337 try: () => handle.read(buffer, 0, bytesToRead, 0),
338 catch: (cause) =>
339 new WorkspaceFileSystemOperationError({
340 workspaceRoot: input.cwd,
341 relativePath: input.relativePath,
342 resolvedPath: realTargetPath,
343 operationPath: realTargetPath,
344 operation: "read",
345 cause,
346 }),
347 });
348 const fileBytes = buffer.subarray(0, bytesRead);
349 if (fileBytes.includes(0)) {
350 return yield* new WorkspaceBinaryFileError({
351 workspaceRoot: input.cwd,
352 relativePath: input.relativePath,
353 resolvedPath: realTargetPath,
354 });
355 }
356​
357 return {
358 relativePath: target.relativePath,
359 contents: new TextDecoder("utf-8").decode(fileBytes),
360 byteLength: stat.size,
361 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
362 };
363 }),
364 (handle) =>
365 Effect.tryPromise({
366 try: () => handle.close(),
367 catch: (cause) =>
368 new WorkspaceFileSystemOperationError({
369 workspaceRoot: input.cwd,
370 relativePath: input.relativePath,
371 resolvedPath: realTargetPath,
372 operationPath: realTargetPath,
373 operation: "close",
374 cause,
375 }),
376 }),
377 );
378 });
379​
380 /**
381 * Resolves the file a write targets. The deepest existing ancestor resolves to
382 * its real path before the root check, so neither the file nor the directories
383 * created for it can follow a symlink out of the root. A dangling symlink is
384 * rejected rather than written through.
385 */
386 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
387 input: ProjectWriteFileInput,
388 ) {
389 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
390 workspaceRoot: input.cwd,
391 relativePath: input.relativePath,
392 });
393 const realWorkspaceRoot = yield* Effect.tryPromise({
394 // Resolve `..` in cwd the way the relative path was resolved, before following links.
395 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
396 catch: (cause) =>
397 new WorkspaceFileSystemOperationError({
398 workspaceRoot: input.cwd,
399 relativePath: input.relativePath,
400 resolvedPath: target.absolutePath,
401 operationPath: input.cwd,
402 operation: "realpath-workspace-root",
403 cause,
404 }),
405 });
406​
407 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
408 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
409 const realTargetPath = yield* Effect.tryPromise({
410 try: async () => {
411 for (let depth = segments.length; depth > 0; depth--) {
412 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
413 try {
414 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
415 } catch (error) {
416 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
417 const exists = await NodeFSP.lstat(candidate).then(
418 () => true,
419 () => false,
420 );
421 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
422 }
423 }
424 return path.join(realWorkspaceRoot, ...segments);
425 },
426 catch: (cause) =>
427 new WorkspaceFileSystemOperationError({
428 workspaceRoot: input.cwd,
429 relativePath: input.relativePath,
430 resolvedPath: target.absolutePath,
431 operationPath: target.absolutePath,
432 operation: "realpath-target",
433 cause,
434 }),
435 });
436 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
437 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
438 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
439 Effect.tryPromise({
440 try: () => isInGitFolder(checkedPath),
441 catch: (cause) =>
442 new WorkspaceFileSystemOperationError({
443 workspaceRoot: input.cwd,
444 relativePath: input.relativePath,
445 resolvedPath: realTargetPath,
446 operationPath: checkedPath,
447 operation: "stat",
448 cause,
449 }),
450 }),
451 );
452 if (
453 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
454 (yield* inGitFolder(realTargetPath)) ||
455 (yield* inGitFolder(namedTargetPath))
456 ) {
457 return yield* new WorkspaceFilePathEscapeError({
458 workspaceRoot: input.cwd,
459 relativePath: input.relativePath,
460 resolvedWorkspaceRoot: realWorkspaceRoot,
461 resolvedPath: realTargetPath,
462 });
463 }
464 return { relativePath: target.relativePath, realTargetPath };
465 });
466​
467 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
468 "WorkspaceFileSystem.writeFile",
469 )(function* (input) {
470 yield* knownWorkspaces.assertContains(input.cwd);
471 const target = yield* resolveWriteTarget(input);
472 const realTargetPath = target.realTargetPath;
473​
474 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
475 Effect.mapError(
476 (cause) =>
477 new WorkspaceFileSystemOperationError({
478 workspaceRoot: input.cwd,
479 relativePath: input.relativePath,
480 resolvedPath: realTargetPath,
481 operationPath: path.dirname(realTargetPath),
482 operation: "make-directory",
483 cause,
484 }),
485 ),
486 );
487 yield* Effect.tryPromise({
488 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
489 try: () =>
490 NodeFSP.writeFile(realTargetPath, input.contents, {
491 flag:
492 NodeFS.constants.O_WRONLY |
493 NodeFS.constants.O_CREAT |
494 NodeFS.constants.O_TRUNC |
495 (NodeFS.constants.O_NOFOLLOW ?? 0),
496 }),
497 catch: (cause) =>
498 new WorkspaceFileSystemOperationError({
499 workspaceRoot: input.cwd,
500 relativePath: input.relativePath,
501 resolvedPath: realTargetPath,
502 operationPath: realTargetPath,
503 operation: "write-file",
504 cause,
505 }),
506 });
507 yield* workspaceEntries.refresh(input.cwd);
508 return { relativePath: target.relativePath };
509 });
510​
511 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
512});
513​
514export const layer = Layer.effect(WorkspaceFileSystem, make);