Open History to see the last commit
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 FileSystem from "effect/FileSystem";
14import * as Hash from "effect/Hash";
15import * as Layer from "effect/Layer";
16import * as Logger from "effect/Logger";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag } from "effect/cli";
21import { ChildProcess } from "effect/process";
22
23import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
24import { loadRepoEnv } from "./lib/public-config.ts";
25
26Object.assign(process.env, loadRepoEnv());
27
28const BASE_SERVER_PORT = 13773;
29const BASE_WEB_PORT = 5733;
30const MAX_HASH_OFFSET = 3000;
31const MAX_PORT = 65535;
32const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
33// HTTP(S) requests to these ports are blocked by the Fetch standard before a
34// browser reaches the network. Keep the complete list here so explicit or
35// future wider offsets cannot produce a URL that curl accepts but browsers
36// reject. https://fetch.spec.whatwg.org/#port-blocking
37const FETCH_BAD_PORTS = new Set([
38 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,
39 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
40 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
41 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
42 6669, 6679, 6697, 10080,
43]);
44// Dev servers bind loopback, so loopback is the only interface whose
45// availability decides whether we can use a port.
46const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
47// A pruned migrate-dev-db copy is tens of MB; some worktrees hold a full copy
48// of the live database instead.
49const LARGE_DEV_DATABASE_BYTES = 500 * 1024 * 1024;
50
51/**
52 * Loopback and the wildcards qualify; a specific interface (e.g. a LAN IP) does
53 * not — the OS binds only that address and the proxy target goes dark.
54 */
55export function isProxiableBindHost(host: string): boolean {
56 const normalized = host.trim();
57 return (
58 normalized === "" ||
59 normalized === "localhost" ||
60 normalized === "127.0.0.1" ||
61 normalized === "::1" ||
62 normalized === "[::1]" ||
63 normalized === "0.0.0.0" ||
64 normalized === "::" ||
65 normalized === "[::]"
66 );
67}
68
69export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
70 path.join(NodeOS.homedir(), ".t3"),
71);
72
73const MODE_ARGS = {
74 dev: [
75 "run",
76 "--filter=@t3tools/contracts",
77 "--filter=@t3tools/web",
78 "--filter=t3",
79 "--parallel",
80 "dev",
81 ],
82 "dev:server": ["run", "--filter=t3", "dev"],
83 "dev:web": ["run", "--filter=@t3tools/web", "dev"],
84 "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],
85} as const satisfies Record<string, ReadonlyArray<string>>;
86
87type DevMode = keyof typeof MODE_ARGS;
88/**
89 * `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
90 * web port is always loopback.
91 */
92type PortAvailabilityCheck<R = never> = (
93 port: number,
94 role?: "server" | "web",
95) => Effect.Effect<boolean, never, R>;
96
97const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
98
99export function isBrowserAllowedPort(port: number): boolean {
100 return !FETCH_BAD_PORTS.has(port);
101}
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 }
113}
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 }
126}
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 }
142}
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 }
158}
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 }
173}
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 }
185}
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" });
256}
257
258const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* (
259 baseDir: string | undefined,
260): Effect.fn.Return<string, never, Path.Path> {
261 const path = yield* Path.Path;
262 const configured = baseDir?.trim();
263
264 if (configured) {
265 return path.resolve(configured);
266 }
267
268 return yield* DEFAULT_T3_HOME;
269});
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;
283}
284
285export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({
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.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
298 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
299 const webPort = BASE_WEB_PORT + webOffset;
300 const configuredBaseDir = t3Home?.trim() || undefined;
301 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
302 const isDesktopMode = mode === "dev:desktop";
303
304 const output: NodeJS.ProcessEnv = {
305 ...baseEnv,
306 PORT: String(webPort),
307 VITE_DEV_SERVER_URL:
308 devUrl?.toString() ??
309 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
310 };
311
312 if (configuredBaseDir !== undefined) {
313 output.T3CODE_HOME = resolvedBaseDir;
314 } else {
315 delete output.T3CODE_HOME;
316 }
317
318 // A dev-runner server is never launcher-managed. When the shell that runs
319 // this script was itself spawned by the machine's managed t3 service (an
320 // agent working inside T3 Code), these leak through and the child server
321 // fails startup with "The service launcher started a different t3 version"
322 // (serviceLauncherClient.ts resolveStartup).
323 delete output.T3_SERVICE_LAUNCHER_CONTEXT;
324 delete output.T3_BOOT_SERVICE_UNIT;
325
326 if (!isDesktopMode) {
327 output.T3CODE_PORT = String(serverPort);
328 // HOST is Vite's own bind address, and the desktop branch below is the
329 // only place we set it. An inherited one (an exported HOST, a container,
330 // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
331 // its HMR socket to that address — see the `explicitHost` gate in
332 // apps/web/vite.config.ts.
333 delete output.HOST;
334 if (mode === "dev" || mode === "dev:web") {
335 // Browser dev is single-origin: everything (including /ws) is proxied
336 // through Vite, so the client must resolve its backend from
337 // window.location.origin rather than a baked-in localhost URL.
338 delete output.VITE_HTTP_URL;
339 delete output.VITE_WS_URL;
340 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
341 // which merges `.env`/`.env.local` *under* this env, so a developer
342 // with either URL in their `.env` would get it back and silently lose
343 // single-origin mode.
344 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
345 } else {
346 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
347 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
348 delete output.T3CODE_SINGLE_ORIGIN_DEV;
349 }
350 } else {
351 output.T3CODE_PORT = String(serverPort);
352 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
353 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
354 // Desktop pins the renderer to loopback on purpose; an ambient marker
355 // must not make Vite drop those URLs.
356 delete output.T3CODE_SINGLE_ORIGIN_DEV;
357 delete output.T3CODE_MODE;
358 delete output.T3CODE_NO_BROWSER;
359 delete output.T3CODE_HOST;
360 delete output.T3CODE_DEV_AUTH_TOKEN;
361 }
362
363 if (!isDesktopMode && host !== undefined) {
364 output.T3CODE_HOST = host;
365 }
366
367 if (!isDesktopMode) {
368 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
369 }
370
371 if (autoBootstrapProjectFromCwd !== undefined) {
372 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
373 } else {
374 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
375 }
376
377 if (logWebSocketEvents !== undefined) {
378 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
379 } else {
380 delete output.T3CODE_LOG_WS_EVENTS;
381 }
382
383 if (mode === "dev") {
384 output.T3CODE_MODE = "web";
385 delete output.T3CODE_DESKTOP_WS_URL;
386 }
387
388 if (mode === "dev:server" || mode === "dev:web") {
389 output.T3CODE_MODE = "web";
390 delete output.T3CODE_DESKTOP_WS_URL;
391 }
392
393 if (isDesktopMode) {
394 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
395 delete output.T3CODE_DESKTOP_WS_URL;
396 }
397
398 return output;
399});
400
401function portPairForOffset(offset: number): {
402 readonly serverPort: number;
403 readonly webPort: number;
404} {
405 return {
406 serverPort: BASE_SERVER_PORT + offset,
407 webPort: BASE_WEB_PORT + offset,
408 };
409}
410
411export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")(
412 function* <R>(
413 port: number,
414 hosts: ReadonlyArray<string>,
415 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
416 ): Effect.fn.Return<boolean, never, R> {
417 for (const host of hosts) {
418 if (!(yield* canListenOnHost(port, host))) {
419 return false;
420 }
421 }
422
423 return true;
424 },
425);
426
427export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
428 const host = configuredHost?.trim();
429 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
430 return DEV_PORT_PROBE_HOSTS;
431 }
432 return [...DEV_PORT_PROBE_HOSTS, host];
433}
434
435const makeDefaultCheckPortAvailability =
436 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
437 (port, role) =>
438 Effect.gen(function* () {
439 const net = yield* NetService.NetService;
440 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
441 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
442 net.canListenOnHost(candidatePort, host),
443 );
444 });
445
446const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
447
448interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
449 readonly startOffset: number;
450 readonly requireServerPort: boolean;
451 readonly requireWebPort: boolean;
452 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
453}
454
455export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
456 R = NetService.NetService,
457>({
458 startOffset,
459 requireServerPort,
460 requireWebPort,
461 checkPortAvailability,
462}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<number, DevRunnerPortExhaustedError, R> {
463 const checkPort = (checkPortAvailability ??
464 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
465
466 for (let candidate = startOffset; ; candidate += 1) {
467 const { serverPort, webPort } = portPairForOffset(candidate);
468 const serverPortOutOfRange = serverPort > MAX_PORT;
469 const webPortOutOfRange = webPort > MAX_PORT;
470
471 if (
472 (requireServerPort && serverPortOutOfRange) ||
473 (requireWebPort && webPortOutOfRange) ||
474 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
475 ) {
476 break;
477 }
478
479 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
480 continue;
481 }
482
483 const checks: Array<Effect.Effect<boolean, never, R>> = [];
484 if (requireServerPort) {
485 checks.push(checkPort(serverPort, "server"));
486 }
487 if (requireWebPort) {
488 checks.push(checkPort(webPort, "web"));
489 }
490
491 if (checks.length === 0) {
492 return candidate;
493 }
494
495 const availability = yield* Effect.all(checks);
496 if (availability.every(Boolean)) {
497 return candidate;
498 }
499 }
500
501 return yield* new DevRunnerPortExhaustedError({
502 startOffset,
503 requireServerPort,
504 requireWebPort,
505 baseServerPort: BASE_SERVER_PORT,
506 baseWebPort: BASE_WEB_PORT,
507 maximumPort: MAX_PORT,
508 });
509});
510
511interface ResolveModePortOffsetsInput<R = NetService.NetService> {
512 readonly mode: DevMode;
513 readonly startOffset: number;
514 readonly hasExplicitServerPort: boolean;
515 readonly hasExplicitDevUrl: boolean;
516 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
517}
518
519export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
520 R = NetService.NetService,
521>({
522 mode,
523 startOffset,
524 hasExplicitServerPort,
525 hasExplicitDevUrl,
526 checkPortAvailability,
527}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
528 { readonly serverOffset: number; readonly webOffset: number },
529 DevRunnerPortExhaustedError,
530 R
531> {
532 const checkPort = (checkPortAvailability ??
533 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
534
535 if (mode === "dev:web") {
536 if (hasExplicitDevUrl) {
537 return { serverOffset: startOffset, webOffset: startOffset };
538 }
539
540 const webOffset = yield* findFirstAvailableOffset({
541 startOffset,
542 requireServerPort: false,
543 requireWebPort: true,
544 checkPortAvailability: checkPort,
545 });
546 return { serverOffset: startOffset, webOffset };
547 }
548
549 if (mode === "dev:server") {
550 if (hasExplicitServerPort) {
551 return { serverOffset: startOffset, webOffset: startOffset };
552 }
553
554 const serverOffset = yield* findFirstAvailableOffset({
555 startOffset,
556 requireServerPort: true,
557 requireWebPort: false,
558 checkPortAvailability: checkPort,
559 });
560 return { serverOffset, webOffset: serverOffset };
561 }
562
563 const sharedOffset = yield* findFirstAvailableOffset({
564 startOffset,
565 requireServerPort: !hasExplicitServerPort,
566 requireWebPort: !hasExplicitDevUrl,
567 checkPortAvailability: checkPort,
568 });
569
570 return { serverOffset: sharedOffset, webOffset: sharedOffset };
571});
572
573/** Best effort: a failed first-start step warns, and dev still starts. */
574const runRepoScript = Effect.fn("dev-runner.runRepoScript")(function* (
575 script: string,
576 args: ReadonlyArray<string>,
577 env: NodeJS.ProcessEnv,
578) {
579 const path = yield* Path.Path;
580 const repoRoot = path.dirname(import.meta.dirname);
581 const exitCode = yield* ChildProcess.make(
582 yield* HostProcess.ExecutablePath,
583 [path.join(repoRoot, script), ...args],
584 { cwd: repoRoot, stdin: "ignore", stdout: "inherit", stderr: "inherit", env, extendEnv: false },
585 ).pipe(
586 Effect.flatMap((child) => child.exitCode),
587 Effect.scoped,
588 Effect.orElseSucceed(() => -1),
589 );
590 if (exitCode !== 0) {
591 yield* Effect.logWarning(`[dev-runner] ${script} failed; starting anyway.`);
592 }
593});
594
595/**
596 * The first start in a worktree seeds its empty database from the live install
597 * and warms the web dependency cache. Each step checks for its own output, so
598 * later starts skip it.
599 */
600const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (input: {
601 readonly mode: DevMode;
602 readonly seed: boolean;
603 readonly worktreeHome: string | undefined;
604 readonly env: NodeJS.ProcessEnv;
605}) {
606 const fs = yield* FileSystem.FileSystem;
607 const path = yield* Path.Path;
608 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
609
610 if (input.worktreeHome !== undefined && input.mode !== "dev:web") {
611 const stateDir = path.join(input.worktreeHome, "userdata");
612 for (const name of ["statev2.sqlite", "state.sqlite"]) {
613 const file = path.join(stateDir, name);
614 const info = yield* fs.stat(file).pipe(Effect.option);
615 if (Option.isSome(info) && Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) {
616 yield* Effect.logWarning(
617 `[dev-runner] ${file} is ${Math.round(Number(info.value.size) / 1024 / 1024)} MB. With the dev server stopped, \`vp run migrate-dev-db\` rebuilds statev2.sqlite as a small copy of recent data.`,
618 );
619 }
620 }
621 const source = path.join(yield* HostProcess.HomeDirectory, ".t3", "userdata", "statev2.sqlite");
622 // A V1 state.sqlite counts as data too: the server imports it only while
623 // statev2.sqlite is missing, so seeding would hide it.
624 if (
625 input.seed &&
626 !(yield* exists(path.join(stateDir, "statev2.sqlite"))) &&
627 !(yield* exists(path.join(stateDir, "state.sqlite"))) &&
628 (yield* exists(source))
629 ) {
630 yield* Effect.logInfo(
631 `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or T3CODE_DEV_SEED=0 skips this.`,
632 );
633 yield* runRepoScript(
634 "apps/server/scripts/migrate-dev-db.ts",
635 ["--base-dir", input.worktreeHome, "--source", source],
636 input.env,
637 );
638 }
639 }
640
641 const repoRoot = path.dirname(import.meta.dirname);
642 if (
643 input.mode !== "dev:server" &&
644 !(yield* exists(path.join(repoRoot, "apps/web/node_modules/.vite/deps/_metadata.json")))
645 ) {
646 yield* runRepoScript("apps/web/scripts/warm-dep-cache.ts", [], input.env);
647 }
648});
649
650interface DevRunnerCliInput {
651 readonly mode: DevMode;
652 readonly t3Home: string | undefined;
653 readonly browser: boolean | undefined;
654 readonly autoBootstrapProjectFromCwd: boolean | undefined;
655 readonly logWebSocketEvents: boolean | undefined;
656 readonly host: string | undefined;
657 readonly port: number | undefined;
658 readonly devUrl: URL | undefined;
659 readonly dryRun: boolean;
660 readonly share: boolean;
661 readonly seed?: boolean | undefined;
662 readonly runArgs: ReadonlyArray<string>;
663}
664
665export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
666 input: DevRunnerCliInput,
667) {
668 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
669 Effect.mapError(
670 (cause) =>
671 new DevRunnerConfigurationError({
672 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
673 cause,
674 }),
675 ),
676 );
677
678 if (
679 (input.mode === "dev" || input.mode === "dev:web") &&
680 input.host !== undefined &&
681 !isProxiableBindHost(input.host)
682 ) {
683 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
684 }
685
686 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
687
688 const { offset, source } = yield* resolveOffset({
689 portOffset,
690 devInstance,
691 worktreePath,
692 });
693
694 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
695 mode: input.mode,
696 startOffset: offset,
697 hasExplicitServerPort: input.port !== undefined,
698 hasExplicitDevUrl: input.devUrl !== undefined,
699 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
700 });
701
702 const hostEnvironment = yield* HostProcess.Environment;
703 // A dev server started inside a worktree defaults to that worktree's own
704 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
705 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
706 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
707 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
708 // as one would skip the worktree default and land on the shared home —
709 // exactly the outcome this precedence exists to prevent.
710 const resolvedT3Home =
711 (input.t3Home?.trim() || undefined) ??
712 worktreeHome ??
713 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
714 const env = yield* createDevRunnerEnv({
715 mode: input.mode,
716 baseEnv: hostEnvironment,
717 serverOffset,
718 webOffset,
719 t3Home: resolvedT3Home,
720 browser: input.browser,
721 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
722 logWebSocketEvents: input.logWebSocketEvents,
723 host: input.host,
724 port: input.port,
725 devUrl: input.devUrl,
726 });
727
728 const selectionSuffix =
729 serverOffset !== offset || webOffset !== offset
730 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
731 : "";
732 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
733
734 yield* Effect.logInfo(
735 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
736 );
737
738 // Before the share block: --dry-run only resolves and prints. Sharing would
739 // replace, then tear down, whatever mapping the port already had — a
740 // surprising side effect from a command documented as inert.
741 if (input.dryRun) {
742 return;
743 }
744
745 const sharedWebPort = BASE_WEB_PORT + webOffset;
746 if (input.share) {
747 if (input.mode === "dev:server") {
748 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
749 } else if (input.mode === "dev:desktop") {
750 yield* Effect.logWarning(
751 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
752 );
753 } else {
754 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
755 // process (and reboots), so the cleanup has to be registered atomically
756 // with creating it. An interrupt landing in between would otherwise
757 // leave a mapping pointing at a port nothing is listening on.
758 const shared = yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () =>
759 unshareDevServer(sharedWebPort).pipe(
760 Effect.flatMap((result) =>
761 result.cleared
762 ? Effect.void
763 : Effect.logWarning(
764 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
765 result.explanation ? `: ${result.explanation}` : ""
766 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
767 ),
768 ),
769 ),
770 ).pipe(
771 Effect.tapError((error: DevShareError) =>
772 Effect.logWarning(
773 `[dev-runner] could not share on the tailnet: ${error.message}${
774 error.hint ? ` — ${error.hint}` : ""
775 }`,
776 ),
777 ),
778 Effect.option,
779 Effect.map(Option.getOrUndefined),
780 );
781
782 if (shared) {
783 // The app is reached from the tailnet origin. Vite already allows
784 // *.ts.net hosts; the backend needs the origin for credentialed
785 // requests that bypass the proxy (desktop renderer, direct calls).
786 env.T3CODE_DEV_ALLOWED_ORIGINS = [
787 env.T3CODE_DEV_ALLOWED_ORIGINS,
788 new URL(shared.url).origin,
789 ]
790 .filter((entry) => entry && entry.length > 0)
791 .join(",");
792 if (input.devUrl === undefined) {
793 env.VITE_DEV_SERVER_URL = shared.url;
794 }
795 // A shared origin serves a remote browser, where unbundled dev's
796 // per-module requests each pay a tailnet round trip — a cold module
797 // graph takes minutes to first paint. Bundled dev collapses that to a
798 // few chunk requests.
799 if (env.T3CODE_BUNDLED_DEV === undefined) {
800 env.T3CODE_BUNDLED_DEV = "1";
801 }
802 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
803 }
804 }
805 }
806
807 // After sharing, so the warm step sees the same bundled-dev env as Vite.
808 yield* prepareFirstStart({
809 mode: input.mode,
810 seed: input.seed !== false,
811 worktreeHome: baseDir === worktreeHome ? worktreeHome : undefined,
812 env,
813 });
814
815 const args = [...MODE_ARGS[input.mode], ...input.runArgs];
816 const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
817 const processContext = {
818 mode: input.mode,
819 executable: "vp" as const,
820 argumentCount: args.length,
821 shell: spawnCommand.shell,
822 } as const;
823 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
824 stdin: "inherit",
825 stdout: "inherit",
826 stderr: "inherit",
827 env,
828 extendEnv: false,
829 shell: spawnCommand.shell,
830 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
831 // reach it directly. Effect defaults to detached: true on non-Windows,
832 // which would put the runner in a new group and require manual forwarding.
833 detached: false,
834 forceKillAfter: "1500 millis",
835 }).pipe(
836 Effect.mapError(
837 (cause) =>
838 new DevRunnerProcessError({
839 ...processContext,
840 operation: "spawn",
841 cause,
842 }),
843 ),
844 );
845
846 const exitCode = yield* child.exitCode.pipe(
847 Effect.mapError(
848 (cause) =>
849 new DevRunnerProcessError({
850 ...processContext,
851 operation: "wait-for-exit",
852 cause,
853 }),
854 ),
855 );
856 if (exitCode !== 0) {
857 return yield* new DevRunnerProcessExitError({
858 ...processContext,
859 exitCode,
860 });
861 }
862});
863
864const devRunnerCli = Command.make("dev-runner", {
865 mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
866 Argument.withDescription("Development mode to run."),
867 ),
868 t3Home: Flag.String("home-dir").pipe(
869 Flag.withDescription(
870 "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.",
871 ),
872 Flag.optional,
873 Flag.map(Option.getOrUndefined),
874 ),
875 browser: Flag.Boolean("browser").pipe(
876 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
877 Flag.withDefault(false),
878 ),
879 autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
880 Flag.withDescription(
881 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
882 ),
883 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
884 ),
885 logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe(
886 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
887 Flag.withAlias("log-ws-events"),
888 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
889 ),
890 host: Flag.String("host").pipe(
891 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
892 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
893 ),
894 port: Flag.Int("port").pipe(
895 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
896 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
897 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
898 ),
899 devUrl: Flag.String("dev-url").pipe(
900 Flag.withSchema(Schema.URLFromString),
901 Flag.withDescription(
902 "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.",
903 ),
904 Flag.optional,
905 Flag.map(Option.getOrUndefined),
906 ),
907 dryRun: Flag.Boolean("dry-run").pipe(
908 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
909 Flag.withDefault(false),
910 ),
911 share: Flag.Boolean("share").pipe(
912 Flag.withDescription(
913 "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.",
914 ),
915 Flag.withDefault(false),
916 ),
917 seed: Flag.Boolean("seed").pipe(
918 Flag.withDescription(
919 "Seed an empty worktree database from ~/.t3 on first start (read-only, via migrate-dev-db). On by default; --no-seed or T3CODE_DEV_SEED=0 skips it.",
920 ),
921 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")),
922 ),
923 runArgs: Argument.String("run-arg").pipe(
924 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
925 Argument.variadic(),
926 ),
927}).pipe(
928 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
929 Command.withHandler((input) => runDevRunnerWithInput(input)),
930);
931
932const cliRuntimeLayer = Layer.mergeAll(
933 Logger.layer([Logger.consolePretty()]),
934 NodeServices.layer,
935 NetService.layer,
936);
937
938if (import.meta.main) {
939 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
940 Effect.scoped,
941 Effect.provide(cliRuntimeLayer),
942 NodeRuntime.runMain,
943 );
944}