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