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 [
227 "dist/bin.mjs",
228 "dist/service-launcher.mjs",
229 "dist/client/index.html",
230 ]) {
231 const abs = path.join(serverDir, relPath);
232 if (!(yield* fs.exists(abs))) {
233 return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
234 }
235 }
236
237 yield* Effect.acquireUseRelease(
238 // Acquire: resolve publish metadata and read every original before mutation.
239 Effect.gen(function* () {
240 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
241 const workspaceConfig = yield* readWorkspaceConfig();
242 const workspaceCatalog = workspaceConfig.catalog ?? {};
243 const workspaceOverrides = workspaceConfig.overrides ?? {};
244 const pkg: PackageJson = {
245 name: serverPackageJson.name,
246 repository: serverPackageJson.repository,
247 bin: serverPackageJson.bin,
248 type: serverPackageJson.type,
249 version,
250 engines: serverPackageJson.engines,
251 files: serverPackageJson.files,
252 dependencies: resolveCatalogDependencies(
253 serverPackageJson.dependencies,
254 workspaceCatalog,
255 "apps/server",
256 ),
257 overrides: resolveCatalogDependencies(
258 workspaceOverrides,
259 workspaceCatalog,
260 "apps/server",
261 ),
262 };
263
264 return {
265 packageJsonString: yield* encodePackageJson(pkg),
266 originalPackageJson: yield* fs.readFile(packageJsonPath),
267 icons: yield* preparePublishIcons(repoRoot, serverDir, version),
268 };
269 }),
270 // Use: pnpm publish from the workspace root so pnpm-only workspace
271 // config, including override selectors, is interpreted correctly.
272 (resource) =>
273 Effect.gen(function* () {
274 yield* fs.writeFileString(packageJsonPath, `${resource.packageJsonString}\n`);
275 for (const icon of resource.icons) {
276 yield* fs.writeFile(icon.targetPath, icon.publish);
277 }
278 yield* Effect.log("[cli] Applied package metadata and publish icon overrides");
279
280 const args = createVpPmPublishArgs(config);
281 const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
282
283 yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
284 yield* runCommand(
285 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
286 cwd: repoRoot,
287 stdout: config.verbose ? "inherit" : "ignore",
288 stderr: "inherit",
289 shell: spawnCommand.shell,
290 }),
291 );
292 }),
293 // Release: restore every file even if applying overrides or publishing fails.
294 (resource) =>
295 Effect.gen(function* () {
296 yield* fs.writeFile(packageJsonPath, resource.originalPackageJson);
297 for (const icon of resource.icons) {
298 yield* fs.writeFile(icon.targetPath, icon.original);
299 }
300 if (config.verbose) yield* Effect.log("[cli] Restored original publish assets");
301 }),
302 );
303 }),
304).pipe(Command.withDescription("Publish the server package to npm."));
305
306// ---------------------------------------------------------------------------
307// root command
308// ---------------------------------------------------------------------------
309
310const cli = Command.make("cli").pipe(
311 Command.withDescription("T3 server build & publish CLI."),
312 Command.withSubcommands([buildCmd, publishCmd]),
313);
314
315Command.run(cli, { version: "0.0.0" }).pipe(
316 Effect.scoped,
317 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
318 NodeRuntime.runMain,
319);