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 shell: process.platform === "win32",
136 })`bun tsdown`,
137 );
138
139 const webDist = path.join(repoRoot, "apps/web/dist");
140 const clientTarget = path.join(serverDir, "dist/client");
141
142 if (yield* fs.exists(webDist)) {
143 yield* fs.copy(webDist, clientTarget);
144 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
145 yield* Effect.log("[cli] Bundled web app into dist/client");
146 } else {
147 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
148 }
149 }),
150).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
151
152// ---------------------------------------------------------------------------
153// publish subcommand
154// ---------------------------------------------------------------------------
155
156const publishCmd = Command.make(
157 "publish",
158 {
159 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
160 access: Flag.string("access").pipe(Flag.withDefault("public")),
161 appVersion: Flag.string("app-version").pipe(Flag.optional),
162 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
163 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
164 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
165 },
166 (config) =>
167 Effect.gen(function* () {
168 const path = yield* Path.Path;
169 const fs = yield* FileSystem.FileSystem;
170 const repoRoot = yield* RepoRoot;
171 const serverDir = path.join(repoRoot, "apps/server");
172 const packageJsonPath = path.join(serverDir, "package.json");
173 const backupPath = `${packageJsonPath}.bak`;
174
175 // Assert build assets exist
176 for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
177 const abs = path.join(serverDir, relPath);
178 if (!(yield* fs.exists(abs))) {
179 return yield* new CliError({
180 message: `Missing build asset: ${abs}. Run the build subcommand first.`,
181 });
182 }
183 }
184
185 yield* Effect.acquireUseRelease(
186 // Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
187 Effect.gen(function* () {
188 // Resolve catalog dependencies before any file mutations. If this throws,
189 // acquire fails and no release hook runs, so filesystem must still be untouched.
190 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
191 const pkg = {
192 name: serverPackageJson.name,
193 repository: serverPackageJson.repository,
194 bin: serverPackageJson.bin,
195 type: serverPackageJson.type,
196 version,
197 engines: serverPackageJson.engines,
198 files: serverPackageJson.files,
199 dependencies: serverPackageJson.dependencies as Record<string, unknown>,
200 };
201
202 pkg.dependencies = resolveCatalogDependencies(
203 pkg.dependencies,
204 rootPackageJson.workspaces.catalog,
205 "apps/server dependencies",
206 );
207
208 const original = yield* fs.readFileString(packageJsonPath);
209 yield* fs.writeFileString(backupPath, original);
210 yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
211 yield* Effect.log("[cli] Resolved package.json for publish");
212
213 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
214 return { iconBackups };
215 }),
216 // Use: npm publish
217 () =>
218 Effect.gen(function* () {
219 const args = ["publish", "--access", config.access, "--tag", config.tag];
220 if (config.provenance) args.push("--provenance");
221 if (config.dryRun) args.push("--dry-run");
222
223 yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
224 yield* runCommand(
225 ChildProcess.make("npm", [...args], {
226 cwd: serverDir,
227 stdout: config.verbose ? "inherit" : "ignore",
228 stderr: "inherit",
229 shell: process.platform === "win32",
230 }),
231 );
232 }),
233 // Release: restore
234 (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
235 Effect.gen(function* () {
236 yield* restorePublishIconOverrides(resource.iconBackups).pipe(
237 Effect.catch((error) =>
238 Effect.logError(
239 `[cli] Failed to restore publish icon overrides: ${String(error)}`,
240 ),
241 ),
242 );
243 yield* fs.rename(backupPath, packageJsonPath);
244 if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
245 }),
246 );
247 }),
248).pipe(Command.withDescription("Publish the server package to npm."));
249
250// ---------------------------------------------------------------------------
251// root command
252// ---------------------------------------------------------------------------
253
254const cli = Command.make("cli").pipe(
255 Command.withDescription("T3 server build & publish CLI."),
256 Command.withSubcommands([buildCmd, publishCmd]),
257);
258
259Command.run(cli, { version: "0.0.0" }).pipe(
260 Effect.scoped,
261 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
262 NodeRuntime.runMain,
263);