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