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