The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off |
| 2 | import * as NodeFS from "node:fs"; |
| 3 | import * as NodeFSP from "node:fs/promises"; |
| 4 | |
| 5 | import type { |
| 6 | FilesystemEntryMetadata, |
| 7 | FilesystemGetMetadataInput, |
| 8 | FilesystemGetMetadataResult, |
| 9 | ProjectReadFileInput, |
| 10 | ProjectReadFileResult, |
| 11 | ProjectWriteFileInput, |
| 12 | ProjectWriteFileResult, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; |
| 15 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 16 | import { isNetworkPath } from "@t3tools/shared/path"; |
| 17 | import * as Context from "effect/Context"; |
| 18 | import * as Effect from "effect/Effect"; |
| 19 | import * as FileSystem from "effect/FileSystem"; |
| 20 | import * as Layer from "effect/Layer"; |
| 21 | import * as Path from "effect/Path"; |
| 22 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 23 | import * as Schema from "effect/Schema"; |
| 24 | |
| 25 | import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; |
| 26 | import * as KnownWorkspaces from "./KnownWorkspaces.ts"; |
| 27 | import * as WorkspaceEntries from "./WorkspaceEntries.ts"; |
| 28 | import * as WorkspacePaths from "./WorkspacePaths.ts"; |
| 29 | import { fileHeaderMimeType } from "./fileHeaderMimeType.ts"; |
| 30 | import { toHostDrivePath } from "./hostDrivePath.ts"; |
| 31 | |
| 32 | const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024; |
| 33 | |
| 34 | // NTFS reaches .git through trailing dots/spaces, stream suffixes and GIT~1; compare uppercased names. |
| 35 | const isGitMetadataName = (segment: string) => { |
| 36 | const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase(); |
| 37 | return name === ".GIT" || name === "GIT~1"; |
| 38 | }; |
| 39 | |
| 40 | export 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 | |
| 65 | export 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 | |
| 79 | export 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 | |
| 92 | export 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 | |
| 105 | export const WorkspaceFileSystemError = Schema.Union([ |
| 106 | WorkspaceFileSystemOperationError, |
| 107 | WorkspaceFilePathEscapeError, |
| 108 | WorkspacePathNotFileError, |
| 109 | WorkspaceBinaryFileError, |
| 110 | ]); |
| 111 | export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type; |
| 112 | |
| 113 | export 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 | |
| 138 | const UTF8_BOM = "\uFEFF"; |
| 139 | |
| 140 | async 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 */ |
| 160 | export 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 | * 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 | }).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 }; |
| 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 | if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) { |
| 370 | return yield* new WorkspaceFilePathEscapeError({ |
| 371 | workspaceRoot: input.cwd, |
| 372 | relativePath: input.relativePath, |
| 373 | resolvedWorkspaceRoot: realWorkspaceRoot, |
| 374 | resolvedPath: resolved.realTargetPath, |
| 375 | }); |
| 376 | } |
| 377 | return { |
| 378 | relativePath: target.relativePath, |
| 379 | realTargetPath: resolved.exists ? resolved.realTargetPath : null, |
| 380 | }; |
| 381 | }); |
| 382 | |
| 383 | const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn( |
| 384 | "WorkspaceFileSystem.readFile", |
| 385 | )(function* (input) { |
| 386 | const target = yield* resolveReadTarget(input); |
| 387 | const absentResult = { |
| 388 | relativePath: target.relativePath, |
| 389 | contents: "", |
| 390 | byteLength: 0, |
| 391 | truncated: false, |
| 392 | exists: false, |
| 393 | }; |
| 394 | const realTargetPath = target.realTargetPath; |
| 395 | if (realTargetPath === null) return absentResult; |
| 396 | if (yield* isServerInternalPath(realTargetPath)) { |
| 397 | return yield* new WorkspacePaths.WorkspacePathOutsideRootError({ |
| 398 | workspaceRoot: input.cwd, |
| 399 | relativePath: input.relativePath, |
| 400 | }); |
| 401 | } |
| 402 | |
| 403 | return yield* Effect.acquireUseRelease( |
| 404 | Effect.tryPromise({ |
| 405 | // Non-blocking opens prevent FIFO hangs before stat rejects them; Windows lacks the flag. |
| 406 | try: () => |
| 407 | NodeFSP.open( |
| 408 | realTargetPath, |
| 409 | NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0), |
| 410 | ), |
| 411 | catch: (cause) => |
| 412 | new WorkspaceFileSystemOperationError({ |
| 413 | workspaceRoot: input.cwd, |
| 414 | relativePath: input.relativePath, |
| 415 | resolvedPath: realTargetPath, |
| 416 | operationPath: realTargetPath, |
| 417 | operation: "open", |
| 418 | cause, |
| 419 | }), |
| 420 | }).pipe( |
| 421 | Effect.catchIf( |
| 422 | (error) => |
| 423 | input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT", |
| 424 | () => Effect.succeed(null), |
| 425 | ), |
| 426 | ), |
| 427 | (handle) => |
| 428 | Effect.gen(function* () { |
| 429 | if (handle === null) return absentResult; |
| 430 | const stat = yield* Effect.tryPromise({ |
| 431 | try: () => handle.stat(), |
| 432 | catch: (cause) => |
| 433 | new WorkspaceFileSystemOperationError({ |
| 434 | workspaceRoot: input.cwd, |
| 435 | relativePath: input.relativePath, |
| 436 | resolvedPath: realTargetPath, |
| 437 | operationPath: realTargetPath, |
| 438 | operation: "stat", |
| 439 | cause, |
| 440 | }), |
| 441 | }); |
| 442 | if (!stat.isFile()) { |
| 443 | return yield* new WorkspacePathNotFileError({ |
| 444 | workspaceRoot: input.cwd, |
| 445 | relativePath: input.relativePath, |
| 446 | resolvedPath: realTargetPath, |
| 447 | }); |
| 448 | } |
| 449 | |
| 450 | const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES); |
| 451 | const buffer = Buffer.alloc(bytesToRead); |
| 452 | let offset = 0; |
| 453 | while (offset < bytesToRead) { |
| 454 | const { bytesRead } = yield* Effect.tryPromise({ |
| 455 | try: () => handle.read(buffer, offset, bytesToRead - offset, offset), |
| 456 | catch: (cause) => |
| 457 | new WorkspaceFileSystemOperationError({ |
| 458 | workspaceRoot: input.cwd, |
| 459 | relativePath: input.relativePath, |
| 460 | resolvedPath: realTargetPath, |
| 461 | operationPath: realTargetPath, |
| 462 | operation: "read", |
| 463 | cause, |
| 464 | }), |
| 465 | }); |
| 466 | if (bytesRead <= 0) break; |
| 467 | offset += bytesRead; |
| 468 | } |
| 469 | const fileBytes = buffer.subarray(0, offset); |
| 470 | const truncated = stat.size > PROJECT_READ_FILE_MAX_BYTES; |
| 471 | const binaryFileError = () => |
| 472 | new WorkspaceBinaryFileError({ |
| 473 | workspaceRoot: input.cwd, |
| 474 | relativePath: input.relativePath, |
| 475 | resolvedPath: realTargetPath, |
| 476 | }); |
| 477 | if (fileBytes.includes(0)) return yield* binaryFileError(); |
| 478 | // Fatal decoding rejects invalid UTF-8, since U+FFFD contents would corrupt the file on save. |
| 479 | // Streaming decode drops a character the byte limit split, instead of rejecting it. |
| 480 | const contents = yield* Effect.try({ |
| 481 | try: () => |
| 482 | new TextDecoder("utf-8", { fatal: true }).decode(fileBytes, { stream: truncated }), |
| 483 | catch: binaryFileError, |
| 484 | }); |
| 485 | return { relativePath: target.relativePath, contents, byteLength: stat.size, truncated }; |
| 486 | }), |
| 487 | (handle) => |
| 488 | handle === null |
| 489 | ? Effect.void |
| 490 | : Effect.tryPromise({ |
| 491 | try: () => handle.close(), |
| 492 | catch: (cause) => |
| 493 | new WorkspaceFileSystemOperationError({ |
| 494 | workspaceRoot: input.cwd, |
| 495 | relativePath: input.relativePath, |
| 496 | resolvedPath: realTargetPath, |
| 497 | operationPath: realTargetPath, |
| 498 | operation: "close", |
| 499 | cause, |
| 500 | }), |
| 501 | }), |
| 502 | ); |
| 503 | }); |
| 504 | |
| 505 | // Resolve existing ancestors and reject dangling links so creation cannot follow symlinks outside root. |
| 506 | const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* ( |
| 507 | input: ProjectWriteFileInput, |
| 508 | ) { |
| 509 | const target = yield* workspacePaths.resolveRelativePathWithinRoot({ |
| 510 | workspaceRoot: input.cwd, |
| 511 | relativePath: input.relativePath, |
| 512 | }); |
| 513 | const realWorkspaceRoot = yield* Effect.tryPromise({ |
| 514 | // Resolve `..` in cwd the way the relative path was resolved, before following links. |
| 515 | try: () => NodeFSP.realpath(path.resolve(input.cwd)), |
| 516 | catch: (cause) => |
| 517 | new WorkspaceFileSystemOperationError({ |
| 518 | workspaceRoot: input.cwd, |
| 519 | relativePath: input.relativePath, |
| 520 | resolvedPath: target.absolutePath, |
| 521 | operationPath: input.cwd, |
| 522 | operation: "realpath-workspace-root", |
| 523 | cause, |
| 524 | }), |
| 525 | }); |
| 526 | |
| 527 | // Split the host path, not the display relativePath: on POSIX `\` is a file name character. |
| 528 | const segments = path.relative(input.cwd, target.absolutePath).split(path.sep); |
| 529 | const realTargetPath = yield* Effect.tryPromise({ |
| 530 | try: async () => { |
| 531 | for (let depth = segments.length; depth > 0; depth--) { |
| 532 | const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth)); |
| 533 | try { |
| 534 | return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth)); |
| 535 | } catch (error) { |
| 536 | // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link. |
| 537 | const exists = await NodeFSP.lstat(candidate).then( |
| 538 | () => true, |
| 539 | () => false, |
| 540 | ); |
| 541 | if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error; |
| 542 | } |
| 543 | } |
| 544 | return path.join(realWorkspaceRoot, ...segments); |
| 545 | }, |
| 546 | catch: (cause) => |
| 547 | new WorkspaceFileSystemOperationError({ |
| 548 | workspaceRoot: input.cwd, |
| 549 | relativePath: input.relativePath, |
| 550 | resolvedPath: target.absolutePath, |
| 551 | operationPath: target.absolutePath, |
| 552 | operation: "realpath-target", |
| 553 | cause, |
| 554 | }), |
| 555 | }); |
| 556 | // The path as named is checked too: a `.git/config` symlink resolves away the `.git`. |
| 557 | const namedTargetPath = path.join(realWorkspaceRoot, ...segments); |
| 558 | const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) => |
| 559 | Effect.tryPromise({ |
| 560 | try: () => isInGitFolder(checkedPath), |
| 561 | catch: (cause) => |
| 562 | new WorkspaceFileSystemOperationError({ |
| 563 | workspaceRoot: input.cwd, |
| 564 | relativePath: input.relativePath, |
| 565 | resolvedPath: realTargetPath, |
| 566 | operationPath: checkedPath, |
| 567 | operation: "stat", |
| 568 | cause, |
| 569 | }), |
| 570 | }), |
| 571 | ); |
| 572 | if ( |
| 573 | !isInsideRealRoot(realWorkspaceRoot, realTargetPath) || |
| 574 | (yield* inGitFolder(realTargetPath)) || |
| 575 | (yield* inGitFolder(namedTargetPath)) |
| 576 | ) { |
| 577 | return yield* new WorkspaceFilePathEscapeError({ |
| 578 | workspaceRoot: input.cwd, |
| 579 | relativePath: input.relativePath, |
| 580 | resolvedWorkspaceRoot: realWorkspaceRoot, |
| 581 | resolvedPath: realTargetPath, |
| 582 | }); |
| 583 | } |
| 584 | return { relativePath: target.relativePath, realTargetPath }; |
| 585 | }); |
| 586 | |
| 587 | const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn( |
| 588 | "WorkspaceFileSystem.writeFile", |
| 589 | )(function* (input) { |
| 590 | yield* knownWorkspaces.assertContains(input.cwd); |
| 591 | const target = yield* resolveWriteTarget(input); |
| 592 | const realTargetPath = target.realTargetPath; |
| 593 | const replacesFile = yield* fileSystem |
| 594 | .exists(realTargetPath) |
| 595 | .pipe(Effect.orElseSucceed(() => false)); |
| 596 | // readFile decodes the BOM away, so an editor save would otherwise drop it from the file. |
| 597 | const keepsBom = |
| 598 | replacesFile && |
| 599 | !input.contents.startsWith(UTF8_BOM) && |
| 600 | (yield* Effect.promise(() => startsWithUtf8Bom(realTargetPath))); |
| 601 | const contents = keepsBom ? UTF8_BOM + input.contents : input.contents; |
| 602 | |
| 603 | yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe( |
| 604 | Effect.mapError( |
| 605 | (cause) => |
| 606 | new WorkspaceFileSystemOperationError({ |
| 607 | workspaceRoot: input.cwd, |
| 608 | relativePath: input.relativePath, |
| 609 | resolvedPath: realTargetPath, |
| 610 | operationPath: path.dirname(realTargetPath), |
| 611 | operation: "make-directory", |
| 612 | cause, |
| 613 | }), |
| 614 | ), |
| 615 | ); |
| 616 | yield* Effect.tryPromise({ |
| 617 | // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW. |
| 618 | try: () => |
| 619 | NodeFSP.writeFile(realTargetPath, contents, { |
| 620 | flag: |
| 621 | NodeFS.constants.O_WRONLY | |
| 622 | NodeFS.constants.O_CREAT | |
| 623 | NodeFS.constants.O_TRUNC | |
| 624 | (NodeFS.constants.O_NOFOLLOW ?? 0), |
| 625 | }), |
| 626 | catch: (cause) => |
| 627 | new WorkspaceFileSystemOperationError({ |
| 628 | workspaceRoot: input.cwd, |
| 629 | relativePath: input.relativePath, |
| 630 | resolvedPath: realTargetPath, |
| 631 | operationPath: realTargetPath, |
| 632 | operation: "write-file", |
| 633 | cause, |
| 634 | }), |
| 635 | }); |
| 636 | // Editor autosave overwrites existing files, which leaves the indexed paths unchanged, and |
| 637 | // fff's watcher applies the new contents on its own. A forced rescan re-walks the whole |
| 638 | // workspace, and the save would wait for it. |
| 639 | if (!replacesFile) { |
| 640 | yield* workspaceEntries.refresh(input.cwd); |
| 641 | } |
| 642 | return { relativePath: target.relativePath }; |
| 643 | }); |
| 644 | |
| 645 | return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile }); |
| 646 | }); |
| 647 | |
| 648 | export const layer = Layer.effect(WorkspaceFileSystem, make); |