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

cli.ts

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