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

server.ts

92 lines4.0 KB

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 ProcessRunner from "../processRunner.ts";
12import * as AutomaticPort from "./automaticPort.ts";
13import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
14​
15const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
16​
17// The desktop launcher reads this process's stdout and stderr. Once it is gone,
18// every log write fails, and Node turns an unhandled stream error into a crash
19// that skips shutdown and leaves the ownership lock and runtime record behind.
20function ignoreClosedLauncherPipe(error: NodeJS.ErrnoException): void {
21 if (error.code !== "EPIPE" && error.code !== "ERR_STREAM_DESTROYED") throw error;
23​
24const runServerCommand = Effect.fn("server.runServerCommand")(function* (
25 flags: CliServerFlags,
26 options?: {
27 readonly startupPresentation?: ServerConfig.StartupPresentation;
28 readonly forceAutoBootstrapProjectFromCwd?: boolean;
29 readonly rejectRunningServer?: boolean;
30 },
31) {
32 // Before config resolution, which claims a port and creates directories.
33 const { runServer } = yield* Effect.promise(() => import("../server.ts"));
34 const logLevel = yield* GlobalFlag.LogLevel;
35 const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer));
36 const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort });
37 const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
38 if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
39 yield* Effect.sync(() => {
40 process.stdout.on("error", ignoreClosedLauncherPipe);
41 process.stderr.on("error", ignoreClosedLauncherPipe);
42 });
43 return yield* Effect.raceFirst(
44 run,
45 awaitLauncherLoss().pipe(
46 // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).
47 Effect.andThen(Effect.interrupt),
48 ),
49 );
50});
51​
52export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand")(function* (
53 flags: CliServerFlags,
54) {
55 if (Option.isSome(flags.cwd)) {
56 const cwd = flags.cwd.value.trim();
57 const fs = yield* FileSystem.FileSystem;
58 const platform = yield* HostProcess.Platform;
59 const explicitPath =
60 cwd === "." ||
61 cwd === ".." ||
62 cwd === "~" ||
63 /[/\\]/.test(cwd) ||
64 (platform === "win32" && /^[a-z]:/i.test(cwd));
65 if (!explicitPath && (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")) {
66 return yield* new CliError.UserError({
67 cause: cwd,
68 userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,
69 });
70 }
71 }
72 return yield* runServerCommand(flags, { rejectRunningServer: true });
73});
74​
75export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
76 Command.withDescription("Same as `t3`."),
77 Command.unlisted,
78 Command.withHandler((flags) => runServerCommand(flags, { rejectRunningServer: true })),
79);
80​
81export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
82 Command.withShortDescription("Run T3 Code in this terminal, with no browser."),
83 Command.withDescription(
84 "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`.",
85 ),
86 Command.withHandler((flags) =>
87 runServerCommand(flags, {
88 startupPresentation: "headless",
89 forceAutoBootstrapProjectFromCwd: false,
90 }),
91 ),
92);