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

dev-runner.ts

533 lines16.7 KB

1#!/usr/bin/env node
2​
3import { homedir } from "node:os";
4​
5import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { NetService } from "@t3tools/shared/Net";
8import { Config, Data, Effect, Hash, Layer, Logger, Option, Path, Schema } from "effect";
9import { Argument, Command, Flag } from "effect/unstable/cli";
10import { ChildProcess } from "effect/unstable/process";
11​
12const BASE_SERVER_PORT = 13773;
13const BASE_WEB_PORT = 5733;
14const MAX_HASH_OFFSET = 3000;
15const MAX_PORT = 65535;
16const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
17const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
18​
19export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
20 path.join(homedir(), ".t3"),
21);
22​
23const MODE_ARGS = {
24 dev: [
25 "run",
26 "dev",
27 "--ui=tui",
28 "--filter=@t3tools/contracts",
29 "--filter=@t3tools/web",
30 "--filter=t3",
31 "--parallel",
32 ],
33 "dev:server": ["run", "dev", "--filter=t3"],
34 "dev:web": ["run", "dev", "--filter=@t3tools/web"],
35 "dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
36} as const satisfies Record<string, ReadonlyArray<string>>;
37​
38type DevMode = keyof typeof MODE_ARGS;
39type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
40​
41const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
42​
43class DevRunnerError extends Data.TaggedError("DevRunnerError")<{
44 readonly message: string;
45 readonly cause?: unknown;
46}> {}
47​
48const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
49 Config.string(name).pipe(
50 Config.option,
51 Config.map((value) => Option.getOrUndefined(value)),
52 );
53const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
54 Config.boolean(name).pipe(
55 Config.option,
56 Config.map((value) => Option.getOrUndefined(value)),
57 );
58const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
59 Config.port(name).pipe(
60 Config.option,
61 Config.map((value) => Option.getOrUndefined(value)),
62 );
63const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
64 Config.int(name).pipe(
65 Config.option,
66 Config.map((value) => Option.getOrUndefined(value)),
67 );
68const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
69 Config.url(name).pipe(
70 Config.option,
71 Config.map((value) => Option.getOrUndefined(value)),
72 );
73​
74const OffsetConfig = Config.all({
75 portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
76 devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
77});
78​
79export function resolveOffset(config: {
80 readonly portOffset: number | undefined;
81 readonly devInstance: string | undefined;
82}): { readonly offset: number; readonly source: string } {
83 if (config.portOffset !== undefined) {
84 if (config.portOffset < 0) {
85 throw new Error(`Invalid T3CODE_PORT_OFFSET: ${config.portOffset}`);
86 }
87 return {
88 offset: config.portOffset,
89 source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
90 };
91 }
92​
93 const seed = config.devInstance?.trim();
94 if (!seed) {
95 return { offset: 0, source: "default ports" };
96 }
97​
98 if (/^\d+$/.test(seed)) {
99 return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
100 }
101​
102 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
103 return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
105​
106function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
107 return Effect.gen(function* () {
108 const path = yield* Path.Path;
109 const configured = baseDir?.trim();
110​
111 if (configured) {
112 return path.resolve(configured);
113 }
114​
115 return yield* DEFAULT_T3_HOME;
116 });
118​
119interface CreateDevRunnerEnvInput {
120 readonly mode: DevMode;
121 readonly baseEnv: NodeJS.ProcessEnv;
122 readonly serverOffset: number;
123 readonly webOffset: number;
124 readonly t3Home: string | undefined;
125 readonly noBrowser: boolean | undefined;
126 readonly autoBootstrapProjectFromCwd: boolean | undefined;
127 readonly logWebSocketEvents: boolean | undefined;
128 readonly host: string | undefined;
129 readonly port: number | undefined;
130 readonly devUrl: URL | undefined;
132​
133export function createDevRunnerEnv({
134 mode,
135 baseEnv,
136 serverOffset,
137 webOffset,
138 t3Home,
139 noBrowser,
140 autoBootstrapProjectFromCwd,
141 logWebSocketEvents,
142 host,
143 port,
144 devUrl,
145}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
146 return Effect.gen(function* () {
147 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
148 const webPort = BASE_WEB_PORT + webOffset;
149 const resolvedBaseDir = yield* resolveBaseDir(t3Home);
150 const isDesktopMode = mode === "dev:desktop";
151​
152 const output: NodeJS.ProcessEnv = {
153 ...baseEnv,
154 PORT: String(webPort),
155 VITE_DEV_SERVER_URL:
156 devUrl?.toString() ??
157 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
158 T3CODE_HOME: resolvedBaseDir,
159 };
160​
161 if (!isDesktopMode) {
162 output.T3CODE_PORT = String(serverPort);
163 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
164 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
165 } else {
166 output.T3CODE_PORT = String(serverPort);
167 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
168 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
169 delete output.T3CODE_MODE;
170 delete output.T3CODE_NO_BROWSER;
171 delete output.T3CODE_HOST;
172 }
173​
174 if (!isDesktopMode && host !== undefined) {
175 output.T3CODE_HOST = host;
176 }
177​
178 if (!isDesktopMode && noBrowser !== undefined) {
179 output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
180 } else if (!isDesktopMode) {
181 delete output.T3CODE_NO_BROWSER;
182 }
183​
184 if (autoBootstrapProjectFromCwd !== undefined) {
185 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
186 } else {
187 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
188 }
189​
190 if (logWebSocketEvents !== undefined) {
191 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
192 } else {
193 delete output.T3CODE_LOG_WS_EVENTS;
194 }
195​
196 if (mode === "dev") {
197 output.T3CODE_MODE = "web";
198 delete output.T3CODE_DESKTOP_WS_URL;
199 }
200​
201 if (mode === "dev:server" || mode === "dev:web") {
202 output.T3CODE_MODE = "web";
203 delete output.T3CODE_DESKTOP_WS_URL;
204 }
205​
206 if (isDesktopMode) {
207 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
208 delete output.T3CODE_DESKTOP_WS_URL;
209 }
210​
211 return output;
212 });
214​
215function portPairForOffset(offset: number): {
216 readonly serverPort: number;
217 readonly webPort: number;
218} {
219 return {
220 serverPort: BASE_SERVER_PORT + offset,
221 webPort: BASE_WEB_PORT + offset,
222 };
224​
225export function checkPortAvailabilityOnHosts<R>(
226 port: number,
227 hosts: ReadonlyArray<string>,
228 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
229): Effect.Effect<boolean, never, R> {
230 return Effect.gen(function* () {
231 for (const host of hosts) {
232 if (!(yield* canListenOnHost(port, host))) {
233 return false;
234 }
235 }
236​
237 return true;
238 });
240​
241const defaultCheckPortAvailability: PortAvailabilityCheck<NetService> = (port) =>
242 Effect.gen(function* () {
243 const net = yield* NetService;
244 return yield* checkPortAvailabilityOnHosts(port, DEV_PORT_PROBE_HOSTS, (candidatePort, host) =>
245 net.canListenOnHost(candidatePort, host),
246 );
247 });
248​
249interface FindFirstAvailableOffsetInput<R = NetService> {
250 readonly startOffset: number;
251 readonly requireServerPort: boolean;
252 readonly requireWebPort: boolean;
253 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
255​
256export function findFirstAvailableOffset<R = NetService>({
257 startOffset,
258 requireServerPort,
259 requireWebPort,
260 checkPortAvailability,
261}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerError, R> {
262 return Effect.gen(function* () {
263 const checkPort = (checkPortAvailability ??
264 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
265​
266 for (let candidate = startOffset; ; candidate += 1) {
267 const { serverPort, webPort } = portPairForOffset(candidate);
268 const serverPortOutOfRange = serverPort > MAX_PORT;
269 const webPortOutOfRange = webPort > MAX_PORT;
270​
271 if (
272 (requireServerPort && serverPortOutOfRange) ||
273 (requireWebPort && webPortOutOfRange) ||
274 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
275 ) {
276 break;
277 }
278​
279 const checks: Array<Effect.Effect<boolean, never, R>> = [];
280 if (requireServerPort) {
281 checks.push(checkPort(serverPort));
282 }
283 if (requireWebPort) {
284 checks.push(checkPort(webPort));
285 }
286​
287 if (checks.length === 0) {
288 return candidate;
289 }
290​
291 const availability = yield* Effect.all(checks);
292 if (availability.every(Boolean)) {
293 return candidate;
294 }
295 }
296​
297 return yield* new DevRunnerError({
298 message: `No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
299 });
300 });
302​
303interface ResolveModePortOffsetsInput<R = NetService> {
304 readonly mode: DevMode;
305 readonly startOffset: number;
306 readonly hasExplicitServerPort: boolean;
307 readonly hasExplicitDevUrl: boolean;
308 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
310​
311export function resolveModePortOffsets<R = NetService>({
312 mode,
313 startOffset,
314 hasExplicitServerPort,
315 hasExplicitDevUrl,
316 checkPortAvailability,
317}: ResolveModePortOffsetsInput<R>): Effect.Effect<
318 { readonly serverOffset: number; readonly webOffset: number },
319 DevRunnerError,
320 R
321> {
322 return Effect.gen(function* () {
323 const checkPort = (checkPortAvailability ??
324 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
325​
326 if (mode === "dev:web") {
327 if (hasExplicitDevUrl) {
328 return { serverOffset: startOffset, webOffset: startOffset };
329 }
330​
331 const webOffset = yield* findFirstAvailableOffset({
332 startOffset,
333 requireServerPort: false,
334 requireWebPort: true,
335 checkPortAvailability: checkPort,
336 });
337 return { serverOffset: startOffset, webOffset };
338 }
339​
340 if (mode === "dev:server") {
341 if (hasExplicitServerPort) {
342 return { serverOffset: startOffset, webOffset: startOffset };
343 }
344​
345 const serverOffset = yield* findFirstAvailableOffset({
346 startOffset,
347 requireServerPort: true,
348 requireWebPort: false,
349 checkPortAvailability: checkPort,
350 });
351 return { serverOffset, webOffset: serverOffset };
352 }
353​
354 const sharedOffset = yield* findFirstAvailableOffset({
355 startOffset,
356 requireServerPort: !hasExplicitServerPort,
357 requireWebPort: !hasExplicitDevUrl,
358 checkPortAvailability: checkPort,
359 });
360​
361 return { serverOffset: sharedOffset, webOffset: sharedOffset };
362 });
364​
365interface DevRunnerCliInput {
366 readonly mode: DevMode;
367 readonly t3Home: string | undefined;
368 readonly noBrowser: boolean | undefined;
369 readonly autoBootstrapProjectFromCwd: boolean | undefined;
370 readonly logWebSocketEvents: boolean | undefined;
371 readonly host: string | undefined;
372 readonly port: number | undefined;
373 readonly devUrl: URL | undefined;
374 readonly dryRun: boolean;
375 readonly turboArgs: ReadonlyArray<string>;
377​
378export function runDevRunnerWithInput(input: DevRunnerCliInput) {
379 return Effect.gen(function* () {
380 const { portOffset, devInstance } = yield* OffsetConfig.asEffect().pipe(
381 Effect.mapError(
382 (cause) =>
383 new DevRunnerError({
384 message: "Failed to read T3CODE_PORT_OFFSET/T3CODE_DEV_INSTANCE configuration.",
385 cause,
386 }),
387 ),
388 );
389​
390 const { offset, source } = yield* Effect.try({
391 try: () => resolveOffset({ portOffset, devInstance }),
392 catch: (cause) =>
393 new DevRunnerError({
394 message: cause instanceof Error ? cause.message : String(cause),
395 cause,
396 }),
397 });
398​
399 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
400 mode: input.mode,
401 startOffset: offset,
402 hasExplicitServerPort: input.port !== undefined,
403 hasExplicitDevUrl: input.devUrl !== undefined,
404 });
405​
406 const env = yield* createDevRunnerEnv({
407 mode: input.mode,
408 baseEnv: process.env,
409 serverOffset,
410 webOffset,
411 t3Home: input.t3Home,
412 noBrowser: input.noBrowser,
413 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
414 logWebSocketEvents: input.logWebSocketEvents,
415 host: input.host,
416 port: input.port,
417 devUrl: input.devUrl,
418 });
419​
420 const selectionSuffix =
421 serverOffset !== offset || webOffset !== offset
422 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
423 : "";
424​
425 yield* Effect.logInfo(
426 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${String(env.T3CODE_HOME)}`,
427 );
428​
429 if (input.dryRun) {
430 return;
431 }
432​
433 const child = yield* ChildProcess.make(
434 "turbo",
435 [...MODE_ARGS[input.mode], ...input.turboArgs],
436 {
437 stdin: "inherit",
438 stdout: "inherit",
439 stderr: "inherit",
440 env,
441 extendEnv: false,
442 // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
443 shell: process.platform === "win32",
444 // Keep turbo in the same process group so terminal signals (Ctrl+C)
445 // reach it directly. Effect defaults to detached: true on non-Windows,
446 // which would put turbo in a new group and require manual forwarding.
447 detached: false,
448 forceKillAfter: "1500 millis",
449 },
450 );
451​
452 const exitCode = yield* child.exitCode;
453 if (exitCode !== 0) {
454 return yield* new DevRunnerError({
455 message: `turbo exited with code ${exitCode}`,
456 });
457 }
458 }).pipe(
459 Effect.mapError((cause) =>
460 cause instanceof DevRunnerError
461 ? cause
462 : new DevRunnerError({
463 message: cause instanceof Error ? cause.message : "dev-runner failed",
464 cause,
465 }),
466 ),
467 );
469​
470const devRunnerCli = Command.make("dev-runner", {
471 mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
472 Argument.withDescription("Development mode to run."),
473 ),
474 t3Home: Flag.string("home-dir").pipe(
475 Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
476 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
477 ),
478 noBrowser: Flag.boolean("no-browser").pipe(
479 Flag.withDescription("Browser auto-open toggle (equivalent to T3CODE_NO_BROWSER)."),
480 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_NO_BROWSER")),
481 ),
482 autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
483 Flag.withDescription(
484 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
485 ),
486 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
487 ),
488 logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
489 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
490 Flag.withAlias("log-ws-events"),
491 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
492 ),
493 host: Flag.string("host").pipe(
494 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
495 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
496 ),
497 port: Flag.integer("port").pipe(
498 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
499 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
500 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
501 ),
502 devUrl: Flag.string("dev-url").pipe(
503 Flag.withSchema(Schema.URLFromString),
504 Flag.withDescription("Web dev URL override (forwards to VITE_DEV_SERVER_URL)."),
505 Flag.withFallbackConfig(optionalUrlConfig("VITE_DEV_SERVER_URL")),
506 ),
507 dryRun: Flag.boolean("dry-run").pipe(
508 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn turbo."),
509 Flag.withDefault(false),
510 ),
511 turboArgs: Argument.string("turbo-arg").pipe(
512 Argument.withDescription("Additional turbo args (pass after `--`)."),
513 Argument.variadic(),
514 ),
515}).pipe(
516 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
517 Command.withHandler((input) => runDevRunnerWithInput(input)),
518);
519​
520const cliRuntimeLayer = Layer.mergeAll(
521 Logger.layer([Logger.consolePretty()]),
522 NodeServices.layer,
523 NetService.layer,
524);
525​
526const runtimeProgram = Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
527 Effect.scoped,
528 Effect.provide(cliRuntimeLayer),
529);
530​
531if (import.meta.main) {
532 NodeRuntime.runMain(runtimeProgram);