Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

main.ts

321 lines10.5 KB

1/**
2 * CliConfig - CLI/runtime bootstrap service definitions.
3 *
4 * Defines startup-only service contracts used while resolving process config
5 * and constructing server runtime layers.
6 *
7 * @module CliConfig
8 */
9import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
10import { Command, Flag } from "effect/unstable/cli";
11​
12import {
13 DEFAULT_PORT,
14 NetService,
15 resolveStaticDir,
16 ServerConfig,
17 type RuntimeMode,
18 type ServerConfigShape,
19} from "./config";
20import { fixPath, resolveStateDir } from "./os-jank";
21import { Open } from "./open";
22import * as SqlitePersistence from "./persistence/Layers/Sqlite";
23import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
24import { Server } from "./wsServer";
25​
26export class StartupError extends Data.TaggedError("StartupError")<{
27 readonly message: string;
28 readonly cause?: unknown;
29}> {}
30​
31interface CliInput {
32 readonly mode: Option.Option<RuntimeMode>;
33 readonly port: Option.Option<number>;
34 readonly host: Option.Option<string>;
35 readonly stateDir: Option.Option<string>;
36 readonly devUrl: Option.Option<URL>;
37 readonly noBrowser: Option.Option<boolean>;
38 readonly authToken: Option.Option<string>;
39 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
40 readonly logWebSocketEvents: Option.Option<boolean>;
42​
43/**
44 * CliConfigShape - Startup helpers required while building server layers.
45 */
46export interface CliConfigShape {
47 /**
48 * Current process working directory.
49 */
50 readonly cwd: string;
51​
52 /**
53 * Apply OS-specific PATH normalization.
54 */
55 readonly fixPath: Effect.Effect<void>;
56​
57 /**
58 * Resolve static web asset directory for server mode.
59 */
60 readonly resolveStaticDir: Effect.Effect<string | undefined>;
62​
63/**
64 * CliConfig - Service tag for startup CLI/runtime helpers.
65 */
66export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
67 "t3/main/CliConfig",
68) {
69 static readonly layer = Layer.effect(
70 CliConfig,
71 Effect.gen(function* () {
72 const fileSystem = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 return {
75 cwd: process.cwd(),
76 fixPath: Effect.sync(fixPath),
77 resolveStaticDir: resolveStaticDir().pipe(
78 Effect.provideService(FileSystem.FileSystem, fileSystem),
79 Effect.provideService(Path.Path, path),
80 ),
81 } satisfies CliConfigShape;
82 }),
83 );
85​
86const CliEnvConfig = Config.all({
87 mode: Config.string("T3CODE_MODE").pipe(
88 Config.option,
89 Config.map(
90 Option.match<RuntimeMode, string>({
91 onNone: () => "web",
92 onSome: (value) => (value === "desktop" ? "desktop" : "web"),
93 }),
94 ),
95 ),
96 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
97 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
98 stateDir: Config.string("T3CODE_STATE_DIR").pipe(
99 Config.option,
100 Config.map(Option.getOrUndefined),
101 ),
102 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
103 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
104 Config.option,
105 Config.map(Option.getOrUndefined),
106 ),
107 authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
108 Config.option,
109 Config.map(Option.getOrUndefined),
110 ),
111 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
112 Config.option,
113 Config.map(Option.getOrUndefined),
114 ),
115 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
116 Config.option,
117 Config.map(Option.getOrUndefined),
118 ),
119});
120​
121const ServerConfigLive = (input: CliInput) =>
122 Layer.effect(
123 ServerConfig,
124 Effect.gen(function* () {
125 const cliConfig = yield* CliConfig;
126 const { findAvailablePort } = yield* NetService;
127 const env = yield* CliEnvConfig.asEffect().pipe(
128 Effect.mapError(
129 (cause) =>
130 new StartupError({ message: "Failed to read environment configuration", cause }),
131 ),
132 );
133​
134 const mode = Option.getOrElse(input.mode, () => env.mode);
135​
136 const port = yield* Option.match(input.port, {
137 onSome: (value) => Effect.succeed(value),
138 onNone: () => {
139 if (env.port) {
140 return Effect.succeed(env.port);
141 }
142 if (mode === "desktop") {
143 return Effect.succeed(DEFAULT_PORT);
144 }
145 return findAvailablePort(DEFAULT_PORT);
146 },
147 });
148 const stateDir = yield* resolveStateDir(
149 Option.getOrUndefined(input.stateDir) ?? env.stateDir,
150 );
151 const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
152 const noBrowser = Option.match(input.noBrowser, {
153 // effect/cli boolean flags parse to `false` when absent; in that case
154 // we still want env/mode fallbacks to apply.
155 onSome: (value) => (value ? true : (env.noBrowser ?? mode === "desktop")),
156 onNone: () => env.noBrowser ?? mode === "desktop",
157 });
158 const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
159 const autoBootstrapProjectFromCwd = Option.match(input.autoBootstrapProjectFromCwd, {
160 // effect/cli boolean flags parse to `false` when absent; in that case
161 // we still want env/mode fallbacks to apply.
162 onSome: (value) => (value ? true : (env.autoBootstrapProjectFromCwd ?? mode === "web")),
163 onNone: () => env.autoBootstrapProjectFromCwd ?? mode === "web",
164 });
165 const logWebSocketEvents = Option.match(input.logWebSocketEvents, {
166 // effect/cli boolean flags parse to `false` when absent; in that case
167 // we still want env/dev fallbacks to apply.
168 onSome: (value) => (value ? true : (env.logWebSocketEvents ?? Boolean(devUrl))),
169 onNone: () => env.logWebSocketEvents ?? Boolean(devUrl),
170 });
171 const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
172 const { join } = yield* Path.Path;
173 const keybindingsConfigPath = join(stateDir, "keybindings.json");
174 const host =
175 Option.getOrUndefined(input.host) ??
176 env.host ??
177 (mode === "desktop" ? "127.0.0.1" : undefined);
178​
179 return {
180 mode,
181 port,
182 cwd: cliConfig.cwd,
183 keybindingsConfigPath,
184 host,
185 stateDir,
186 staticDir,
187 devUrl,
188 noBrowser,
189 authToken,
190 autoBootstrapProjectFromCwd,
191 logWebSocketEvents,
192 } satisfies ServerConfigShape;
193 }),
194 );
195​
196const LayerLive = (input: CliInput) =>
197 Layer.empty.pipe(
198 Layer.provideMerge(makeServerRuntimeServicesLayer()),
199 Layer.provideMerge(makeServerProviderLayer()),
200 Layer.provideMerge(SqlitePersistence.layerConfig),
201 Layer.provideMerge(ServerConfigLive(input)),
202 );
203​
204const isWildcardHost = (host: string | undefined): boolean =>
205 host === "0.0.0.0" || host === "::" || host === "[::]";
206​
207const formatHostForUrl = (host: string): string =>
208 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
209​
210const makeServerProgram = (input: CliInput) =>
211 Effect.gen(function* () {
212 const cliConfig = yield* CliConfig;
213 const { start, stopSignal } = yield* Server;
214 const openDeps = yield* Open;
215 yield* cliConfig.fixPath;
216​
217 const config = yield* ServerConfig;
218​
219 if (!config.devUrl && !config.staticDir) {
220 yield* Effect.logWarning(
221 "web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
222 {
223 hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
224 },
225 );
226 }
227​
228 yield* start;
229​
230 const localUrl = `http://localhost:${config.port}`;
231 const bindUrl =
232 config.host && !isWildcardHost(config.host)
233 ? `http://${formatHostForUrl(config.host)}:${config.port}`
234 : localUrl;
235 yield* Effect.logInfo("T3 Code running", {
236 url: bindUrl,
237 localUrl,
238 bindHost: config.host ?? "default",
239 cwd: config.cwd,
240 mode: config.mode,
241 stateDir: config.stateDir,
242 authEnabled: Boolean(config.authToken),
243 });
244​
245 if (!config.noBrowser) {
246 const target = config.devUrl?.toString() ?? bindUrl;
247 yield* openDeps.openBrowser(target).pipe(
248 Effect.catch(() =>
249 Effect.logInfo("browser auto-open unavailable", {
250 hint: `Open ${target} in your browser.`,
251 }),
252 ),
253 );
254 }
255​
256 return yield* stopSignal;
257 }).pipe(Effect.provide(LayerLive(input)));
258​
259/**
260 * These flags mirrors the environment variables and the config shape.
261 */
262​
263const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
264 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
265 Flag.optional,
266);
267const portFlag = Flag.integer("port").pipe(
268 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
269 Flag.withDescription("Port for the HTTP/WebSocket server."),
270 Flag.optional,
271);
272const hostFlag = Flag.string("host").pipe(
273 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
274 Flag.optional,
275);
276const stateDirFlag = Flag.string("state-dir").pipe(
277 Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
278 Flag.optional,
279);
280const devUrlFlag = Flag.string("dev-url").pipe(
281 Flag.withSchema(Schema.URLFromString),
282 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
283 Flag.optional,
284);
285const noBrowserFlag = Flag.boolean("no-browser").pipe(
286 Flag.withDescription("Disable automatic browser opening."),
287 Flag.optional,
288);
289const authTokenFlag = Flag.string("auth-token").pipe(
290 Flag.withDescription("Auth token required for WebSocket connections."),
291 Flag.withAlias("token"),
292 Flag.optional,
293);
294const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
295 Flag.withDescription(
296 "Create a project for the current working directory on startup when missing.",
297 ),
298 Flag.optional,
299);
300const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
301 Flag.withDescription(
302 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
303 ),
304 Flag.withAlias("log-ws-events"),
305 Flag.optional,
306);
307​
308export const t3Cli = Command.make("t3", {
309 mode: modeFlag,
310 port: portFlag,
311 host: hostFlag,
312 stateDir: stateDirFlag,
313 devUrl: devUrlFlag,
314 noBrowser: noBrowserFlag,
315 authToken: authTokenFlag,
316 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
317 logWebSocketEvents: logWebSocketEventsFlag,
318}).pipe(
319 Command.withDescription("Run the T3 Code server."),
320 Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
321);