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 * as Schema from "effect/Schema";
10import { Command, Flag } from "effect/unstable/cli";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12
13import {
14 DEVELOPMENT_ICON_OVERRIDES,
15 resolveWebAssetBrandForPackageVersion,
16 resolveWebIconOverrides,
17} from "../../../scripts/lib/brand-assets.ts";
18import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-external-packages.ts";
19import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
20import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
21import { fromYaml } from "@t3tools/shared/schemaYaml";
22import { resolveSpawnCommand } from "@t3tools/shared/shell";
23import serverPackageJson from "../package.json" with { type: "json" };
24import {
25 ServerCliBuildAssetMissingError,
26 ServerCliCommandExitError,
27 ServerCliDevelopmentIconSourceMissingError,
28 ServerCliDevelopmentIconTargetMissingError,
29 ServerCliExecutableImportError,
30 ServerCliPublishIconSourceMissingError,
31 ServerCliPublishIconTargetMissingError,
32} from "./cliErrors.ts";
33
34interface PackageJson {
35 name: string;
36 repository: {
37 type: string;
38 url: string;
39 directory: string;
40 };
41 bin: Record<string, string>;
42 type: string;
43 version: string;
44 engines: Record<string, string>;
45 files: string[];
46 dependencies: Record<string, string>;
47 overrides: Record<string, string>;
48}
49
50const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
51const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
52
53const WorkspaceConfig = Schema.Struct({
54 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
55 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
56});
57type WorkspaceConfig = typeof WorkspaceConfig.Type;
58const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
59
60const RepoRoot = Effect.service(Path.Path).pipe(
61 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
62);
63
64const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
65 const path = yield* Path.Path;
66 const fs = yield* FileSystem.FileSystem;
67 const repoRoot = yield* RepoRoot;
68 const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
69 return yield* decodeWorkspaceConfig(workspaceYaml);
70});
71
72const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
73 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
74 const child = yield* spawner.spawn(command);
75 const exitCode = yield* child.exitCode;
76
77 if (exitCode !== 0) {
78 return yield* new ServerCliCommandExitError({
79 command: command.command,
80 args: command.args,
81 cwd: command.options.cwd,
82 exitCode,
83 });
84 }
85});
86
87const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
88 repoRoot: string,
89 serverDir: string,
90 version: string,
91) {
92 const path = yield* Path.Path;
93 const fs = yield* FileSystem.FileSystem;
94 const brand = resolveWebAssetBrandForPackageVersion(version);
95 const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
96 sourcePath: path.join(repoRoot, override.sourceRelativePath),
97 targetPath: path.join(serverDir, override.targetRelativePath),
98 }));
99
100 for (const icon of icons) {
101 if (!(yield* fs.exists(icon.sourcePath))) {
102 return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
103 }
104 if (!(yield* fs.exists(icon.targetPath))) {
105 return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
106 }
107 }
108
109 return yield* Effect.forEach(icons, (icon) =>
110 Effect.all({
111 original: fs.readFile(icon.targetPath),
112 publish: fs.readFile(icon.sourcePath),
113 }).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
114 );
115});
116
117const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
118 repoRoot: string,
119 serverDir: string,
120) {
121 const path = yield* Path.Path;
122 const fs = yield* FileSystem.FileSystem;
123
124 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
125 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
126 const targetPath = path.join(serverDir, override.targetRelativePath);
127
128 if (!(yield* fs.exists(sourcePath))) {
129 return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
130 }
131 if (!(yield* fs.exists(targetPath))) {
132 return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
133 }
134
135 yield* fs.copyFile(sourcePath, targetPath);
136 }
137
138 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
139});
140
141// ---------------------------------------------------------------------------
142// build subcommand
143// ---------------------------------------------------------------------------
144
145const buildCmd = Command.make(
146 "build",
147 {
148 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
149 },
150 (config) =>
151 Effect.gen(function* () {
152 const path = yield* Path.Path;
153 const fs = yield* FileSystem.FileSystem;
154 const repoRoot = yield* RepoRoot;
155 const serverDir = path.join(repoRoot, "apps/server");
156
157 yield* Effect.log("[cli] Running tsdown...");
158 yield* runCommand(
159 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
160 cwd: serverDir,
161 stdout: config.verbose ? "inherit" : "ignore",
162 stderr: "inherit",
163 shell: false,
164 }),
165 );
166
167 const webDist = path.join(repoRoot, "apps/web/dist");
168 const clientTarget = path.join(serverDir, "dist/client");
169
170 if (yield* fs.exists(webDist)) {
171 yield* fs.copy(webDist, clientTarget);
172 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
173 yield* Effect.log("[cli] Bundled web app into dist/client");
174 } else {
175 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
176 }
177 }),
178).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
179
180// ---------------------------------------------------------------------------
181// build-exe subcommand
182// ---------------------------------------------------------------------------
183
184const buildExeCmd = Command.make(
185 "build-exe",
186 {
187 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
188 target: Flag.string("target").pipe(
189 Flag.withDescription(
190 "Cross-build for <platform>-<arch> in nodejs.org naming (for example darwin-x64); defaults to the host.",
191 ),
192 Flag.optional,
193 ),
194 },
195 (config) =>
196 Effect.gen(function* () {
197 const path = yield* Path.Path;
198 const fs = yield* FileSystem.FileSystem;
199 const repoRoot = yield* RepoRoot;
200 const serverDir = path.join(repoRoot, "apps/server");
201
202 yield* Effect.log("[cli] Building single-executable...");
203 const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
204 yield* runCommand(
205 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
206 cwd: serverDir,
207 env: {
208 ...process.env,
209 T3CODE_PACK_EXE: "1",
210 ...Option.match(config.target, {
211 onNone: () => ({}),
212 onSome: (target) => ({ T3CODE_PACK_EXE_TARGET: target }),
213 }),
214 },
215 stdout: config.verbose ? "inherit" : "ignore",
216 stderr: "inherit",
217 shell: spawnCommand.shell,
218 }),
219 );
220
221 // The executable can only `import` built-ins. A file-backed import
222 // passes the bundler and `node dist/bin.mjs`, then throws inside the
223 // binary, so read the emitted module graph rather than trusting config.
224 const bundlePath = path.join(serverDir, "dist-exe/bin.mjs");
225 const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
226 if (specifiers.length > 0) {
227 return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
228 }
229 yield* Effect.log(
230 "[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)",
231 );
232 }),
233).pipe(
234 Command.withDescription(
235 "Build the server as a Node single-executable (needs a Node 25.7+ host for --build-sea). The binary still resolves native packages from a node_modules tree beside it.",
236 ),
237);
238
239// ---------------------------------------------------------------------------
240// publish subcommand
241// ---------------------------------------------------------------------------
242
243interface PublishCommandConfig {
244 readonly access: string;
245 readonly tag: string;
246 readonly provenance: boolean;
247 readonly dryRun: boolean;
248}
249
250const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
251 const args = [
252 "publish",
253 "--filter",
254 "t3",
255 "--access",
256 config.access,
257 "--tag",
258 config.tag,
259 "--no-git-checks",
260 ];
261
262 if (config.provenance) args.push("--provenance");
263 if (config.dryRun) args.push("--dry-run");
264
265 return args;
266};
267
268const publishCmd = Command.make(
269 "publish",
270 {
271 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
272 access: Flag.string("access").pipe(Flag.withDefault("public")),
273 appVersion: Flag.string("app-version").pipe(Flag.optional),
274 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
275 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
276 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
277 },
278 (config) =>
279 Effect.gen(function* () {
280 const path = yield* Path.Path;
281 const fs = yield* FileSystem.FileSystem;
282 const repoRoot = yield* RepoRoot;
283 const serverDir = path.join(repoRoot, "apps/server");
284 const packageJsonPath = path.join(serverDir, "package.json");
285
286 // Assert build assets exist
287 for (const relPath of [
288 "dist/bin.mjs",
289 "dist/service-launcher.mjs",
290 "dist/client/index.html",
291 ]) {
292 const abs = path.join(serverDir, relPath);
293 if (!(yield* fs.exists(abs))) {
294 return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
295 }
296 }
297
298 yield* Effect.acquireUseRelease(
299 // Acquire: resolve publish metadata and read every original before mutation.
300 Effect.gen(function* () {
301 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
302 const workspaceConfig = yield* readWorkspaceConfig();
303 const workspaceCatalog = workspaceConfig.catalog ?? {};
304 const workspaceOverrides = workspaceConfig.overrides ?? {};
305 const pkg: PackageJson = {
306 name: serverPackageJson.name,
307 repository: serverPackageJson.repository,
308 bin: serverPackageJson.bin,
309 type: serverPackageJson.type,
310 version,
311 engines: serverPackageJson.engines,
312 files: serverPackageJson.files,
313 dependencies: resolveCatalogDependencies(
314 serverPackageJson.dependencies,
315 workspaceCatalog,
316 "apps/server",
317 ),
318 overrides: resolveCatalogDependencies(
319 workspaceOverrides,
320 workspaceCatalog,
321 "apps/server",
322 ),
323 };
324
325 return {
326 packageJsonString: yield* encodePackageJson(pkg),
327 originalPackageJson: yield* fs.readFile(packageJsonPath),
328 icons: yield* preparePublishIcons(repoRoot, serverDir, version),
329 };
330 }),
331 // Use: pnpm publish from the workspace root so pnpm-only workspace
332 // config, including override selectors, is interpreted correctly.
333 (resource) =>
334 Effect.gen(function* () {
335 yield* fs.writeFileString(packageJsonPath, `${resource.packageJsonString}\n`);
336 for (const icon of resource.icons) {
337 yield* fs.writeFile(icon.targetPath, icon.publish);
338 }
339 yield* Effect.log("[cli] Applied package metadata and publish icon overrides");
340
341 const args = createVpPmPublishArgs(config);
342 const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
343
344 yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
345 yield* runCommand(
346 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
347 cwd: repoRoot,
348 stdout: config.verbose ? "inherit" : "ignore",
349 stderr: "inherit",
350 shell: spawnCommand.shell,
351 }),
352 );
353 }),
354 // Release: restore every file even if applying overrides or publishing fails.
355 (resource) =>
356 Effect.gen(function* () {
357 yield* fs.writeFile(packageJsonPath, resource.originalPackageJson);
358 for (const icon of resource.icons) {
359 yield* fs.writeFile(icon.targetPath, icon.original);
360 }
361 if (config.verbose) yield* Effect.log("[cli] Restored original publish assets");
362 }),
363 );
364 }),
365).pipe(Command.withDescription("Publish the server package to npm."));
366
367// ---------------------------------------------------------------------------
368// root command
369// ---------------------------------------------------------------------------
370
371const cli = Command.make("cli").pipe(
372 Command.withDescription("T3 server build & publish CLI."),
373 Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
374);
375
376Command.run(cli, { version: "0.0.0" }).pipe(
377 Effect.scoped,
378 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
379 NodeRuntime.runMain,
380);