Open History to see the last commit
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 { cliAssets } from "../../../scripts/lib/cli-assets.ts";
14import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-executable-imports.ts";
15import { injectLinuxArm64Sea } from "../../../scripts/lib/linux-arm64-sea.ts";
16import rootPackageJson from "../../../package.json" with { type: "json" };
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { resolveSpawnCommand } from "@t3tools/shared/shell";
19import {
20 ServerCliBootstrapTooLargeError,
21 ServerCliBuildAssetMissingError,
22 ServerCliCommandExitError,
23 ServerCliDevelopmentIconSourceMissingError,
24 ServerCliDevelopmentIconTargetMissingError,
25 ServerCliExecutableImportError,
26} from "./cliErrors.ts";
27
28const RepoRoot = Effect.service(Path.Path).pipe(
29 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
30);
31
32const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
33 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
34 const child = yield* spawner.spawn(command);
35 const exitCode = yield* child.exitCode;
36
37 if (exitCode !== 0) {
38 return yield* new ServerCliCommandExitError({
39 command: command.command,
40 args: command.args.map(String),
41 cwd: command.options.cwd,
42 exitCode,
43 });
44 }
45});
46
47const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
48 repoRoot: string,
49 serverDir: string,
50) {
51 const path = yield* Path.Path;
52 const fs = yield* FileSystem.FileSystem;
53
54 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
55 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
56 const targetPath = path.join(serverDir, override.targetRelativePath);
57
58 if (!(yield* fs.exists(sourcePath))) {
59 return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
60 }
61 if (!(yield* fs.exists(targetPath))) {
62 return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
63 }
64
65 yield* fs.copyFile(sourcePath, targetPath);
66 }
67
68 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
69});
70
71const buildCmd = Command.make(
72 "build",
73 {
74 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
75 },
76 (config) =>
77 Effect.gen(function* () {
78 const path = yield* Path.Path;
79 const fs = yield* FileSystem.FileSystem;
80 const repoRoot = yield* RepoRoot;
81 const serverDir = path.join(repoRoot, "apps/server");
82
83 yield* Effect.log("[cli] Running tsdown...");
84 yield* runCommand(
85 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
86 cwd: serverDir,
87 stdout: config.verbose ? "inherit" : "ignore",
88 stderr: "inherit",
89 shell: false,
90 }),
91 );
92
93 const webDist = path.join(repoRoot, "apps/web/dist");
94 const clientTarget = path.join(serverDir, "dist/client");
95
96 if (yield* fs.exists(webDist)) {
97 yield* fs.copy(webDist, clientTarget);
98 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
99 yield* Effect.log("[cli] Bundled web app into dist/client");
100 } else {
101 yield* Effect.logWarning("[cli] Web dist not found. Skipping client bundle.");
102 }
103 }),
104).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
105
106const buildExeCmd = Command.make(
107 "build-exe",
108 {
109 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
110 target: Flag.String("target").pipe(
111 Flag.withDescription(
112 "Cross-build for <platform>-<arch> in nodejs.org naming (for example darwin-x64); defaults to the host.",
113 ),
114 Flag.optional,
115 ),
116 },
117 (config) =>
118 Effect.gen(function* () {
119 const path = yield* Path.Path;
120 const fs = yield* FileSystem.FileSystem;
121 const repoRoot = yield* RepoRoot;
122 const serverDir = path.join(repoRoot, "apps/server");
123
124 yield* Effect.log("[cli] Building single-executable...");
125 const target = Option.getOrUndefined(config.target);
126 // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048
127 const linuxArm64 =
128 !target &&
129 (yield* HostProcess.Platform) === "linux" &&
130 (yield* HostProcess.Architecture) === "arm64";
131 const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
132 const cliAssetDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-asset-" });
133 const pack = (packMode: "bundle" | "bootstrap" | "1") =>
134 runCommand(
135 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
136 cwd: serverDir,
137 env: {
138 ...process.env,
139 T3CODE_PACK_EXE: packMode,
140 T3CODE_CLI_ASSET_DIR: cliAssetDir,
141 T3CODE_PACK_EXE_TARGET: target ?? "",
142 },
143 stdout: config.verbose ? "inherit" : "ignore",
144 stderr: "inherit",
145 shell: spawnCommand.shell,
146 }),
147 );
148
149 yield* pack("bundle");
150 yield* pack(linuxArm64 ? "bootstrap" : "1");
151
152 // Executables reject non-builtin imports even when bundling succeeds; inspect the emitted graph.
153 const bootstrapPath = path.join(serverDir, "dist-exe/bin.mjs");
154 const cliModulePaths = Object.values(cliAssets(cliAssetDir));
155 for (const bundlePath of [bootstrapPath, ...cliModulePaths]) {
156 const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
157 if (specifiers.length > 0) {
158 return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
159 }
160 }
161 // The service launcher's memory win depends on the CLI staying out of the bootstrap.
162 const bootstrapBytes = (yield* fs.stat(bootstrapPath)).size;
163 if (bootstrapBytes > 1024 * 1024) {
164 return yield* new ServerCliBootstrapTooLargeError({
165 bootstrapPath,
166 bytes: Number(bootstrapBytes),
167 });
168 }
169 // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048
170 if (linuxArm64) {
171 yield* injectLinuxArm64Sea({
172 bundlePath: bootstrapPath,
173 cliAssetDir,
174 outputPath: path.join(serverDir, "dist-exe/t3"),
175 nodeVersion: rootPackageJson.engines.node,
176 verbose: config.verbose,
177 });
178 }
179 yield* Effect.log(
180 "[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)",
181 );
182 }),
183).pipe(
184 Command.withDescription(
185 `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. Linux ARM64 builds only on a Linux ARM64 host. The binary still resolves native packages from a node_modules tree beside it.`,
186 ),
187);
188
189/** Publish after the GitHub release exists; the launcher downloads from it. */
190const publishCmd = Command.make(
191 "publish",
192 {
193 packagesDir: Flag.String("packages-dir").pipe(
194 Flag.withDescription("Output dir of scripts/build-npm-launcher.ts."),
195 ),
196 tag: Flag.String("tag").pipe(Flag.withDefault("latest")),
197 access: Flag.String("access").pipe(Flag.withDefault("public")),
198 provenance: Flag.Boolean("provenance").pipe(Flag.withDefault(false)),
199 dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)),
200 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
201 },
202 (config) =>
203 Effect.gen(function* () {
204 const path = yield* Path.Path;
205 const fs = yield* FileSystem.FileSystem;
206 const packagesDir = path.resolve(config.packagesDir);
207 const launcherTarball = path.join(packagesDir, "t3.tgz");
208 if (!(yield* fs.exists(launcherTarball))) {
209 return yield* new ServerCliBuildAssetMissingError({ assetPath: launcherTarball });
210 }
211
212 const args = ["publish", "--access", config.access, "--tag", config.tag];
213 if (config.provenance) args.push("--provenance");
214 if (config.dryRun) args.push("--dry-run");
215 const spawnCommand = yield* resolveSpawnCommand("npm", [...args, launcherTarball]);
216 yield* Effect.log(`[cli] npm ${args.join(" ")} t3.tgz`);
217 yield* runCommand(
218 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
219 cwd: packagesDir,
220 stdout: config.verbose ? "inherit" : "ignore",
221 stderr: "inherit",
222 shell: spawnCommand.shell,
223 }),
224 );
225 }),
226).pipe(Command.withDescription("Publish the t3 launcher to npm."));
227
228const cli = Command.make("cli").pipe(
229 Command.withDescription("T3 server build & publish CLI."),
230 Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
231);
232
233Command.run(cli, { version: "0.0.0" }).pipe(
234 Effect.scoped,
235 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
236 NodeRuntime.runMain,
237);