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

dev-runner.ts

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