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