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

cli.ts

335 lines11.7 KB

1#!/usr/bin/env node
2import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Data from "effect/Data";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Logger from "effect/Logger";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { Command, Flag } from "effect/unstable/cli";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13​
14import {
15 DEVELOPMENT_ICON_OVERRIDES,
16 PUBLISH_ICON_OVERRIDES,
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" };
23​
24interface PackageJson {
25 name: string;
26 repository: {
27 type: string;
28 url: string;
29 directory: string;
30 };
31 bin: Record<string, string>;
32 type: string;
33 version: string;
34 engines: Record<string, string>;
35 files: string[];
36 dependencies: Record<string, string>;
37 overrides: Record<string, string>;
39​
40const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
41const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
42​
43const WorkspaceConfig = Schema.Struct({
44 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
45 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
46});
47type WorkspaceConfig = typeof WorkspaceConfig.Type;
48const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
49​
50class CliError extends Data.TaggedError("CliError")<{
51 readonly message: string;
52 readonly cause?: unknown;
53}> {}
54​
55const RepoRoot = Effect.service(Path.Path).pipe(
56 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
57);
58​
59const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
60 const path = yield* Path.Path;
61 const fs = yield* FileSystem.FileSystem;
62 const repoRoot = yield* RepoRoot;
63 const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
64 return yield* decodeWorkspaceConfig(workspaceYaml);
65});
66​
67const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
68 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
69 const child = yield* spawner.spawn(command);
70 const exitCode = yield* child.exitCode;
71​
72 if (exitCode !== 0) {
73 return yield* new CliError({
74 message: `Command exited with non-zero exit code (${exitCode})`,
75 });
76 }
77});
78​
79interface PublishIconBackup {
80 readonly targetPath: string;
81 readonly backupPath: string;
83​
84const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
85 repoRoot: string,
86 serverDir: string,
87) {
88 const path = yield* Path.Path;
89 const fs = yield* FileSystem.FileSystem;
90 const backups: PublishIconBackup[] = [];
91​
92 for (const override of PUBLISH_ICON_OVERRIDES) {
93 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
94 const targetPath = path.join(serverDir, override.targetRelativePath);
95 const backupPath = `${targetPath}.publish-bak`;
96​
97 if (!(yield* fs.exists(sourcePath))) {
98 return yield* new CliError({
99 message: `Missing publish icon source: ${sourcePath}`,
100 });
101 }
102 if (!(yield* fs.exists(targetPath))) {
103 return yield* new CliError({
104 message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
105 });
106 }
107​
108 yield* fs.copyFile(targetPath, backupPath);
109 yield* fs.copyFile(sourcePath, targetPath);
110 backups.push({ targetPath, backupPath });
111 }
112​
113 yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
114 return backups as ReadonlyArray<PublishIconBackup>;
115});
116​
117const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
118 backups: ReadonlyArray<PublishIconBackup>,
119) {
120 const fs = yield* FileSystem.FileSystem;
121 for (const backup of backups) {
122 if (!(yield* fs.exists(backup.backupPath))) {
123 continue;
124 }
125 yield* fs.rename(backup.backupPath, backup.targetPath);
126 }
127});
128​
129const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
130 repoRoot: string,
131 serverDir: string,
132) {
133 const path = yield* Path.Path;
134 const fs = yield* FileSystem.FileSystem;
135​
136 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
137 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
138 const targetPath = path.join(serverDir, override.targetRelativePath);
139​
140 if (!(yield* fs.exists(sourcePath))) {
141 return yield* new CliError({
142 message: `Missing development icon source: ${sourcePath}`,
143 });
144 }
145 if (!(yield* fs.exists(targetPath))) {
146 return yield* new CliError({
147 message: `Missing development icon target: ${targetPath}. Build web first.`,
148 });
149 }
150​
151 yield* fs.copyFile(sourcePath, targetPath);
152 }
153​
154 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
155});
156​
157// ---------------------------------------------------------------------------
158// build subcommand
159// ---------------------------------------------------------------------------
160​
161const buildCmd = Command.make(
162 "build",
163 {
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​
173 yield* Effect.log("[cli] Running tsdown...");
174 yield* runCommand(
175 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
176 cwd: serverDir,
177 stdout: config.verbose ? "inherit" : "ignore",
178 stderr: "inherit",
179 shell: false,
180 }),
181 );
182​
183 const webDist = path.join(repoRoot, "apps/web/dist");
184 const clientTarget = path.join(serverDir, "dist/client");
185​
186 if (yield* fs.exists(webDist)) {
187 yield* fs.copy(webDist, clientTarget);
188 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
189 yield* Effect.log("[cli] Bundled web app into dist/client");
190 } else {
191 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
192 }
193 }),
194).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
195​
196// ---------------------------------------------------------------------------
197// publish subcommand
198// ---------------------------------------------------------------------------
199​
200interface PublishCommandConfig {
201 readonly access: string;
202 readonly tag: string;
203 readonly provenance: boolean;
204 readonly dryRun: boolean;
206​
207const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
208 const args = [
209 "publish",
210 "--filter",
211 "t3",
212 "--access",
213 config.access,
214 "--tag",
215 config.tag,
216 "--no-git-checks",
217 ];
218​
219 if (config.provenance) args.push("--provenance");
220 if (config.dryRun) args.push("--dry-run");
221​
222 return args;
223};
224​
225const publishCmd = Command.make(
226 "publish",
227 {
228 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
229 access: Flag.string("access").pipe(Flag.withDefault("public")),
230 appVersion: Flag.string("app-version").pipe(Flag.optional),
231 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
232 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
233 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
234 },
235 (config) =>
236 Effect.gen(function* () {
237 const path = yield* Path.Path;
238 const fs = yield* FileSystem.FileSystem;
239 const repoRoot = yield* RepoRoot;
240 const serverDir = path.join(repoRoot, "apps/server");
241 const packageJsonPath = path.join(serverDir, "package.json");
242 const backupPath = `${packageJsonPath}.bak`;
243​
244 // Assert build assets exist
245 for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
246 const abs = path.join(serverDir, relPath);
247 if (!(yield* fs.exists(abs))) {
248 return yield* new CliError({
249 message: `Missing build asset: ${abs}. Run the build subcommand first.`,
250 });
251 }
252 }
253​
254 yield* Effect.acquireUseRelease(
255 // Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
256 Effect.gen(function* () {
257 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
258 const workspaceConfig = yield* readWorkspaceConfig();
259 const workspaceCatalog = workspaceConfig.catalog ?? {};
260 const workspaceOverrides = workspaceConfig.overrides ?? {};
261 const pkg: PackageJson = {
262 name: serverPackageJson.name,
263 repository: serverPackageJson.repository,
264 bin: serverPackageJson.bin,
265 type: serverPackageJson.type,
266 version,
267 engines: serverPackageJson.engines,
268 files: serverPackageJson.files,
269 dependencies: resolveCatalogDependencies(
270 serverPackageJson.dependencies,
271 workspaceCatalog,
272 "apps/server",
273 ),
274 overrides: resolveCatalogDependencies(
275 workspaceOverrides,
276 workspaceCatalog,
277 "apps/server",
278 ),
279 };
280​
281 const original = yield* fs.readFileString(packageJsonPath);
282 const packageJsonString = yield* encodePackageJson(pkg);
283 yield* fs.writeFileString(backupPath, original);
284 yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
285 yield* Effect.log("[cli] Prepared package.json for publish");
286​
287 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
288 return { iconBackups };
289 }),
290 // Use: pnpm publish from the workspace root so pnpm-only workspace
291 // config, including override selectors, is interpreted correctly.
292 () =>
293 Effect.gen(function* () {
294 const args = createVpPmPublishArgs(config);
295 const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
296​
297 yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
298 yield* runCommand(
299 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
300 cwd: repoRoot,
301 stdout: config.verbose ? "inherit" : "ignore",
302 stderr: "inherit",
303 shell: spawnCommand.shell,
304 }),
305 );
306 }),
307 // Release: restore
308 (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
309 Effect.gen(function* () {
310 yield* restorePublishIconOverrides(resource.iconBackups).pipe(
311 Effect.catch((error) =>
312 Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
313 ),
314 );
315 yield* fs.rename(backupPath, packageJsonPath);
316 if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
317 }),
318 );
319 }),
320).pipe(Command.withDescription("Publish the server package to npm."));
321​
322// ---------------------------------------------------------------------------
323// root command
324// ---------------------------------------------------------------------------
325​
326const cli = Command.make("cli").pipe(
327 Command.withDescription("T3 server build & publish CLI."),
328 Command.withSubcommands([buildCmd, publishCmd]),
329);
330​
331Command.run(cli, { version: "0.0.0" }).pipe(
332 Effect.scoped,
333 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
334 NodeRuntime.runMain,
335);