@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 191 lines 7.55 KB
Raw
1 import * as NodeV8 from "node:v8";
2 import { layerRuntime, registerHttpServer } from "@alchemy.run/cloudflare-runtime/core";
3 import { Artifacts, createArtifactStore, makeScopedArtifacts } from "alchemy/Artifacts";
4 import * as RpcServerEnvironment from "alchemy/Local/RpcServerEnvironment";
5 import { PlatformServices, runMain } from "alchemy/Util/PlatformServices";
6 import * as Effect from "effect/Effect";
7 import * as FetchHttpClient from "effect/http/FetchHttpClient";
8 import * as Layer from "effect/Layer";
9 import * as Match from "effect/Match";
10 import * as Stdio from "effect/Stdio";
11 import * as Stream from "effect/Stream";
12 import { CloudflareAuth } from "../Auth/AuthProvider.ts";
13 import * as CloudflareEnvironment from "../CloudflareEnvironment.ts";
14 import * as Credentials from "../Credentials.ts";
15 import { materializeRuntimeBindings } from "./RuntimeBindings.ts";
16 import { loadSource, SourceProviderError } from "./Source.ts";
17 import * as Vite from "./Sources/Vite.ts";
18 import {
19 type ViteChildConfig,
20 VITE_CHILD_READY_PREFIX,
21 VITE_CHILD_READY_SUFFIX,
22 } from "./ViteChild.shared.ts";
23
24 const readConfig = Effect.gen(function* () {
25 const stdio = yield* Stdio.Stdio;
26 const chunks = yield* Stream.runCollect(stdio.stdin);
27 const bytes = Buffer.concat(chunks);
28 // A cross-runtime spawn (bun engine → node child) sends JSON because
29 // bun's `v8.serialize` output is unreadable by real V8. Sniff the
30 // encoding by the JSON marker: only JSON starts with `{` — node's V8
31 // payloads start with 0xFF and bun's JSC serialization with its own
32 // binary header, so same-runtime spawns fall through to deserialize.
33 return (
34 bytes[0] === 0x7b // "{"
35 ? JSON.parse(bytes.toString("utf8"))
36 : NodeV8.deserialize(bytes)
37 ) as ViteChildConfig;
38 });
39
40 const program = Effect.scoped(
41 Effect.gen(function* () {
42 const config = yield* readConfig;
43 const credentials = Credentials.fromAuthProvider().pipe(
44 Layer.provideMerge(CloudflareEnvironment.fromProfile()),
45 Layer.provide(CloudflareAuth),
46 );
47 const runtimeContext = yield* Layer.unwrap(
48 Effect.gen(function* () {
49 const environment = yield* CloudflareEnvironment.CloudflareEnvironment;
50 return layerRuntime({
51 api: { accountId: Effect.map(environment, (env) => env.accountId) },
52 storage: { directory: config.storageDirectory },
53 });
54 }),
55 ).pipe(Layer.provide(Layer.mergeAll(credentials, FetchHttpClient.layer)), Layer.build);
56 // The non-runtime fields are consumed here; everything else in
57 // `config.worker` is the runtime worker shape `viteDev` expects, so new
58 // runtime fields flow through without being re-listed.
59 const {
60 compatibility,
61 main,
62 viteEnvironments,
63 hasAssets,
64 bindingDescriptors,
65 devRemote,
66 devAccess,
67 ...runtimeWorker
68 } = config.worker;
69 const source = config.source;
70 const provider = source
71 ? yield* loadSource(source.descriptor).pipe(
72 // `loadSource` is typed against the full `SourceServices` union
73 // (which includes the per-run Artifacts cache the live provider
74 // supplies); the dev child has no run-scoped cache, so hand the
75 // module a fresh one.
76 Effect.provideService(Artifacts, makeScopedArtifacts(createArtifactStore(), source.fqn)),
77 )
78 : undefined;
79 const bindings = yield* materializeRuntimeBindings(
80 {
81 name: config.worker.name,
82 env: config.env,
83 hasAssets: hasAssets || provider?.devAssetsBinding === true,
84 bindingDescriptors,
85 devRemote,
86 devAccess,
87 },
88 { accountId: config.accountId, selfUrl: config.publicUrl, stack: config.stack },
89 );
90 const viteHost = "127.0.0.1";
91 // `viteDev` resolves `port: 0` per the loaded Vite: a true OS-assigned
92 // random port on Vite >= 8.2.1 (vitejs/vite#23158), a probed ephemeral
93 // port on older Vite.
94 const vitePort = source ? undefined : 0;
95 const url =
96 source && provider
97 ? yield* provider
98 .dev({
99 id: source.id,
100 fqn: source.fqn,
101 workerName: config.worker.name,
102 compatibility,
103 entry: { kind: "external" },
104 stack: config.stack,
105 env: config.env,
106 // Dev hands `env` to the source unresolved; the Worker's own
107 // URL is only substituted into a build's inlined env on deploy.
108 selfUrl: undefined,
109 extraOptions: undefined,
110 assets: source.assets,
111 worker: {
112 bindings,
113 durableObjectNamespaces: config.worker.durableObjectNamespaces,
114 hyperdrives: config.worker.hyperdrives,
115 queueConsumers: Effect.succeed(config.worker.queueConsumers),
116 assets: config.worker.assets,
117 options: {
118 workflows: runtimeWorker.workflows,
119 crons: runtimeWorker.crons,
120 tails: runtimeWorker.tails,
121 streamingTails: runtimeWorker.streamingTails,
122 cache: runtimeWorker.cache,
123 cf: runtimeWorker.cf,
124 zone: runtimeWorker.zone,
125 access: devAccess,
126 workerd: runtimeWorker.workerd,
127 },
128 },
129 runtimeContext,
130 })
131 .pipe(
132 Effect.flatMap((handle) =>
133 Match.value(handle).pipe(
134 Match.when({ mode: "server" }, (handle) =>
135 (handle.serviceBinding === "http"
136 ? registerHttpServer(config.worker.name, handle.url).pipe(
137 Effect.provideContext(runtimeContext),
138 )
139 : Effect.void
140 ).pipe(Effect.as(handle.url.toString())),
141 ),
142 Match.when({ mode: "bundle" }, () =>
143 Effect.fail(
144 new SourceProviderError({
145 provider: source.descriptor.provider,
146 message:
147 "A source declared devMode 'server' but returned a bundle-mode dev handle.",
148 }),
149 ),
150 ),
151 Match.exhaustive,
152 ),
153 ),
154 )
155 : yield* Vite.viteDev(
156 config.rootDir,
157 config.env,
158 {
159 main,
160 compatibilityDate: compatibility.date,
161 compatibilityFlags: compatibility.flags,
162 viteEnvironments,
163 // `dev.access` populates the Worker's native `ctx.access`.
164 worker: {
165 ...runtimeWorker,
166 bindings,
167 publicUrl: config.publicUrl,
168 access: devAccess,
169 },
170 context: runtimeContext,
171 entrypoints: bindingDescriptors.flatMap((binding) =>
172 binding.type === "self_service" && binding.entrypoint ? [binding.entrypoint] : [],
173 ),
174 },
175 { host: viteHost, port: vitePort, strictPort: false },
176 ).pipe(Effect.map((server) => server.resolvedUrls?.local[0]));
177 if (!url) {
178 return yield* Effect.die("Dev server child started without a local URL");
179 }
180 yield* Effect.sync(() => {
181 process.stdout.write(`${VITE_CHILD_READY_PREFIX}${url}${VITE_CHILD_READY_SUFFIX}\n`);
182 });
183 return yield* Effect.never;
184 }),
185 );
186
187 runMain(
188 program.pipe(
189 Effect.provide(RpcServerEnvironment.fromEnv().pipe(Layer.provideMerge(PlatformServices))),
190 ),
191 );