Open History to see the last commit
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 { isNetworkPath } from "@t3tools/shared/path";
17import * as Context from "effect/Context";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Path from "effect/Path";
22import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
23import * as Schema from "effect/Schema";
24
25import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
26import * as KnownWorkspaces from "./KnownWorkspaces.ts";
27import * as WorkspaceEntries from "./WorkspaceEntries.ts";
28import * as WorkspacePaths from "./WorkspacePaths.ts";
29import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
30import { toWslDrivePath } from "./wslDrivePath.ts";
31
32const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
33
34// NTFS reaches .git through trailing dots/spaces, stream suffixes and GIT~1; compare uppercased names.
35const isGitMetadataName = (segment: string) => {
36 const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
37 return name === ".GIT" || name === "GIT~1";
38};
39
40export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
41 "WorkspaceFileSystemOperationError",
42 {
43 workspaceRoot: Schema.String,
44 relativePath: Schema.String,
45 resolvedPath: Schema.String,
46 operationPath: Schema.String,
47 operation: Schema.Literals([
48 "realpath-workspace-root",
49 "realpath-target",
50 "open",
51 "stat",
52 "read",
53 "close",
54 "make-directory",
55 "write-file",
56 ]),
57 cause: Schema.Defect(),
58 },
59) {
60 override get message(): string {
61 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
62 }
63}
64
65export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
66 "WorkspaceFilePathEscapeError",
67 {
68 workspaceRoot: Schema.String,
69 relativePath: Schema.String,
70 resolvedWorkspaceRoot: Schema.String,
71 resolvedPath: Schema.String,
72 },
73) {
74 override get message(): string {
75 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
76 }
77}
78
79export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
80 "WorkspacePathNotFileError",
81 {
82 workspaceRoot: Schema.String,
83 relativePath: Schema.String,
84 resolvedPath: Schema.String,
85 },
86) {
87 override get message(): string {
88 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
89 }
90}
91
92export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
93 "WorkspaceBinaryFileError",
94 {
95 workspaceRoot: Schema.String,
96 relativePath: Schema.String,
97 resolvedPath: Schema.String,
98 },
99) {
100 override get message(): string {
101 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
102 }
103}
104
105export const WorkspaceFileSystemError = Schema.Union([
106 WorkspaceFileSystemOperationError,
107 WorkspaceFilePathEscapeError,
108 WorkspacePathNotFileError,
109 WorkspaceBinaryFileError,
110]);
111export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
112
113export class WorkspaceFileSystem extends Context.Service<
114 WorkspaceFileSystem,
115 {
116 readonly getMetadata: (
117 input: FilesystemGetMetadataInput,
118 ) => Effect.Effect<FilesystemGetMetadataResult>;
119
120 readonly readFile: (
121 input: ProjectReadFileInput,
122 ) => Effect.Effect<
123 ProjectReadFileResult,
124 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
125 >;
126 /** Writes inside a known workspace only. */
127 readonly writeFile: (
128 input: ProjectWriteFileInput,
129 ) => Effect.Effect<
130 ProjectWriteFileResult,
131 | WorkspaceFileSystemError
132 | WorkspacePaths.WorkspacePathOutsideRootError
133 | KnownWorkspaces.UnknownWorkspaceError
134 >;
135 }
136>()("t3/workspace/WorkspaceFileSystem") {}
137
138const UTF8_BOM = "\uFEFF";
139
140async function startsWithUtf8Bom(filePath: string): Promise<boolean> {
141 const handle = await NodeFSP.open(
142 filePath,
143 // O_NONBLOCK keeps a FIFO with no writer from hanging the save.
144 NodeFS.constants.O_RDONLY |
145 (NodeFS.constants.O_NOFOLLOW ?? 0) |
146 (NodeFS.constants.O_NONBLOCK ?? 0),
147 ).catch(() => null);
148 if (!handle) return false;
149 try {
150 const { bytesRead, buffer } = await handle.read(Buffer.alloc(3), 0, 3, 0);
151 return bytesRead === 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf;
152 } catch {
153 return false;
154 } finally {
155 await handle.close();
156 }
157}
158
159/** @public */
160export const make = Effect.gen(function* () {
161 const fileSystem = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
164 const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
165 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
166 const isServerInternalPath = yield* makeIsServerInternalPath;
167 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
168
169 const toHostPath = (requestedPath: string) =>
170 toWslDrivePath(requestedPath).pipe(
171 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
172 );
173
174 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
175 const expandedPath = expandHomePath(
176 yield* toHostPath(requestedPath),
177 yield* HostProcess.HomeDirectory,
178 );
179 // Chips ask as soon as an agent's message renders, and touching a network
180 // path makes Windows sign in to its host with the user's NTLM credentials.
181 if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null;
182 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
183 // Server state files answer like missing paths, as readFile refuses them.
184 if (stat._tag === "None" || (yield* isServerInternalPath(expandedPath))) return null;
185 if (stat.value.type === "Directory") return { kind: "directory" } as const;
186 if (stat.value.type !== "File") return { kind: "other" } as const;
187 let mimeType: string | undefined;
188 if (path.extname(expandedPath) === "" && stat.value.size > 0) {
189 mimeType = yield* Effect.tryPromise({
190 try: async () => {
191 const handle = await NodeFSP.open(
192 expandedPath,
193 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
194 );
195 try {
196 if (!(await handle.stat()).isFile()) return undefined;
197 const buffer = Buffer.alloc(512);
198 const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
199 return fileHeaderMimeType(buffer.subarray(0, bytesRead));
200 } finally {
201 await handle.close();
202 }
203 },
204 catch: () => undefined,
205 }).pipe(Effect.orElseSucceed(() => undefined));
206 }
207 return {
208 kind: "file",
209 byteLength: Number(stat.value.size),
210 ...(mimeType === undefined ? {} : { mimeType }),
211 } satisfies FilesystemEntryMetadata;
212 });
213
214 const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
215 "WorkspaceFileSystem.getMetadata",
216 )(function* (input) {
217 const paths = [...new Set(input.paths)];
218 const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
219 const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
220 return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
221 });
222
223 /** Both paths must already be real paths. */
224 const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
225 const relative = path.relative(realWorkspaceRoot, realPath);
226 return !(
227 relative.startsWith(`..${path.sep}`) ||
228 relative === ".." ||
229 path.isAbsolute(relative)
230 );
231 };
232
233 // Reject Git folders, including renamed bare repos whose config/hooks can execute; paths must be normalized.
234 // Stop at linked worktrees' .git files since worktrees can sit inside bare repos.
235 const isInGitFolder = async (absolutePath: string) => {
236 if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
237 for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
238 const [head, commondir, objects, refs, dotGit] = await Promise.all(
239 ["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
240 NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
241 // Any other failure leaves the folder unknown, so the write is refused.
242 if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
243 throw error;
244 }),
245 ),
246 );
247 // Git recognizes HEAD with commondir or objects/refs as a repository.
248 if (head && (commondir || (objects && refs))) return true;
249 if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
250 }
251 };
252
253 /**
254 * Workspace-relative paths must stay inside the root, symlinks included. An
255 * absolute or `~/` path reads a host file in place, such as a report an agent
256 * wrote to a temp directory; it gets no root check. A network path does, since
257 * Windows signs in to its host with the user's NTLM credentials.
258 */
259 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
260 input: ProjectReadFileInput,
261 ) {
262 const requestedPath = input.relativePath;
263 const hostPath =
264 requestedPath.startsWith("~/") || requestedPath.startsWith("~\\")
265 ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
266 : yield* toHostPath(requestedPath);
267 if (
268 isNetworkPath(hostPath) &&
269 !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd))
270 ) {
271 return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
272 workspaceRoot: input.cwd,
273 relativePath: input.relativePath,
274 });
275 }
276 if (path.isAbsolute(hostPath)) {
277 // Native realpath hands Windows a `\\?\` path as written, `..` included,
278 // so a network path must be the resolved one the check above approved.
279 // Others keep POSIX `link/..` semantics, which resolving first would change.
280 const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath;
281 const realTargetPath = yield* Effect.tryPromise({
282 try: () => NodeFSP.realpath(absolutePath),
283 catch: (cause) =>
284 new WorkspaceFileSystemOperationError({
285 workspaceRoot: input.cwd,
286 relativePath: input.relativePath,
287 resolvedPath: absolutePath,
288 operationPath: absolutePath,
289 operation: "realpath-target",
290 cause,
291 }),
292 }).pipe(
293 Effect.catchIf(
294 (error) =>
295 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
296 () => Effect.succeed(null),
297 ),
298 );
299 return { relativePath: requestedPath, realTargetPath };
300 }
301
302 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
303 workspaceRoot: input.cwd,
304 relativePath: input.relativePath,
305 });
306
307 const realWorkspaceRoot = yield* Effect.tryPromise({
308 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
309 catch: (cause) =>
310 new WorkspaceFileSystemOperationError({
311 workspaceRoot: input.cwd,
312 relativePath: input.relativePath,
313 resolvedPath: target.absolutePath,
314 operationPath: input.cwd,
315 operation: "realpath-workspace-root",
316 cause,
317 }),
318 });
319 const resolved = yield* Effect.tryPromise({
320 try: async () => {
321 let candidate = target.absolutePath;
322 for (;;) {
323 try {
324 return {
325 realTargetPath: path.join(
326 await NodeFSP.realpath(candidate),
327 path.relative(candidate, target.absolutePath),
328 ),
329 exists: candidate === target.absolutePath,
330 };
331 } catch (error) {
332 if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") {
333 throw error;
334 }
335 // Like writes, missing reads must check the nearest existing ancestor.
336 // An existing entry that cannot resolve is a dangling link, not absence.
337 const exists = await NodeFSP.lstat(candidate).then(
338 () => true,
339 (cause: NodeJS.ErrnoException) => {
340 if (cause.code !== "ENOENT") throw cause;
341 return false;
342 },
343 );
344 if (exists || path.dirname(candidate) === candidate) throw error;
345 candidate = path.dirname(candidate);
346 }
347 }
348 },
349 catch: (cause) =>
350 new WorkspaceFileSystemOperationError({
351 workspaceRoot: input.cwd,
352 relativePath: input.relativePath,
353 resolvedPath: target.absolutePath,
354 operationPath: target.absolutePath,
355 operation: "realpath-target",
356 cause,
357 }),
358 });
359 if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) {
360 return yield* new WorkspaceFilePathEscapeError({
361 workspaceRoot: input.cwd,
362 relativePath: input.relativePath,
363 resolvedWorkspaceRoot: realWorkspaceRoot,
364 resolvedPath: resolved.realTargetPath,
365 });
366 }
367 return {
368 relativePath: target.relativePath,
369 realTargetPath: resolved.exists ? resolved.realTargetPath : null,
370 };
371 });
372
373 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
374 "WorkspaceFileSystem.readFile",
375 )(function* (input) {
376 const target = yield* resolveReadTarget(input);
377 const absentResult = {
378 relativePath: target.relativePath,
379 contents: "",
380 byteLength: 0,
381 truncated: false,
382 exists: false,
383 };
384 const realTargetPath = target.realTargetPath;
385 if (realTargetPath === null) return absentResult;
386 if (yield* isServerInternalPath(realTargetPath)) {
387 return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
388 workspaceRoot: input.cwd,
389 relativePath: input.relativePath,
390 });
391 }
392
393 return yield* Effect.acquireUseRelease(
394 Effect.tryPromise({
395 // Non-blocking opens prevent FIFO hangs before stat rejects them; Windows lacks the flag.
396 try: () =>
397 NodeFSP.open(
398 realTargetPath,
399 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
400 ),
401 catch: (cause) =>
402 new WorkspaceFileSystemOperationError({
403 workspaceRoot: input.cwd,
404 relativePath: input.relativePath,
405 resolvedPath: realTargetPath,
406 operationPath: realTargetPath,
407 operation: "open",
408 cause,
409 }),
410 }).pipe(
411 Effect.catchIf(
412 (error) =>
413 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
414 () => Effect.succeed(null),
415 ),
416 ),
417 (handle) =>
418 Effect.gen(function* () {
419 if (handle === null) return absentResult;
420 const stat = yield* Effect.tryPromise({
421 try: () => handle.stat(),
422 catch: (cause) =>
423 new WorkspaceFileSystemOperationError({
424 workspaceRoot: input.cwd,
425 relativePath: input.relativePath,
426 resolvedPath: realTargetPath,
427 operationPath: realTargetPath,
428 operation: "stat",
429 cause,
430 }),
431 });
432 if (!stat.isFile()) {
433 return yield* new WorkspacePathNotFileError({
434 workspaceRoot: input.cwd,
435 relativePath: input.relativePath,
436 resolvedPath: realTargetPath,
437 });
438 }
439
440 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
441 const buffer = Buffer.alloc(bytesToRead);
442 let offset = 0;
443 while (offset < bytesToRead) {
444 const { bytesRead } = yield* Effect.tryPromise({
445 try: () => handle.read(buffer, offset, bytesToRead - offset, offset),
446 catch: (cause) =>
447 new WorkspaceFileSystemOperationError({
448 workspaceRoot: input.cwd,
449 relativePath: input.relativePath,
450 resolvedPath: realTargetPath,
451 operationPath: realTargetPath,
452 operation: "read",
453 cause,
454 }),
455 });
456 if (bytesRead <= 0) break;
457 offset += bytesRead;
458 }
459 const fileBytes = buffer.subarray(0, offset);
460 const truncated = stat.size > PROJECT_READ_FILE_MAX_BYTES;
461 const binaryFileError = () =>
462 new WorkspaceBinaryFileError({
463 workspaceRoot: input.cwd,
464 relativePath: input.relativePath,
465 resolvedPath: realTargetPath,
466 });
467 if (fileBytes.includes(0)) return yield* binaryFileError();
468 // Fatal decoding rejects invalid UTF-8, since U+FFFD contents would corrupt the file on save.
469 // Streaming decode drops a character the byte limit split, instead of rejecting it.
470 const contents = yield* Effect.try({
471 try: () =>
472 new TextDecoder("utf-8", { fatal: true }).decode(fileBytes, { stream: truncated }),
473 catch: binaryFileError,
474 });
475 return { relativePath: target.relativePath, contents, byteLength: stat.size, truncated };
476 }),
477 (handle) =>
478 handle === null
479 ? Effect.void
480 : Effect.tryPromise({
481 try: () => handle.close(),
482 catch: (cause) =>
483 new WorkspaceFileSystemOperationError({
484 workspaceRoot: input.cwd,
485 relativePath: input.relativePath,
486 resolvedPath: realTargetPath,
487 operationPath: realTargetPath,
488 operation: "close",
489 cause,
490 }),
491 }),
492 );
493 });
494
495 // Resolve existing ancestors and reject dangling links so creation cannot follow symlinks outside root.
496 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
497 input: ProjectWriteFileInput,
498 ) {
499 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
500 workspaceRoot: input.cwd,
501 relativePath: input.relativePath,
502 });
503 const realWorkspaceRoot = yield* Effect.tryPromise({
504 // Resolve `..` in cwd the way the relative path was resolved, before following links.
505 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
506 catch: (cause) =>
507 new WorkspaceFileSystemOperationError({
508 workspaceRoot: input.cwd,
509 relativePath: input.relativePath,
510 resolvedPath: target.absolutePath,
511 operationPath: input.cwd,
512 operation: "realpath-workspace-root",
513 cause,
514 }),
515 });
516
517 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
518 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
519 const realTargetPath = yield* Effect.tryPromise({
520 try: async () => {
521 for (let depth = segments.length; depth > 0; depth--) {
522 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
523 try {
524 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
525 } catch (error) {
526 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
527 const exists = await NodeFSP.lstat(candidate).then(
528 () => true,
529 () => false,
530 );
531 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
532 }
533 }
534 return path.join(realWorkspaceRoot, ...segments);
535 },
536 catch: (cause) =>
537 new WorkspaceFileSystemOperationError({
538 workspaceRoot: input.cwd,
539 relativePath: input.relativePath,
540 resolvedPath: target.absolutePath,
541 operationPath: target.absolutePath,
542 operation: "realpath-target",
543 cause,
544 }),
545 });
546 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
547 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
548 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
549 Effect.tryPromise({
550 try: () => isInGitFolder(checkedPath),
551 catch: (cause) =>
552 new WorkspaceFileSystemOperationError({
553 workspaceRoot: input.cwd,
554 relativePath: input.relativePath,
555 resolvedPath: realTargetPath,
556 operationPath: checkedPath,
557 operation: "stat",
558 cause,
559 }),
560 }),
561 );
562 if (
563 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
564 (yield* inGitFolder(realTargetPath)) ||
565 (yield* inGitFolder(namedTargetPath))
566 ) {
567 return yield* new WorkspaceFilePathEscapeError({
568 workspaceRoot: input.cwd,
569 relativePath: input.relativePath,
570 resolvedWorkspaceRoot: realWorkspaceRoot,
571 resolvedPath: realTargetPath,
572 });
573 }
574 return { relativePath: target.relativePath, realTargetPath };
575 });
576
577 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
578 "WorkspaceFileSystem.writeFile",
579 )(function* (input) {
580 yield* knownWorkspaces.assertContains(input.cwd);
581 const target = yield* resolveWriteTarget(input);
582 const realTargetPath = target.realTargetPath;
583 const replacesFile = yield* fileSystem
584 .exists(realTargetPath)
585 .pipe(Effect.orElseSucceed(() => false));
586 // readFile decodes the BOM away, so an editor save would otherwise drop it from the file.
587 const keepsBom =
588 replacesFile &&
589 !input.contents.startsWith(UTF8_BOM) &&
590 (yield* Effect.promise(() => startsWithUtf8Bom(realTargetPath)));
591 const contents = keepsBom ? UTF8_BOM + input.contents : input.contents;
592
593 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
594 Effect.mapError(
595 (cause) =>
596 new WorkspaceFileSystemOperationError({
597 workspaceRoot: input.cwd,
598 relativePath: input.relativePath,
599 resolvedPath: realTargetPath,
600 operationPath: path.dirname(realTargetPath),
601 operation: "make-directory",
602 cause,
603 }),
604 ),
605 );
606 yield* Effect.tryPromise({
607 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
608 try: () =>
609 NodeFSP.writeFile(realTargetPath, contents, {
610 flag:
611 NodeFS.constants.O_WRONLY |
612 NodeFS.constants.O_CREAT |
613 NodeFS.constants.O_TRUNC |
614 (NodeFS.constants.O_NOFOLLOW ?? 0),
615 }),
616 catch: (cause) =>
617 new WorkspaceFileSystemOperationError({
618 workspaceRoot: input.cwd,
619 relativePath: input.relativePath,
620 resolvedPath: realTargetPath,
621 operationPath: realTargetPath,
622 operation: "write-file",
623 cause,
624 }),
625 });
626 // Editor autosave overwrites existing files, which leaves the indexed paths unchanged, and
627 // fff's watcher applies the new contents on its own. A forced rescan re-walks the whole
628 // workspace, and the save would wait for it.
629 if (!replacesFile) {
630 yield* workspaceEntries.refresh(input.cwd);
631 }
632 return { relativePath: target.relativePath };
633 });
634
635 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
636});
637
638export const layer = Layer.effect(WorkspaceFileSystem, make);