Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import { Command, GlobalFlag } from "effect/cli";
7import * as CliError from "effect/cli/CliError";
8
9import * as ServerConfig from "../config.ts";
10import { awaitLauncherLoss } from "../launcherWatch.ts";
11import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
12import * as ProcessRunner from "../processRunner.ts";
13import * as AutomaticPort from "./automaticPort.ts";
14import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
15
16const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
17
18// The desktop launcher reads this process's stdout and stderr. Once it is gone,
19// every log write fails, and Node turns an unhandled stream error into a crash
20// that skips shutdown and leaves the ownership lock and runtime record behind.
21function ignoreClosedLauncherPipe(error: NodeJS.ErrnoException): void {
22 if (error.code !== "EPIPE" && error.code !== "ERR_STREAM_DESTROYED") throw error;
23}
24
25const runServerCommand = Effect.fn("server.runServerCommand")(function* (
26 flags: CliServerFlags,
27 options?: {
28 readonly startupPresentation?: ServerConfig.StartupPresentation;
29 readonly forceAutoBootstrapProjectFromCwd?: boolean;
30 readonly rejectRunningServer?: boolean;
31 },
32) {
33 // Before config resolution, which claims a port and creates directories.
34 const { runServer } = yield* Effect.promise(() => import("../server.ts"));
35 const logLevel = yield* GlobalFlag.LogLevel;
36 const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer));
37 const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort });
38 const run = runServer.pipe(
39 Effect.provideService(ServerConfig.ServerConfig, config),
40 // Settings' Reclaim stops the server; repair once the database is closed, before the restart.
41 Effect.ensuring(
42 DatabaseMaintenance.runRequestedReclaim(config.dbPath).pipe(
43 Effect.provide(DatabaseMaintenance.layer),
44 ),
45 ),
46 );
47 if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
48 yield* Effect.sync(() => {
49 process.stdout.on("error", ignoreClosedLauncherPipe);
50 process.stderr.on("error", ignoreClosedLauncherPipe);
51 });
52 return yield* Effect.raceFirst(
53 run,
54 awaitLauncherLoss().pipe(
55 // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).
56 Effect.andThen(Effect.interrupt),
57 ),
58 );
59});
60
61export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand")(function* (
62 flags: CliServerFlags,
63) {
64 if (Option.isSome(flags.cwd)) {
65 const cwd = flags.cwd.value.trim();
66 const fs = yield* FileSystem.FileSystem;
67 const platform = yield* HostProcess.Platform;
68 const explicitPath =
69 cwd === "." ||
70 cwd === ".." ||
71 cwd === "~" ||
72 /[/\\]/.test(cwd) ||
73 (platform === "win32" && /^[a-z]:/i.test(cwd));
74 if (!explicitPath && (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")) {
75 return yield* new CliError.UserError({
76 cause: cwd,
77 userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,
78 });
79 }
80 }
81 return yield* runServerCommand(flags, { rejectRunningServer: true });
82});
83
84export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
85 Command.withDescription("Same as `t3`."),
86 Command.unlisted,
87 Command.withHandler((flags) => runServerCommand(flags, { rejectRunningServer: true })),
88);
89
90// Serve never bootstraps a project, so it does not offer the flag that asks for one.
91const { autoBootstrapProjectFromCwd: _, ...serveCommandFlags } = sharedServerCommandFlags;
92
93export const serveCommand = Command.make("serve", serveCommandFlags).pipe(
94 Command.withShortDescription("Run T3 Code in this terminal, with no browser."),
95 Command.withDescription(
96 "Run T3 Code in this terminal without opening a browser, and print pairing details. The background service runs this. To set up access from your other devices, run `t3 up`.",
97 ),
98 Command.withHandler((flags) =>
99 runServerCommand(
100 { ...flags, autoBootstrapProjectFromCwd: Option.none() },
101 {
102 startupPresentation: "headless",
103 forceAutoBootstrapProjectFromCwd: false,
104 },
105 ),
106 ),
107);