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