Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
6import { Command, Flag } from "effect/unstable/cli";
7import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
9import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
10import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
11import rootPackageJson from "../../../package.json" with { type: "json" };
12import serverPackageJson from "../package.json" with { type: "json" };
13
14class CliError extends Data.TaggedError("CliError")<{
15 readonly message: string;
16 readonly cause?: unknown;
17}> {}
18
19const RepoRoot = Effect.service(Path.Path).pipe(
20 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
21);
22
23const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
24 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
25 const child = yield* spawner.spawn(command);
26 const exitCode = yield* child.exitCode;
27
28 if (exitCode !== 0) {
29 return yield* new CliError({
30 message: `Command exited with non-zero exit code (${exitCode})`,
31 });
32 }
33});
34
35interface PublishIconBackup {
36 readonly targetPath: string;
37 readonly backupPath: string;
38}
39
40const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
41 repoRoot: string,
42 serverDir: string,
43) {
44 const path = yield* Path.Path;
45 const fs = yield* FileSystem.FileSystem;
46 const backups: PublishIconBackup[] = [];
47
48 for (const override of PUBLISH_ICON_OVERRIDES) {
49 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
50 const targetPath = path.join(serverDir, override.targetRelativePath);
51 const backupPath = `${targetPath}.publish-bak`;
52
53 if (!(yield* fs.exists(sourcePath))) {
54 return yield* new CliError({
55 message: `Missing publish icon source: ${sourcePath}`,
56 });
57 }
58 if (!(yield* fs.exists(targetPath))) {
59 return yield* new CliError({
60 message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
61 });
62 }
63
64 yield* fs.copyFile(targetPath, backupPath);
65 yield* fs.copyFile(sourcePath, targetPath);
66 backups.push({ targetPath, backupPath });
67 }
68
69 yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
70 return backups as ReadonlyArray<PublishIconBackup>;
71});
72
73const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
74 backups: ReadonlyArray<PublishIconBackup>,
75) {
76 const fs = yield* FileSystem.FileSystem;
77 for (const backup of backups) {
78 if (!(yield* fs.exists(backup.backupPath))) {
79 continue;
80 }
81 yield* fs.rename(backup.backupPath, backup.targetPath);
82 }
83});
84
85const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
86 repoRoot: string,
87 serverDir: string,
88) {
89 const path = yield* Path.Path;
90 const fs = yield* FileSystem.FileSystem;
91
92 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
93 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
94 const targetPath = path.join(serverDir, override.targetRelativePath);
95
96 if (!(yield* fs.exists(sourcePath))) {
97 return yield* new CliError({
98 message: `Missing development icon source: ${sourcePath}`,
99 });
100 }
101 if (!(yield* fs.exists(targetPath))) {
102 return yield* new CliError({
103 message: `Missing development icon target: ${targetPath}. Build web first.`,
104 });
105 }
106
107 yield* fs.copyFile(sourcePath, targetPath);
108 }
109
110 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
111});
112
113// ---------------------------------------------------------------------------
114// build subcommand
115// ---------------------------------------------------------------------------
116
117const buildCmd = Command.make(
118 "build",
119 {
120 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
121 },
122 (config) =>
123 Effect.gen(function* () {
124 const path = yield* Path.Path;
125 const fs = yield* FileSystem.FileSystem;
126 const repoRoot = yield* RepoRoot;
127 const serverDir = path.join(repoRoot, "apps/server");
128
129 yield* Effect.log("[cli] Running tsdown...");
130 yield* runCommand(
131 ChildProcess.make({
132 cwd: serverDir,
133 stdout: config.verbose ? "inherit" : "ignore",
134 stderr: "inherit",
135 // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
136 shell: process.platform === "win32",
137 })`bun tsdown`,
138 );
139
140 const webDist = path.join(repoRoot, "apps/web/dist");
141 const clientTarget = path.join(serverDir, "dist/client");
142
143 if (yield* fs.exists(webDist)) {
144 yield* fs.copy(webDist, clientTarget);
145 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
146 yield* Effect.log("[cli] Bundled web app into dist/client");
147 } else {
148 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
149 }
150 }),
151).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
152
153// ---------------------------------------------------------------------------
154// publish subcommand
155// ---------------------------------------------------------------------------
156
157const publishCmd = Command.make(
158 "publish",
159 {
160 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
161 access: Flag.string("access").pipe(Flag.withDefault("public")),
162 appVersion: Flag.string("app-version").pipe(Flag.optional),
163 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
164 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
165 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
166 },
167 (config) =>
168 Effect.gen(function* () {
169 const path = yield* Path.Path;
170 const fs = yield* FileSystem.FileSystem;
171 const repoRoot = yield* RepoRoot;
172 const serverDir = path.join(repoRoot, "apps/server");
173 const packageJsonPath = path.join(serverDir, "package.json");
174 const backupPath = `${packageJsonPath}.bak`;
175
176 // Assert build assets exist
177 for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
178 const abs = path.join(serverDir, relPath);
179 if (!(yield* fs.exists(abs))) {
180 return yield* new CliError({
181 message: `Missing build asset: ${abs}. Run the build subcommand first.`,
182 });
183 }
184 }
185
186 yield* Effect.acquireUseRelease(
187 // Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
188 Effect.gen(function* () {
189 // Resolve catalog dependencies before any file mutations. If this throws,
190 // acquire fails and no release hook runs, so filesystem must still be untouched.
191 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
192 const pkg = {
193 name: serverPackageJson.name,
194 repository: serverPackageJson.repository,
195 bin: serverPackageJson.bin,
196 type: serverPackageJson.type,
197 version,
198 engines: serverPackageJson.engines,
199 files: serverPackageJson.files,
200 dependencies: serverPackageJson.dependencies as Record<string, unknown>,
201 };
202
203 pkg.dependencies = resolveCatalogDependencies(
204 pkg.dependencies,
205 rootPackageJson.workspaces.catalog,
206 "apps/server dependencies",
207 );
208
209 const original = yield* fs.readFileString(packageJsonPath);
210 yield* fs.writeFileString(backupPath, original);
211 yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
212 yield* Effect.log("[cli] Resolved package.json for publish");
213
214 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
215 return { iconBackups };
216 }),
217 // Use: npm publish
218 () =>
219 Effect.gen(function* () {
220 const args = ["publish", "--access", config.access, "--tag", config.tag];
221 if (config.provenance) args.push("--provenance");
222 if (config.dryRun) args.push("--dry-run");
223
224 yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
225 yield* runCommand(
226 ChildProcess.make("npm", [...args], {
227 cwd: serverDir,
228 stdout: config.verbose ? "inherit" : "ignore",
229 stderr: "inherit",
230 // Windows needs shell mode to resolve .cmd shims.
231 shell: process.platform === "win32",
232 }),
233 );
234 }),
235 // Release: restore
236 (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
237 Effect.gen(function* () {
238 yield* restorePublishIconOverrides(resource.iconBackups).pipe(
239 Effect.catch((error) =>
240 Effect.logError(
241 `[cli] Failed to restore publish icon overrides: ${String(error)}`,
242 ),
243 ),
244 );
245 yield* fs.rename(backupPath, packageJsonPath);
246 if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
247 }),
248 );
249 }),
250).pipe(Command.withDescription("Publish the server package to npm."));
251
252// ---------------------------------------------------------------------------
253// root command
254// ---------------------------------------------------------------------------
255
256const cli = Command.make("cli").pipe(
257 Command.withDescription("T3 server build & publish CLI."),
258 Command.withSubcommands([buildCmd, publishCmd]),
259);
260
261Command.run(cli, { version: "0.0.0" }).pipe(
262 Effect.scoped,
263 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
264 NodeRuntime.runMain,
265);