@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 06:00 UTC

main
ts 171 lines 6.01 KB
Raw
1 import * as Digest from "effect/crypto/Digest";
2 import * as SecureRandom from "effect/crypto/SecureRandom";
3 import type { Input as DurationInput } from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import type { FileSystem } from "effect/FileSystem";
6 import type { HttpServer } from "effect/http/HttpServer";
7 import type { ServeError } from "effect/http/HttpServerError";
8 import * as Layer from "effect/Layer";
9 import type { Path } from "effect/Path";
10 import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
11 import { defaultTeardown, type Teardown } from "effect/Runtime";
12 import type { WebSocketConstructor } from "effect/socket/Socket";
13 import type { Stdio } from "effect/Stdio";
14 import type { Terminal } from "effect/Terminal";
15 import { disableCrossSpawnChdir } from "./Node.ts";
16
17 const isBun = typeof Bun !== "undefined";
18
19 const importPlatformPeer = <A>(
20 peerDependency: "@effect/platform-bun" | "@effect/platform-node",
21 load: () => Promise<A>,
22 ): Promise<A> =>
23 load().catch(() => {
24 console.error(
25 [
26 `Alchemy could not load the required peer dependency "${peerDependency}".`,
27 `Install a compatible version of "${peerDependency}" in the same project as "alchemy".`,
28 "If it is already installed, you may be running a globally installed Alchemy CLI; run the project-local CLI instead.",
29 ].join("\n"),
30 );
31 process.exit(1);
32 });
33
34 /**
35 * Constructs a layer with different implementations for Bun and Node.
36 */
37 export const platformLayer = <A, E, R>(constructors: {
38 bun: () => Promise<Layer.Layer<A, E, R>>;
39 node: () => Promise<Layer.Layer<A, E, R>>;
40 }) =>
41 Layer.unwrap(
42 Effect.promise(async () => {
43 if (isBun) {
44 return await constructors.bun();
45 } else {
46 return await constructors.node();
47 }
48 }),
49 );
50
51 // effect 4.1 dropped crypto from the platform `*Services` bundles.
52 const WebCryptoServices = Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto);
53
54 export type PlatformServices =
55 | ChildProcessSpawner
56 | Digest.Digest
57 | SecureRandom.SecureRandom
58 | FileSystem
59 | Path
60 | Stdio
61 | Terminal
62 // WebSocketConstructor is not included in NodeServices/BunServices, but required for Workers tail
63 | WebSocketConstructor;
64
65 export const PlatformServices: Layer.Layer<PlatformServices> = platformLayer({
66 bun: async () => {
67 const [BunServices, BunSocket] = await Promise.all([
68 importPlatformPeer("@effect/platform-bun", () => import("@effect/platform-bun/BunServices")),
69 importPlatformPeer("@effect/platform-bun", () => import("@effect/platform-bun/BunSocket")),
70 ]);
71 return Layer.mergeAll(
72 BunServices.layer,
73 BunSocket.layerWebSocketConstructor,
74 WebCryptoServices,
75 );
76 },
77 node: async () => {
78 const [NodeServices, NodeSocket] = await Promise.all([
79 importPlatformPeer(
80 "@effect/platform-node",
81 () => import("@effect/platform-node/NodeServices"),
82 ),
83 importPlatformPeer("@effect/platform-node", () => import("@effect/platform-node/NodeSocket")),
84 ]);
85 return Layer.mergeAll(
86 NodeServices.layer,
87 NodeSocket.layerWebSocketConstructor,
88 WebCryptoServices,
89 );
90 },
91 });
92
93 /**
94 * ALWAYS exit once the main effect completes. The platform `runMain` default
95 * only force-exits on failure or signal interruption — a *successful*
96 * `alchemy deploy`/`destroy` otherwise lingers for ~100 seconds after "Done"
97 * while keep-alive sockets (Cloudflare API agents, provider sidecar handles)
98 * pin the event loop until the remote side closes them. All Effect finalizers
99 * have already run by the time teardown is invoked; the macrotask hop lets
100 * any buffered stdout drain before the process exits.
101 */
102 const exitingTeardown: Teardown = (exit, onExit) => {
103 defaultTeardown(exit, (code) => {
104 const finalCode = code !== 0 ? code : Number(process.exitCode ?? 0) || 0;
105 setTimeout(() => process.exit(finalCode), 0);
106 onExit(finalCode);
107 });
108 };
109
110 export const runMain = <E, A>(
111 effect: Effect.Effect<A, E>,
112 options?: {
113 readonly disableErrorReporting?: boolean | undefined;
114 readonly teardown?: Teardown | undefined;
115 },
116 ): void => {
117 // Every alchemy process (CLI, exec child, sidecar, build/dev runners)
118 // runs concurrent effects that depend on a stable working directory —
119 // forbid cross-spawn's transient process-wide chdir (see Util/Node.ts).
120 disableCrossSpawnChdir();
121 const opts = {
122 ...options,
123 teardown: options?.teardown ?? exitingTeardown,
124 };
125 if (isBun) {
126 void importPlatformPeer(
127 "@effect/platform-bun",
128 () => import("@effect/platform-bun/BunRuntime"),
129 ).then((BunRuntime) => BunRuntime.runMain(effect, opts));
130 } else {
131 void importPlatformPeer(
132 "@effect/platform-node",
133 () => import("@effect/platform-node/NodeRuntime"),
134 ).then((NodeRuntime) => NodeRuntime.runMain(effect, opts));
135 }
136 };
137
138 export const httpServer = (
139 port: number = 0,
140 host: string = "127.0.0.1",
141 options?: {
142 readonly gracefulShutdownTimeout?: DurationInput | undefined;
143 },
144 ): Layer.Layer<HttpServer, ServeError> =>
145 platformLayer({
146 bun: async () => {
147 const BunHttpServer = await importPlatformPeer(
148 "@effect/platform-bun",
149 () => import("@effect/platform-bun/BunHttpServer"),
150 );
151 // `idleTimeout: 0` disables Bun's default 10s request idle timeout.
152 // The RPC spawner serves a long-lived `/logs` stream (sidecar output
153 // forwarded to the exec child's renderer) that can legitimately sit
154 // idle between lines; Bun would otherwise sever it mid-session.
155 return BunHttpServer.layer({ hostname: host, port, idleTimeout: 0 });
156 },
157 node: async () => {
158 const [NodeHttpServer, Http] = await Promise.all([
159 importPlatformPeer(
160 "@effect/platform-node",
161 () => import("@effect/platform-node/NodeHttpServer"),
162 ),
163 import("node:http"),
164 ]);
165 return NodeHttpServer.layerServer(Http.createServer, {
166 host,
167 port,
168 gracefulShutdownTimeout: options?.gracefulShutdownTimeout,
169 });
170 },
171 });