The best way to control Claude Code, Codex and more from any computer or phone

main
ts 140 lines 4.93 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - FileSystem does not expose no-follow
2 // or non-blocking open flags, and the response must keep the validated descriptor.
3 import * as NodeFS from "node:fs";
4 import * as NodeFSP from "node:fs/promises";
5
6 import * as NodeStream from "@effect/platform-node/NodeStream";
7 import * as Effect from "effect/Effect";
8 import * as Schema from "effect/Schema";
9
10 class MediaFileOpenError extends Schema.TaggedError<MediaFileOpenError>()("MediaFileOpenError", {
11 path: Schema.String,
12 cause: Schema.Defect(),
13 }) {
14 override get message(): string {
15 return `Failed to open media file '${this.path}'.`;
16 }
17 }
18
19 class MediaFileReadError extends Schema.TaggedError<MediaFileReadError>()("MediaFileReadError", {
20 path: Schema.String,
21 cause: Schema.Defect(),
22 }) {
23 override get message(): string {
24 return `Failed to read media file '${this.path}'.`;
25 }
26 }
27
28 class MediaFileStatError extends Schema.TaggedError<MediaFileStatError>()("MediaFileStatError", {
29 path: Schema.String,
30 cause: Schema.Defect(),
31 }) {
32 override get message(): string {
33 return `Failed to read metadata for media file '${this.path}'.`;
34 }
35 }
36
37 export interface OpenMediaFile {
38 readonly handle: NodeFSP.FileHandle;
39 readonly info: NodeFS.BigIntStats;
40 }
41
42 const realpathLikeFileSystem = (filePath: string) =>
43 new Promise<string>((resolve, reject) => {
44 NodeFS.realpath(filePath, (error, resolved) => (error ? reject(error) : resolve(resolved)));
45 });
46
47 export const openMediaFile = Effect.fn("openMediaFile")(function* (
48 filePath: string,
49 identity?: { readonly device: string; readonly inode: string },
50 ) {
51 return yield* Effect.acquireRelease(
52 Effect.tryPromise({
53 try: async () => {
54 const before = await NodeFSP.lstat(filePath, { bigint: true });
55 if (!before.isFile() || before.ino === 0n) return null;
56 if (
57 identity &&
58 (before.dev.toString() !== identity.device || before.ino.toString() !== identity.inode)
59 ) {
60 return null;
61 }
62
63 // Windows lacks these flags; the descriptor/path identity checks still apply.
64 const handle = await NodeFSP.open(
65 filePath,
66 NodeFS.constants.O_RDONLY |
67 (NodeFS.constants.O_NOFOLLOW ?? 0) |
68 (NodeFS.constants.O_NONBLOCK ?? 0),
69 );
70 let accepted = false;
71 try {
72 const info = await handle.stat({ bigint: true });
73 if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) return null;
74 if (
75 identity &&
76 (info.dev.toString() !== identity.device || info.ino.toString() !== identity.inode)
77 ) {
78 return null;
79 }
80 // Match FileSystem.realPath's JS behavior; native realpath expands Windows 8.3 names too.
81 if ((await realpathLikeFileSystem(filePath)) !== filePath) return null;
82 const after = await NodeFSP.lstat(filePath, { bigint: true });
83 if (!after.isFile() || info.dev !== after.dev || info.ino !== after.ino) return null;
84 accepted = true;
85 return { handle, info } satisfies OpenMediaFile;
86 } finally {
87 if (!accepted) await handle.close();
88 }
89 },
90 catch: (cause) => new MediaFileOpenError({ path: filePath, cause }),
91 }),
92 (file) => (file ? Effect.promise(() => file.handle.close()) : Effect.void),
93 );
94 });
95
96 /** Identity, size and nanosecond times, so it moves whenever the file is edited or replaced. */
97 export const mediaFileRevision = (info: NodeFS.BigIntStats) =>
98 `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
99
100 /** Follows links, as serving the path does. Null when nothing can be read there. */
101 export const readFileRevision = (filePath: string) =>
102 Effect.promise(() =>
103 NodeFSP.stat(filePath, { bigint: true }).then(mediaFileRevision, () => null),
104 );
105
106 export const readMediaFileHeader = (filePath: string, file: OpenMediaFile, byteCount: number) =>
107 Effect.tryPromise({
108 try: async () => {
109 const buffer = new Uint8Array(byteCount);
110 const { bytesRead } = await file.handle.read(buffer, 0, byteCount, 0);
111 return buffer.subarray(0, bytesRead);
112 },
113 catch: (cause) => new MediaFileReadError({ path: filePath, cause }),
114 });
115
116 export const statMediaFile = Effect.fn("statMediaFile")(function* (
117 filePath: string,
118 file: OpenMediaFile,
119 ) {
120 return yield* Effect.tryPromise({
121 try: () => file.handle.stat({ bigint: true }),
122 catch: (cause) => new MediaFileStatError({ path: filePath, cause }),
123 });
124 });
125
126 export const streamMediaFile = (file: OpenMediaFile, offset: bigint, bytesToRead: bigint) => {
127 const start = Number(offset);
128 const end = Number(offset + bytesToRead - 1n);
129 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
130 return null;
131 }
132 return NodeStream.fromReadable<Uint8Array>({
133 evaluate: () =>
134 file.handle.createReadStream({
135 autoClose: false,
136 start,
137 end,
138 }),
139 });
140 };