| 352 | } |
| 353 | |
| 354 | readFileSync( |
| 355 | path: string, |
| 356 | options?: BufferEncoding | { encoding?: BufferEncoding | null } | null, |
| 357 | ): Buffer | string { |
| 358 | const encoding = typeof options === "string" ? options : options?.encoding; |
| 359 | const { path: canonical } = canonicalizePath(path); |
| 360 | const pending = getPendingWriteBufferByPath(this.db, canonical); |
| 361 | if (pending !== undefined) { |
| 362 | const snapshot = Buffer.alloc(pending.size); |
| 363 | snapshot.set(pending.buf.subarray(0, pending.size)); |
| 364 | return encoding ? snapshot.toString(encoding) : snapshot; |
| 365 | } |
| 366 | const node = resolveInode(this.db, path); |
| 367 | if (node === null) { |
| 368 | throw createWorkspaceError("ENOENT", `no such file: ${path}`, path); |
| 369 | } |
| 370 | if (node.type !== "file") { |
| 371 | throw createWorkspaceError("EISDIR", `path is a directory: ${path}`, path); |
| 372 | } |
| 373 | // While a buffer is open for this inode it owns the latest |
| 374 | // bytes; serve from it instead of the chunk store. |
| 375 | const buffered = getWriteBuffer(this.db, node.inode); |
| 376 | if (buffered?.dirty) { |
| 377 | const snapshot = Buffer.alloc(buffered.size); |
| 378 | snapshot.set(buffered.buf.subarray(0, buffered.size)); |
| 379 | return encoding ? snapshot.toString(encoding) : snapshot; |
| 380 | } |
| 381 | const chunks = this.db.all<{ hash: Uint8Array; size: number }>( |
| 382 | "SELECT hash, size FROM vfs_chunks WHERE inode = ? ORDER BY idx", |
| 383 | node.inode, |
| 384 | ); |
| 385 | let total = 0; |
| 386 | for (const c of chunks) total += c.size; |
| 387 | const out = Buffer.alloc(total); |
| 388 | let offset = 0; |
| 389 | for (const chunk of chunks) { |
| 390 | const bytes = getBlobBytes(this.db, chunk.hash); |
| 391 | if (bytes === undefined) { |
| 392 | throw createWorkspaceError("EIO", `missing blob bytes for ${path}`, path); |
| 393 | } |
| 394 | out.set(bytes, offset); |
| 395 | offset += bytes.byteLength; |
| 396 | } |
| 397 | return encoding ? out.toString(encoding) : out; |
| 398 | } |
| 399 | |
| 400 | writeFile( |
| 401 | path: string, |