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

WorkspaceFileSystem.ts

637 lines24.0 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 { 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 }
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 }
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 }
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 }
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 }
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 = requestedPath.startsWith("~/")
264 ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
265 : yield* toHostPath(requestedPath);
266 if (
267 isNetworkPath(hostPath) &&
268 !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd))
269 ) {
270 return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
271 workspaceRoot: input.cwd,
272 relativePath: input.relativePath,
273 });
274 }
275 if (path.isAbsolute(hostPath)) {
276 // Native realpath hands Windows a `\\?\` path as written, `..` included,
277 // so a network path must be the resolved one the check above approved.
278 // Others keep POSIX `link/..` semantics, which resolving first would change.
279 const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath;
280 const realTargetPath = yield* Effect.tryPromise({
281 try: () => NodeFSP.realpath(absolutePath),
282 catch: (cause) =>
283 new WorkspaceFileSystemOperationError({
284 workspaceRoot: input.cwd,
285 relativePath: input.relativePath,
286 resolvedPath: absolutePath,
287 operationPath: absolutePath,
288 operation: "realpath-target",
289 cause,
290 }),
291 }).pipe(
292 Effect.catchIf(
293 (error) =>
294 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
295 () => Effect.succeed(null),
296 ),
297 );
298 return { relativePath: requestedPath, realTargetPath };
299 }
300​
301 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
302 workspaceRoot: input.cwd,
303 relativePath: input.relativePath,
304 });
305​
306 const realWorkspaceRoot = yield* Effect.tryPromise({
307 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
308 catch: (cause) =>
309 new WorkspaceFileSystemOperationError({
310 workspaceRoot: input.cwd,
311 relativePath: input.relativePath,
312 resolvedPath: target.absolutePath,
313 operationPath: input.cwd,
314 operation: "realpath-workspace-root",
315 cause,
316 }),
317 });
318 const resolved = yield* Effect.tryPromise({
319 try: async () => {
320 let candidate = target.absolutePath;
321 for (;;) {
322 try {
323 return {
324 realTargetPath: path.join(
325 await NodeFSP.realpath(candidate),
326 path.relative(candidate, target.absolutePath),
327 ),
328 exists: candidate === target.absolutePath,
329 };
330 } catch (error) {
331 if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") {
332 throw error;
333 }
334 // Like writes, missing reads must check the nearest existing ancestor.
335 // An existing entry that cannot resolve is a dangling link, not absence.
336 const exists = await NodeFSP.lstat(candidate).then(
337 () => true,
338 (cause: NodeJS.ErrnoException) => {
339 if (cause.code !== "ENOENT") throw cause;
340 return false;
341 },
342 );
343 if (exists || path.dirname(candidate) === candidate) throw error;
344 candidate = path.dirname(candidate);
345 }
346 }
347 },
348 catch: (cause) =>
349 new WorkspaceFileSystemOperationError({
350 workspaceRoot: input.cwd,
351 relativePath: input.relativePath,
352 resolvedPath: target.absolutePath,
353 operationPath: target.absolutePath,
354 operation: "realpath-target",
355 cause,
356 }),
357 });
358 if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) {
359 return yield* new WorkspaceFilePathEscapeError({
360 workspaceRoot: input.cwd,
361 relativePath: input.relativePath,
362 resolvedWorkspaceRoot: realWorkspaceRoot,
363 resolvedPath: resolved.realTargetPath,
364 });
365 }
366 return {
367 relativePath: target.relativePath,
368 realTargetPath: resolved.exists ? resolved.realTargetPath : null,
369 };
370 });
371​
372 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
373 "WorkspaceFileSystem.readFile",
374 )(function* (input) {
375 const target = yield* resolveReadTarget(input);
376 const absentResult = {
377 relativePath: target.relativePath,
378 contents: "",
379 byteLength: 0,
380 truncated: false,
381 exists: false,
382 };
383 const realTargetPath = target.realTargetPath;
384 if (realTargetPath === null) return absentResult;
385 if (yield* isServerInternalPath(realTargetPath)) {
386 return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
387 workspaceRoot: input.cwd,
388 relativePath: input.relativePath,
389 });
390 }
391​
392 return yield* Effect.acquireUseRelease(
393 Effect.tryPromise({
394 // Non-blocking opens prevent FIFO hangs before stat rejects them; Windows lacks the flag.
395 try: () =>
396 NodeFSP.open(
397 realTargetPath,
398 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
399 ),
400 catch: (cause) =>
401 new WorkspaceFileSystemOperationError({
402 workspaceRoot: input.cwd,
403 relativePath: input.relativePath,
404 resolvedPath: realTargetPath,
405 operationPath: realTargetPath,
406 operation: "open",
407 cause,
408 }),
409 }).pipe(
410 Effect.catchIf(
411 (error) =>
412 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
413 () => Effect.succeed(null),
414 ),
415 ),
416 (handle) =>
417 Effect.gen(function* () {
418 if (handle === null) return absentResult;
419 const stat = yield* Effect.tryPromise({
420 try: () => handle.stat(),
421 catch: (cause) =>
422 new WorkspaceFileSystemOperationError({
423 workspaceRoot: input.cwd,
424 relativePath: input.relativePath,
425 resolvedPath: realTargetPath,
426 operationPath: realTargetPath,
427 operation: "stat",
428 cause,
429 }),
430 });
431 if (!stat.isFile()) {
432 return yield* new WorkspacePathNotFileError({
433 workspaceRoot: input.cwd,
434 relativePath: input.relativePath,
435 resolvedPath: realTargetPath,
436 });
437 }
438​
439 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
440 const buffer = Buffer.alloc(bytesToRead);
441 let offset = 0;
442 while (offset < bytesToRead) {
443 const { bytesRead } = yield* Effect.tryPromise({
444 try: () => handle.read(buffer, offset, bytesToRead - offset, offset),
445 catch: (cause) =>
446 new WorkspaceFileSystemOperationError({
447 workspaceRoot: input.cwd,
448 relativePath: input.relativePath,
449 resolvedPath: realTargetPath,
450 operationPath: realTargetPath,
451 operation: "read",
452 cause,
453 }),
454 });
455 if (bytesRead <= 0) break;
456 offset += bytesRead;
457 }
458 const fileBytes = buffer.subarray(0, offset);
459 const truncated = stat.size > PROJECT_READ_FILE_MAX_BYTES;
460 const binaryFileError = () =>
461 new WorkspaceBinaryFileError({
462 workspaceRoot: input.cwd,
463 relativePath: input.relativePath,
464 resolvedPath: realTargetPath,
465 });
466 if (fileBytes.includes(0)) return yield* binaryFileError();
467 // Fatal decoding rejects invalid UTF-8, since U+FFFD contents would corrupt the file on save.
468 // Streaming decode drops a character the byte limit split, instead of rejecting it.
469 const contents = yield* Effect.try({
470 try: () =>
471 new TextDecoder("utf-8", { fatal: true }).decode(fileBytes, { stream: truncated }),
472 catch: binaryFileError,
473 });
474 return { relativePath: target.relativePath, contents, byteLength: stat.size, truncated };
475 }),
476 (handle) =>
477 handle === null
478 ? Effect.void
479 : Effect.tryPromise({
480 try: () => handle.close(),
481 catch: (cause) =>
482 new WorkspaceFileSystemOperationError({
483 workspaceRoot: input.cwd,
484 relativePath: input.relativePath,
485 resolvedPath: realTargetPath,
486 operationPath: realTargetPath,
487 operation: "close",
488 cause,
489 }),
490 }),
491 );
492 });
493​
494 // Resolve existing ancestors and reject dangling links so creation cannot follow symlinks outside root.
495 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
496 input: ProjectWriteFileInput,
497 ) {
498 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
499 workspaceRoot: input.cwd,
500 relativePath: input.relativePath,
501 });
502 const realWorkspaceRoot = yield* Effect.tryPromise({
503 // Resolve `..` in cwd the way the relative path was resolved, before following links.
504 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
505 catch: (cause) =>
506 new WorkspaceFileSystemOperationError({
507 workspaceRoot: input.cwd,
508 relativePath: input.relativePath,
509 resolvedPath: target.absolutePath,
510 operationPath: input.cwd,
511 operation: "realpath-workspace-root",
512 cause,
513 }),
514 });
515​
516 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
517 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
518 const realTargetPath = yield* Effect.tryPromise({
519 try: async () => {
520 for (let depth = segments.length; depth > 0; depth--) {
521 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
522 try {
523 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
524 } catch (error) {
525 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
526 const exists = await NodeFSP.lstat(candidate).then(
527 () => true,
528 () => false,
529 );
530 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
531 }
532 }
533 return path.join(realWorkspaceRoot, ...segments);
534 },
535 catch: (cause) =>
536 new WorkspaceFileSystemOperationError({
537 workspaceRoot: input.cwd,
538 relativePath: input.relativePath,
539 resolvedPath: target.absolutePath,
540 operationPath: target.absolutePath,
541 operation: "realpath-target",
542 cause,
543 }),
544 });
545 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
546 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
547 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
548 Effect.tryPromise({
549 try: () => isInGitFolder(checkedPath),
550 catch: (cause) =>
551 new WorkspaceFileSystemOperationError({
552 workspaceRoot: input.cwd,
553 relativePath: input.relativePath,
554 resolvedPath: realTargetPath,
555 operationPath: checkedPath,
556 operation: "stat",
557 cause,
558 }),
559 }),
560 );
561 if (
562 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
563 (yield* inGitFolder(realTargetPath)) ||
564 (yield* inGitFolder(namedTargetPath))
565 ) {
566 return yield* new WorkspaceFilePathEscapeError({
567 workspaceRoot: input.cwd,
568 relativePath: input.relativePath,
569 resolvedWorkspaceRoot: realWorkspaceRoot,
570 resolvedPath: realTargetPath,
571 });
572 }
573 return { relativePath: target.relativePath, realTargetPath };
574 });
575​
576 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
577 "WorkspaceFileSystem.writeFile",
578 )(function* (input) {
579 yield* knownWorkspaces.assertContains(input.cwd);
580 const target = yield* resolveWriteTarget(input);
581 const realTargetPath = target.realTargetPath;
582 const replacesFile = yield* fileSystem
583 .exists(realTargetPath)
584 .pipe(Effect.orElseSucceed(() => false));
585 // readFile decodes the BOM away, so an editor save would otherwise drop it from the file.
586 const keepsBom =
587 replacesFile &&
588 !input.contents.startsWith(UTF8_BOM) &&
589 (yield* Effect.promise(() => startsWithUtf8Bom(realTargetPath)));
590 const contents = keepsBom ? UTF8_BOM + input.contents : input.contents;
591​
592 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
593 Effect.mapError(
594 (cause) =>
595 new WorkspaceFileSystemOperationError({
596 workspaceRoot: input.cwd,
597 relativePath: input.relativePath,
598 resolvedPath: realTargetPath,
599 operationPath: path.dirname(realTargetPath),
600 operation: "make-directory",
601 cause,
602 }),
603 ),
604 );
605 yield* Effect.tryPromise({
606 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
607 try: () =>
608 NodeFSP.writeFile(realTargetPath, contents, {
609 flag:
610 NodeFS.constants.O_WRONLY |
611 NodeFS.constants.O_CREAT |
612 NodeFS.constants.O_TRUNC |
613 (NodeFS.constants.O_NOFOLLOW ?? 0),
614 }),
615 catch: (cause) =>
616 new WorkspaceFileSystemOperationError({
617 workspaceRoot: input.cwd,
618 relativePath: input.relativePath,
619 resolvedPath: realTargetPath,
620 operationPath: realTargetPath,
621 operation: "write-file",
622 cause,
623 }),
624 });
625 // Editor autosave overwrites existing files, which leaves the indexed paths unchanged, and
626 // fff's watcher applies the new contents on its own. A forced rescan re-walks the whole
627 // workspace, and the save would wait for it.
628 if (!replacesFile) {
629 yield* workspaceEntries.refresh(input.cwd);
630 }
631 return { relativePath: target.relativePath };
632 });
633​
634 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
635});
636​
637export const layer = Layer.effect(WorkspaceFileSystem, make);