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

dev-runner.ts

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