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

main
ts 78 lines 2.63 KB
Raw
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import type { SourceFile } from "tsrs/unstable/ast";
6 import { API, formatDiagnostics } from "tsrs/unstable/async";
7
8 export class SyntaxProjectError extends Data.TaggedError("SyntaxProjectError")<{
9 readonly message: string;
10 readonly cause?: unknown;
11 }> {}
12
13 const tryApi = <A>(message: string, evaluate: () => Promise<A>) =>
14 Effect.tryPromise({
15 try: evaluate,
16 catch: (cause) => new SyntaxProjectError({ message, cause }),
17 });
18
19 /**
20 * Native syntax-only project: don't load imports, libraries, or inferred types.
21 * The tsrs API process and its temporary tsconfig live as long as the ambient
22 * `Scope`.
23 */
24 export const createSyntaxProject = Effect.fn("createSyntaxProject")(function* (
25 files: readonly string[],
26 ) {
27 const fs = yield* FileSystem.FileSystem;
28 const path = yield* Path.Path;
29 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-typescript-" });
30 const configPath = path.join(directory, "tsconfig.json");
31 yield* fs.writeFileString(
32 configPath,
33 JSON.stringify({
34 files,
35 compilerOptions: {
36 noResolve: true,
37 noLib: true,
38 types: [],
39 jsx: "preserve",
40 },
41 }),
42 );
43 const api = yield* Effect.acquireRelease(
44 Effect.try({
45 try: () => new API(),
46 catch: (cause) => new SyntaxProjectError({ message: "Failed to start tsrs API", cause }),
47 }),
48 (api) => tryApi("Failed to close tsrs API", () => api.close()).pipe(Effect.ignore),
49 );
50 const snapshot = yield* tryApi(`Failed to open syntax project ${configPath}`, () =>
51 api.createSnapshot({ openProjects: [configPath] }),
52 );
53 const project = snapshot.getConfiguredProject(configPath);
54 if (!project) {
55 return yield* new SyntaxProjectError({
56 message: `Failed to open syntax project ${configPath}`,
57 });
58 }
59 const diagnostics = yield* tryApi("Failed to read syntactic diagnostics", () =>
60 project.program.getSyntacticDiagnostics(),
61 );
62 if (diagnostics.length) {
63 return yield* new SyntaxProjectError({ message: formatDiagnostics(diagnostics, api) });
64 }
65
66 const getSourceFile = (filename: string): Effect.Effect<SourceFile, SyntaxProjectError> =>
67 tryApi(`Failed to read source file ${filename}`, () =>
68 project.program.getSourceFile(filename),
69 ).pipe(
70 Effect.flatMap((sourceFile) =>
71 sourceFile
72 ? Effect.succeed(sourceFile)
73 : Effect.fail(new SyntaxProjectError({ message: `Missing source file ${filename}` })),
74 ),
75 );
76
77 return { api, project, getSourceFile };
78 });