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

dev-runner.ts

848 lines28.7 KB

1#!/usr/bin/env node
2​
3import * as NodeOS from "node:os";
4​
5import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as NetService from "@t3tools/shared/Net";
8import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Config from "effect/Config";
12import * as Effect from "effect/Effect";
13import * as Hash from "effect/Hash";
14import * as Layer from "effect/Layer";
15import * as Logger from "effect/Logger";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import { Argument, Command, Flag } from "effect/cli";
20import { ChildProcess } from "effect/process";
21​
22import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
23import { loadRepoEnv } from "./lib/public-config.ts";
24​
25Object.assign(process.env, loadRepoEnv());
26​
27const BASE_SERVER_PORT = 13773;
28const BASE_WEB_PORT = 5733;
29const MAX_HASH_OFFSET = 3000;
30const MAX_PORT = 65535;
31const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
32// HTTP(S) requests to these ports are blocked by the Fetch standard before a
33// browser reaches the network. Keep the complete list here so explicit or
34// future wider offsets cannot produce a URL that curl accepts but browsers
35// reject. https://fetch.spec.whatwg.org/#port-blocking
36const FETCH_BAD_PORTS = new Set([
37 0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
38 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
39 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
40 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
41 6669, 6679, 6697, 10080,
42]);
43// Dev servers bind loopback, so loopback is the only interface whose
44// availability decides whether we can use a port.
45const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
46​
47/**
48 * Loopback and the wildcards qualify; a specific interface (e.g. a LAN IP) does
49 * not — the OS binds only that address and the proxy target goes dark.
50 */
51export function isProxiableBindHost(host: string): boolean {
52 const normalized = host.trim();
53 return (
54 normalized === "" ||
55 normalized === "localhost" ||
56 normalized === "127.0.0.1" ||
57 normalized === "::1" ||
58 normalized === "[::1]" ||
59 normalized === "0.0.0.0" ||
60 normalized === "::" ||
61 normalized === "[::]"
62 );
64​
65export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
66 path.join(NodeOS.homedir(), ".t3"),
67);
68​
69const MODE_ARGS = {
70 dev: [
71 "run",
72 "--filter=@t3tools/contracts",
73 "--filter=@t3tools/web",
74 "--filter=t3",
75 "--parallel",
76 "dev",
77 ],
78 "dev:server": ["run", "--filter=t3", "dev"],
79 "dev:web": ["run", "--filter=@t3tools/web", "dev"],
80 "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],
81} as const satisfies Record<string, ReadonlyArray<string>>;
82​
83type DevMode = keyof typeof MODE_ARGS;
84/**
85 * `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
86 * web port is always loopback.
87 */
88type PortAvailabilityCheck<R = never> = (
89 port: number,
90 role?: "server" | "web",
91) => Effect.Effect<boolean, never, R>;
92​
93const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
94​
95export function isBrowserAllowedPort(port: number): boolean {
96 return !FETCH_BAD_PORTS.has(port);
98​
99export class DevRunnerConfigurationError extends Schema.TaggedError<DevRunnerConfigurationError>()(
100 "DevRunnerConfigurationError",
101 {
102 configKeys: Schema.Array(Schema.String),
103 cause: Schema.Defect(),
104 },
105) {
106 override get message(): string {
107 return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
108 }
110​
111export class DevRunnerInvalidPortOffsetError extends Schema.TaggedError<DevRunnerInvalidPortOffsetError>()(
112 "DevRunnerInvalidPortOffsetError",
113 {
114 configKey: Schema.Literal("T3CODE_PORT_OFFSET"),
115 portOffset: Schema.Number,
116 minimum: Schema.Number,
117 },
118) {
119 override get message(): string {
120 return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
121 }
123​
124export class DevRunnerPortExhaustedError extends Schema.TaggedError<DevRunnerPortExhaustedError>()(
125 "DevRunnerPortExhaustedError",
126 {
127 startOffset: Schema.Number,
128 requireServerPort: Schema.Boolean,
129 requireWebPort: Schema.Boolean,
130 baseServerPort: Schema.Number,
131 baseWebPort: Schema.Number,
132 maximumPort: Schema.Number,
133 },
134) {
135 override get message(): string {
136 return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
137 }
139​
140export class DevRunnerProcessError extends Schema.TaggedError<DevRunnerProcessError>()(
141 "DevRunnerProcessError",
142 {
143 operation: Schema.Literals(["spawn", "wait-for-exit"]),
144 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
145 executable: Schema.Literal("vp"),
146 argumentCount: Schema.Number,
147 shell: Schema.Boolean,
148 cause: Schema.Defect(),
149 },
150) {
151 override get message(): string {
152 return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
153 }
155​
156export class DevRunnerProcessExitError extends Schema.TaggedError<DevRunnerProcessExitError>()(
157 "DevRunnerProcessExitError",
158 {
159 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
160 executable: Schema.Literal("vp"),
161 argumentCount: Schema.Number,
162 shell: Schema.Boolean,
163 exitCode: Schema.Number,
164 },
165) {
166 override get message(): string {
167 return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
168 }
170​
171export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunnerHostNotProxiableError>()(
172 "DevRunnerHostNotProxiableError",
173 {
174 mode: Schema.Literals(["dev", "dev:web"]),
175 host: Schema.String,
176 },
177) {
178 override get message(): string {
179 return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`;
180 }
182​
183const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
184 Config.String(name).pipe(
185 Config.option,
186 Config.map((value) => Option.getOrUndefined(value)),
187 );
188const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
189 Config.Boolean(name).pipe(
190 Config.option,
191 Config.map((value) => Option.getOrUndefined(value)),
192 );
193const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
194 Config.Port(name).pipe(
195 Config.option,
196 Config.map((value) => Option.getOrUndefined(value)),
197 );
198const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
199 Config.Int(name).pipe(
200 Config.option,
201 Config.map((value) => Option.getOrUndefined(value)),
202 );
203const OffsetConfig = Config.all({
204 portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
205 devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
206});
207​
208export function resolveOffset(config: {
209 readonly portOffset: number | undefined;
210 readonly devInstance: string | undefined;
211 readonly worktreePath?: string | undefined;
212}): Effect.Effect<
213 { readonly offset: number; readonly source: string },
214 DevRunnerInvalidPortOffsetError
215> {
216 if (config.portOffset !== undefined) {
217 if (config.portOffset < 0) {
218 return Effect.fail(
219 new DevRunnerInvalidPortOffsetError({
220 configKey: "T3CODE_PORT_OFFSET",
221 portOffset: config.portOffset,
222 minimum: 0,
223 }),
224 );
225 }
226 return Effect.succeed({
227 offset: config.portOffset,
228 source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
229 });
230 }
231​
232 const seed = config.devInstance?.trim();
233 if (seed) {
234 if (/^\d+$/.test(seed)) {
235 return Effect.succeed({
236 offset: Number(seed),
237 source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
238 });
239 }
240​
241 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
242 return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
243 }
244​
245 const worktreePath = config.worktreePath?.trim();
246 if (worktreePath) {
247 const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
248 return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
249 }
250​
251 return Effect.succeed({ offset: 0, source: "default ports" });
253​
254const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* (
255 baseDir: string | undefined,
256): Effect.fn.Return<string, never, Path.Path> {
257 const path = yield* Path.Path;
258 const configured = baseDir?.trim();
259​
260 if (configured) {
261 return path.resolve(configured);
262 }
263​
264 return yield* DEFAULT_T3_HOME;
265});
266​
267interface CreateDevRunnerEnvInput {
268 readonly mode: DevMode;
269 readonly baseEnv: NodeJS.ProcessEnv;
270 readonly serverOffset: number;
271 readonly webOffset: number;
272 readonly t3Home: string | undefined;
273 readonly browser: boolean | undefined;
274 readonly autoBootstrapProjectFromCwd: boolean | undefined;
275 readonly logWebSocketEvents: boolean | undefined;
276 readonly host: string | undefined;
277 readonly port: number | undefined;
278 readonly devUrl: URL | undefined;
280​
281export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({
282 mode,
283 baseEnv,
284 serverOffset,
285 webOffset,
286 t3Home,
287 browser,
288 autoBootstrapProjectFromCwd,
289 logWebSocketEvents,
290 host,
291 port,
292 devUrl,
293}: CreateDevRunnerEnvInput): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
294 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
295 const webPort = BASE_WEB_PORT + webOffset;
296 const configuredBaseDir = t3Home?.trim() || undefined;
297 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
298 const isDesktopMode = mode === "dev:desktop";
299​
300 const output: NodeJS.ProcessEnv = {
301 ...baseEnv,
302 PORT: String(webPort),
303 VITE_DEV_SERVER_URL:
304 devUrl?.toString() ??
305 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
306 };
307​
308 if (configuredBaseDir !== undefined) {
309 output.T3CODE_HOME = resolvedBaseDir;
310 } else {
311 delete output.T3CODE_HOME;
312 }
313​
314 // A dev-runner server is never launcher-managed. When the shell that runs
315 // this script was itself spawned by the machine's managed t3 service (an
316 // agent working inside T3 Code), these leak through and the child server
317 // fails startup with "The service launcher started a different t3 version"
318 // (serviceLauncherClient.ts resolveStartup).
319 delete output.T3_SERVICE_LAUNCHER_CONTEXT;
320 delete output.T3_BOOT_SERVICE_UNIT;
321​
322 if (!isDesktopMode) {
323 output.T3CODE_PORT = String(serverPort);
324 // HOST is Vite's own bind address, and the desktop branch below is the
325 // only place we set it. An inherited one (an exported HOST, a container,
326 // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
327 // its HMR socket to that address — see the `explicitHost` gate in
328 // apps/web/vite.config.ts.
329 delete output.HOST;
330 if (mode === "dev" || mode === "dev:web") {
331 // Browser dev is single-origin: everything (including /ws) is proxied
332 // through Vite, so the client must resolve its backend from
333 // window.location.origin rather than a baked-in localhost URL.
334 delete output.VITE_HTTP_URL;
335 delete output.VITE_WS_URL;
336 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
337 // which merges `.env`/`.env.local` *under* this env, so a developer
338 // with either URL in their `.env` would get it back and silently lose
339 // single-origin mode.
340 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
341 } else {
342 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
343 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
344 delete output.T3CODE_SINGLE_ORIGIN_DEV;
345 }
346 } else {
347 output.T3CODE_PORT = String(serverPort);
348 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
349 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
350 // Desktop pins the renderer to loopback on purpose; an ambient marker
351 // must not make Vite drop those URLs.
352 delete output.T3CODE_SINGLE_ORIGIN_DEV;
353 delete output.T3CODE_MODE;
354 delete output.T3CODE_NO_BROWSER;
355 delete output.T3CODE_HOST;
356 delete output.T3CODE_DEV_AUTH_TOKEN;
357 }
358​
359 if (!isDesktopMode && host !== undefined) {
360 output.T3CODE_HOST = host;
361 }
362​
363 if (!isDesktopMode) {
364 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
365 }
366​
367 if (autoBootstrapProjectFromCwd !== undefined) {
368 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
369 } else {
370 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
371 }
372​
373 if (logWebSocketEvents !== undefined) {
374 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
375 } else {
376 delete output.T3CODE_LOG_WS_EVENTS;
377 }
378​
379 if (mode === "dev") {
380 output.T3CODE_MODE = "web";
381 delete output.T3CODE_DESKTOP_WS_URL;
382 }
383​
384 if (mode === "dev:server" || mode === "dev:web") {
385 output.T3CODE_MODE = "web";
386 delete output.T3CODE_DESKTOP_WS_URL;
387 }
388​
389 if (isDesktopMode) {
390 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
391 delete output.T3CODE_DESKTOP_WS_URL;
392 }
393​
394 return output;
395});
396​
397function portPairForOffset(offset: number): {
398 readonly serverPort: number;
399 readonly webPort: number;
400} {
401 return {
402 serverPort: BASE_SERVER_PORT + offset,
403 webPort: BASE_WEB_PORT + offset,
404 };
406​
407export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")(
408 function* <R>(
409 port: number,
410 hosts: ReadonlyArray<string>,
411 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
412 ): Effect.fn.Return<boolean, never, R> {
413 for (const host of hosts) {
414 if (!(yield* canListenOnHost(port, host))) {
415 return false;
416 }
417 }
418​
419 return true;
420 },
421);
422​
423export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
424 const host = configuredHost?.trim();
425 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
426 return DEV_PORT_PROBE_HOSTS;
427 }
428 return [...DEV_PORT_PROBE_HOSTS, host];
430​
431const makeDefaultCheckPortAvailability =
432 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
433 (port, role) =>
434 Effect.gen(function* () {
435 const net = yield* NetService.NetService;
436 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
437 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
438 net.canListenOnHost(candidatePort, host),
439 );
440 });
441​
442const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
443​
444interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
445 readonly startOffset: number;
446 readonly requireServerPort: boolean;
447 readonly requireWebPort: boolean;
448 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
450​
451export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
452 R = NetService.NetService,
453>({
454 startOffset,
455 requireServerPort,
456 requireWebPort,
457 checkPortAvailability,
458}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<number, DevRunnerPortExhaustedError, R> {
459 const checkPort = (checkPortAvailability ??
460 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
461​
462 for (let candidate = startOffset; ; candidate += 1) {
463 const { serverPort, webPort } = portPairForOffset(candidate);
464 const serverPortOutOfRange = serverPort > MAX_PORT;
465 const webPortOutOfRange = webPort > MAX_PORT;
466​
467 if (
468 (requireServerPort && serverPortOutOfRange) ||
469 (requireWebPort && webPortOutOfRange) ||
470 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
471 ) {
472 break;
473 }
474​
475 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
476 continue;
477 }
478​
479 const checks: Array<Effect.Effect<boolean, never, R>> = [];
480 if (requireServerPort) {
481 checks.push(checkPort(serverPort, "server"));
482 }
483 if (requireWebPort) {
484 checks.push(checkPort(webPort, "web"));
485 }
486​
487 if (checks.length === 0) {
488 return candidate;
489 }
490​
491 const availability = yield* Effect.all(checks);
492 if (availability.every(Boolean)) {
493 return candidate;
494 }
495 }
496​
497 return yield* new DevRunnerPortExhaustedError({
498 startOffset,
499 requireServerPort,
500 requireWebPort,
501 baseServerPort: BASE_SERVER_PORT,
502 baseWebPort: BASE_WEB_PORT,
503 maximumPort: MAX_PORT,
504 });
505});
506​
507interface ResolveModePortOffsetsInput<R = NetService.NetService> {
508 readonly mode: DevMode;
509 readonly startOffset: number;
510 readonly hasExplicitServerPort: boolean;
511 readonly hasExplicitDevUrl: boolean;
512 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
514​
515export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
516 R = NetService.NetService,
517>({
518 mode,
519 startOffset,
520 hasExplicitServerPort,
521 hasExplicitDevUrl,
522 checkPortAvailability,
523}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
524 { readonly serverOffset: number; readonly webOffset: number },
525 DevRunnerPortExhaustedError,
526 R
527> {
528 const checkPort = (checkPortAvailability ??
529 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
530​
531 if (mode === "dev:web") {
532 if (hasExplicitDevUrl) {
533 return { serverOffset: startOffset, webOffset: startOffset };
534 }
535​
536 const webOffset = yield* findFirstAvailableOffset({
537 startOffset,
538 requireServerPort: false,
539 requireWebPort: true,
540 checkPortAvailability: checkPort,
541 });
542 return { serverOffset: startOffset, webOffset };
543 }
544​
545 if (mode === "dev:server") {
546 if (hasExplicitServerPort) {
547 return { serverOffset: startOffset, webOffset: startOffset };
548 }
549​
550 const serverOffset = yield* findFirstAvailableOffset({
551 startOffset,
552 requireServerPort: true,
553 requireWebPort: false,
554 checkPortAvailability: checkPort,
555 });
556 return { serverOffset, webOffset: serverOffset };
557 }
558​
559 const sharedOffset = yield* findFirstAvailableOffset({
560 startOffset,
561 requireServerPort: !hasExplicitServerPort,
562 requireWebPort: !hasExplicitDevUrl,
563 checkPortAvailability: checkPort,
564 });
565​
566 return { serverOffset: sharedOffset, webOffset: sharedOffset };
567});
568​
569interface DevRunnerCliInput {
570 readonly mode: DevMode;
571 readonly t3Home: string | undefined;
572 readonly browser: boolean | undefined;
573 readonly autoBootstrapProjectFromCwd: boolean | undefined;
574 readonly logWebSocketEvents: boolean | undefined;
575 readonly host: string | undefined;
576 readonly port: number | undefined;
577 readonly devUrl: URL | undefined;
578 readonly dryRun: boolean;
579 readonly share: boolean;
580 readonly runArgs: ReadonlyArray<string>;
582​
583export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
584 input: DevRunnerCliInput,
585) {
586 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
587 Effect.mapError(
588 (cause) =>
589 new DevRunnerConfigurationError({
590 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
591 cause,
592 }),
593 ),
594 );
595​
596 if (
597 (input.mode === "dev" || input.mode === "dev:web") &&
598 input.host !== undefined &&
599 !isProxiableBindHost(input.host)
600 ) {
601 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
602 }
603​
604 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
605​
606 const { offset, source } = yield* resolveOffset({
607 portOffset,
608 devInstance,
609 worktreePath,
610 });
611​
612 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
613 mode: input.mode,
614 startOffset: offset,
615 hasExplicitServerPort: input.port !== undefined,
616 hasExplicitDevUrl: input.devUrl !== undefined,
617 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
618 });
619​
620 const hostEnvironment = yield* HostProcess.Environment;
621 // A dev server started inside a worktree defaults to that worktree's own
622 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
623 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
624 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
625 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
626 // as one would skip the worktree default and land on the shared home —
627 // exactly the outcome this precedence exists to prevent.
628 const resolvedT3Home =
629 (input.t3Home?.trim() || undefined) ??
630 worktreeHome ??
631 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
632 const env = yield* createDevRunnerEnv({
633 mode: input.mode,
634 baseEnv: hostEnvironment,
635 serverOffset,
636 webOffset,
637 t3Home: resolvedT3Home,
638 browser: input.browser,
639 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
640 logWebSocketEvents: input.logWebSocketEvents,
641 host: input.host,
642 port: input.port,
643 devUrl: input.devUrl,
644 });
645​
646 const selectionSuffix =
647 serverOffset !== offset || webOffset !== offset
648 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
649 : "";
650 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
651​
652 yield* Effect.logInfo(
653 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
654 );
655​
656 // Before the share block: --dry-run only resolves and prints. Sharing would
657 // replace, then tear down, whatever mapping the port already had — a
658 // surprising side effect from a command documented as inert.
659 if (input.dryRun) {
660 return;
661 }
662​
663 const sharedWebPort = BASE_WEB_PORT + webOffset;
664 if (input.share) {
665 if (input.mode === "dev:server") {
666 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
667 } else if (input.mode === "dev:desktop") {
668 yield* Effect.logWarning(
669 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
670 );
671 } else {
672 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
673 // process (and reboots), so the cleanup has to be registered atomically
674 // with creating it. An interrupt landing in between would otherwise
675 // leave a mapping pointing at a port nothing is listening on.
676 const shared = yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () =>
677 unshareDevServer(sharedWebPort).pipe(
678 Effect.flatMap((result) =>
679 result.cleared
680 ? Effect.void
681 : Effect.logWarning(
682 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
683 result.explanation ? `: ${result.explanation}` : ""
684 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
685 ),
686 ),
687 ),
688 ).pipe(
689 Effect.tapError((error: DevShareError) =>
690 Effect.logWarning(
691 `[dev-runner] could not share on the tailnet: ${error.message}${
692 error.hint ? ` — ${error.hint}` : ""
693 }`,
694 ),
695 ),
696 Effect.option,
697 Effect.map(Option.getOrUndefined),
698 );
699​
700 if (shared) {
701 // The app is reached from the tailnet origin. Vite already allows
702 // *.ts.net hosts; the backend needs the origin for credentialed
703 // requests that bypass the proxy (desktop renderer, direct calls).
704 env.T3CODE_DEV_ALLOWED_ORIGINS = [
705 env.T3CODE_DEV_ALLOWED_ORIGINS,
706 new URL(shared.url).origin,
707 ]
708 .filter((entry) => entry && entry.length > 0)
709 .join(",");
710 if (input.devUrl === undefined) {
711 env.VITE_DEV_SERVER_URL = shared.url;
712 }
713 // A shared origin serves a remote browser, where unbundled dev's
714 // per-module requests each pay a tailnet round trip — a cold module
715 // graph takes minutes to first paint. Bundled dev collapses that to a
716 // few chunk requests.
717 if (env.T3CODE_BUNDLED_DEV === undefined) {
718 env.T3CODE_BUNDLED_DEV = "1";
719 }
720 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
721 }
722 }
723 }
724​
725 const args = [...MODE_ARGS[input.mode], ...input.runArgs];
726 const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
727 const processContext = {
728 mode: input.mode,
729 executable: "vp" as const,
730 argumentCount: args.length,
731 shell: spawnCommand.shell,
732 } as const;
733 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
734 stdin: "inherit",
735 stdout: "inherit",
736 stderr: "inherit",
737 env,
738 extendEnv: false,
739 shell: spawnCommand.shell,
740 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
741 // reach it directly. Effect defaults to detached: true on non-Windows,
742 // which would put the runner in a new group and require manual forwarding.
743 detached: false,
744 forceKillAfter: "1500 millis",
745 }).pipe(
746 Effect.mapError(
747 (cause) =>
748 new DevRunnerProcessError({
749 ...processContext,
750 operation: "spawn",
751 cause,
752 }),
753 ),
754 );
755​
756 const exitCode = yield* child.exitCode.pipe(
757 Effect.mapError(
758 (cause) =>
759 new DevRunnerProcessError({
760 ...processContext,
761 operation: "wait-for-exit",
762 cause,
763 }),
764 ),
765 );
766 if (exitCode !== 0) {
767 return yield* new DevRunnerProcessExitError({
768 ...processContext,
769 exitCode,
770 });
771 }
772});
773​
774const devRunnerCli = Command.make("dev-runner", {
775 mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
776 Argument.withDescription("Development mode to run."),
777 ),
778 t3Home: Flag.String("home-dir").pipe(
779 Flag.withDescription(
780 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.",
781 ),
782 Flag.optional,
783 Flag.map(Option.getOrUndefined),
784 ),
785 browser: Flag.Boolean("browser").pipe(
786 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
787 Flag.withDefault(false),
788 ),
789 autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
790 Flag.withDescription(
791 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
792 ),
793 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
794 ),
795 logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe(
796 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
797 Flag.withAlias("log-ws-events"),
798 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
799 ),
800 host: Flag.String("host").pipe(
801 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
802 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
803 ),
804 port: Flag.Int("port").pipe(
805 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
806 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
807 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
808 ),
809 devUrl: Flag.String("dev-url").pipe(
810 Flag.withSchema(Schema.URLFromString),
811 Flag.withDescription(
812 "Explicit web dev URL override (forwards to VITE_DEV_SERVER_URL). Ambient VITE_DEV_SERVER_URL values are ignored so a parent dev app cannot redirect the child runner.",
813 ),
814 Flag.optional,
815 Flag.map(Option.getOrUndefined),
816 ),
817 dryRun: Flag.Boolean("dry-run").pipe(
818 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
819 Flag.withDefault(false),
820 ),
821 share: Flag.Boolean("share").pipe(
822 Flag.withDescription(
823 "Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
824 ),
825 Flag.withDefault(false),
826 ),
827 runArgs: Argument.String("run-arg").pipe(
828 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
829 Argument.variadic(),
830 ),
831}).pipe(
832 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
833 Command.withHandler((input) => runDevRunnerWithInput(input)),
834);
835​
836const cliRuntimeLayer = Layer.mergeAll(
837 Logger.layer([Logger.consolePretty()]),
838 NodeServices.layer,
839 NetService.layer,
840);
841​
842if (import.meta.main) {
843 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
844 Effect.scoped,
845 Effect.provide(cliRuntimeLayer),
846 NodeRuntime.runMain,
847 );