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

cli.ts

203 lines7.6 KB

1#!/usr/bin/env node
2import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Logger from "effect/Logger";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import { Command, Flag } from "effect/cli";
10import { ChildProcess, ChildProcessSpawner } from "effect/process";
11​
12import { DEVELOPMENT_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
13import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-executable-imports.ts";
14import rootPackageJson from "../../../package.json" with { type: "json" };
15import { resolveSpawnCommand } from "@t3tools/shared/shell";
16import {
17 ServerCliBuildAssetMissingError,
18 ServerCliCommandExitError,
19 ServerCliDevelopmentIconSourceMissingError,
20 ServerCliDevelopmentIconTargetMissingError,
21 ServerCliExecutableImportError,
22} from "./cliErrors.ts";
23​
24const RepoRoot = Effect.service(Path.Path).pipe(
25 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
26);
27​
28const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
29 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
30 const child = yield* spawner.spawn(command);
31 const exitCode = yield* child.exitCode;
32​
33 if (exitCode !== 0) {
34 return yield* new ServerCliCommandExitError({
35 command: command.command,
36 args: command.args,
37 cwd: command.options.cwd,
38 exitCode,
39 });
40 }
41});
42​
43const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
44 repoRoot: string,
45 serverDir: string,
46) {
47 const path = yield* Path.Path;
48 const fs = yield* FileSystem.FileSystem;
49​
50 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
51 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
52 const targetPath = path.join(serverDir, override.targetRelativePath);
53​
54 if (!(yield* fs.exists(sourcePath))) {
55 return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
56 }
57 if (!(yield* fs.exists(targetPath))) {
58 return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
59 }
60​
61 yield* fs.copyFile(sourcePath, targetPath);
62 }
63​
64 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
65});
66​
67const buildCmd = Command.make(
68 "build",
69 {
70 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
71 },
72 (config) =>
73 Effect.gen(function* () {
74 const path = yield* Path.Path;
75 const fs = yield* FileSystem.FileSystem;
76 const repoRoot = yield* RepoRoot;
77 const serverDir = path.join(repoRoot, "apps/server");
78​
79 yield* Effect.log("[cli] Running tsdown...");
80 yield* runCommand(
81 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
82 cwd: serverDir,
83 stdout: config.verbose ? "inherit" : "ignore",
84 stderr: "inherit",
85 shell: false,
86 }),
87 );
88​
89 const webDist = path.join(repoRoot, "apps/web/dist");
90 const clientTarget = path.join(serverDir, "dist/client");
91​
92 if (yield* fs.exists(webDist)) {
93 yield* fs.copy(webDist, clientTarget);
94 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
95 yield* Effect.log("[cli] Bundled web app into dist/client");
96 } else {
97 yield* Effect.logWarning("[cli] Web dist not found. Skipping client bundle.");
98 }
99 }),
100).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
101​
102const buildExeCmd = Command.make(
103 "build-exe",
104 {
105 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
106 target: Flag.String("target").pipe(
107 Flag.withDescription(
108 "Cross-build for <platform>-<arch> in nodejs.org naming (for example darwin-x64); defaults to the host.",
109 ),
110 Flag.optional,
111 ),
112 },
113 (config) =>
114 Effect.gen(function* () {
115 const path = yield* Path.Path;
116 const fs = yield* FileSystem.FileSystem;
117 const repoRoot = yield* RepoRoot;
118 const serverDir = path.join(repoRoot, "apps/server");
119​
120 yield* Effect.log("[cli] Building single-executable...");
121 const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
122 yield* runCommand(
123 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
124 cwd: serverDir,
125 env: {
126 ...process.env,
127 T3CODE_PACK_EXE: "1",
128 ...Option.match(config.target, {
129 onNone: () => ({}),
130 onSome: (target) => ({ T3CODE_PACK_EXE_TARGET: target }),
131 }),
132 },
133 stdout: config.verbose ? "inherit" : "ignore",
134 stderr: "inherit",
135 shell: spawnCommand.shell,
136 }),
137 );
138​
139 // Executables reject non-builtin imports even when bundling succeeds; inspect the emitted graph.
140 const bundlePath = path.join(serverDir, "dist-exe/bin.mjs");
141 const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
142 if (specifiers.length > 0) {
143 return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
144 }
145 yield* Effect.log(
146 "[cli] Built dist-exe/t3 (expects client/, resource-monitor/, and the runtime-external node_modules beside it; scripts/build-cli-archive.ts assembles that tree)",
147 );
148 }),
149).pipe(
150 Command.withDescription(
151 `Build the server as a Node single-executable. Native builds require Node ${rootPackageJson.engines.node}; explicit cross-target builds need a Node 25.7+ host for --build-sea. The binary still resolves native packages from a node_modules tree beside it.`,
152 ),
153);
154​
155/** Publish after the GitHub release exists; the launcher downloads from it. */
156const publishCmd = Command.make(
157 "publish",
158 {
159 packagesDir: Flag.String("packages-dir").pipe(
160 Flag.withDescription("Output dir of scripts/build-npm-launcher.ts."),
161 ),
162 tag: Flag.String("tag").pipe(Flag.withDefault("latest")),
163 access: Flag.String("access").pipe(Flag.withDefault("public")),
164 provenance: Flag.Boolean("provenance").pipe(Flag.withDefault(false)),
165 dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)),
166 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
167 },
168 (config) =>
169 Effect.gen(function* () {
170 const path = yield* Path.Path;
171 const fs = yield* FileSystem.FileSystem;
172 const packagesDir = path.resolve(config.packagesDir);
173 const launcherTarball = path.join(packagesDir, "t3.tgz");
174 if (!(yield* fs.exists(launcherTarball))) {
175 return yield* new ServerCliBuildAssetMissingError({ assetPath: launcherTarball });
176 }
177​
178 const args = ["publish", "--access", config.access, "--tag", config.tag];
179 if (config.provenance) args.push("--provenance");
180 if (config.dryRun) args.push("--dry-run");
181 const spawnCommand = yield* resolveSpawnCommand("npm", [...args, launcherTarball]);
182 yield* Effect.log(`[cli] npm ${args.join(" ")} t3.tgz`);
183 yield* runCommand(
184 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
185 cwd: packagesDir,
186 stdout: config.verbose ? "inherit" : "ignore",
187 stderr: "inherit",
188 shell: spawnCommand.shell,
189 }),
190 );
191 }),
192).pipe(Command.withDescription("Publish the t3 launcher to npm."));
193​
194const cli = Command.make("cli").pipe(
195 Command.withDescription("T3 server build & publish CLI."),
196 Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
197);
198​
199Command.run(cli, { version: "0.0.0" }).pipe(
200 Effect.scoped,
201 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
202 NodeRuntime.runMain,
203);