Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cli.ts

261 lines9.5 KB

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