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

build-desktop-artifact.ts

778 lines25.2 KB

1#!/usr/bin/env node
2​
3import { spawnSync } from "node:child_process";
4import { existsSync } from "node:fs";
5import { join } from "node:path";
6​
7import rootPackageJson from "../package.json" with { type: "json" };
8import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
9import serverPackageJson from "../apps/server/package.json" with { type: "json" };
10​
11import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
12import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
13​
14import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
15import * as NodeServices from "@effect/platform-node/NodeServices";
16import { Config, Data, Effect, FileSystem, Layer, Logger, Option, Path, Schema } from "effect";
17import { Command, Flag } from "effect/unstable/cli";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19​
20const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
21const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
22​
23const RepoRoot = Effect.service(Path.Path).pipe(
24 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
25);
26const ProductionMacIconSource = Effect.zipWith(RepoRoot, Effect.service(Path.Path), (repoRoot, path) =>
27 path.join(repoRoot, BRAND_ASSET_PATHS.productionMacIconPng),
28);
29const ProductionLinuxIconSource = Effect.zipWith(
30 RepoRoot,
31 Effect.service(Path.Path),
32 (repoRoot, path) => path.join(repoRoot, BRAND_ASSET_PATHS.productionLinuxIconPng),
33);
34const ProductionWindowsIconSource = Effect.zipWith(
35 RepoRoot,
36 Effect.service(Path.Path),
37 (repoRoot, path) => path.join(repoRoot, BRAND_ASSET_PATHS.productionWindowsIconIco),
38);
39const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
40​
41interface PlatformConfig {
42 readonly cliFlag: "--mac" | "--linux" | "--win";
43 readonly defaultTarget: string;
44 readonly archChoices: ReadonlyArray<typeof BuildArch.Type>;
46​
47const PLATFORM_CONFIG: Record<typeof BuildPlatform.Type, PlatformConfig> = {
48 mac: {
49 cliFlag: "--mac",
50 defaultTarget: "dmg",
51 archChoices: ["arm64", "x64", "universal"],
52 },
53 linux: {
54 cliFlag: "--linux",
55 defaultTarget: "AppImage",
56 archChoices: ["x64", "arm64"],
57 },
58 win: {
59 cliFlag: "--win",
60 defaultTarget: "nsis",
61 archChoices: ["x64", "arm64"],
62 },
63};
64​
65interface BuildCliInput {
66 readonly platform: Option.Option<typeof BuildPlatform.Type>;
67 readonly target: Option.Option<string>;
68 readonly arch: Option.Option<typeof BuildArch.Type>;
69 readonly buildVersion: Option.Option<string>;
70 readonly outputDir: Option.Option<string>;
71 readonly skipBuild: Option.Option<boolean>;
72 readonly keepStage: Option.Option<boolean>;
73 readonly signed: Option.Option<boolean>;
74 readonly verbose: Option.Option<boolean>;
76​
77function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
78 if (hostPlatform === "darwin") return "mac";
79 if (hostPlatform === "linux") return "linux";
80 if (hostPlatform === "win32") return "win";
81 return undefined;
83​
84function getDefaultArch(platform: typeof BuildPlatform.Type): typeof BuildArch.Type {
85 const config = PLATFORM_CONFIG[platform];
86 if (!config) {
87 return "x64";
88 }
89​
90 if (process.arch === "arm64" && config.archChoices.includes("arm64")) {
91 return "arm64";
92 }
93 if (process.arch === "x64" && config.archChoices.includes("x64")) {
94 return "x64";
95 }
96​
97 return config.archChoices[0] ?? "x64";
99​
100class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
101 readonly message: string;
102 readonly cause?: unknown;
103}> {}
104​
105function resolveGitCommitHash(repoRoot: string): string {
106 const result = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], {
107 cwd: repoRoot,
108 encoding: "utf8",
109 });
110 if (result.status !== 0) {
111 return "unknown";
112 }
113 const hash = result.stdout.trim();
114 if (!/^[0-9a-f]{7,40}$/i.test(hash)) {
115 return "unknown";
116 }
117 return hash.toLowerCase();
119​
120function resolvePythonForNodeGyp(): string | undefined {
121 const configured = process.env.npm_config_python ?? process.env.PYTHON;
122 if (configured && existsSync(configured)) {
123 return configured;
124 }
125​
126 if (process.platform === "win32") {
127 const localAppData = process.env.LOCALAPPDATA;
128 if (localAppData) {
129 for (const version of ["Python313", "Python312", "Python311", "Python310"]) {
130 const candidate = join(localAppData, "Programs", "Python", version, "python.exe");
131 if (existsSync(candidate)) {
132 return candidate;
133 }
134 }
135 }
136 }
137​
138 const probe = spawnSync("python", ["-c", "import sys;print(sys.executable)"], {
139 encoding: "utf8",
140 });
141 if (probe.status !== 0) {
142 return undefined;
143 }
144​
145 const executable = probe.stdout.trim();
146 if (!executable || !existsSync(executable)) {
147 return undefined;
148 }
149​
150 return executable;
152​
153interface ResolvedBuildOptions {
154 readonly platform: typeof BuildPlatform.Type;
155 readonly target: string;
156 readonly arch: typeof BuildArch.Type;
157 readonly version: string | undefined;
158 readonly outputDir: string;
159 readonly skipBuild: boolean;
160 readonly keepStage: boolean;
161 readonly signed: boolean;
162 readonly verbose: boolean;
164​
165interface StagePackageJson {
166 readonly name: string;
167 readonly version: string;
168 readonly buildVersion: string;
169 readonly t3codeCommitHash: string;
170 readonly private: true;
171 readonly description: string;
172 readonly author: string;
173 readonly main: string;
174 readonly build: Record<string, unknown>;
175 readonly dependencies: Record<string, unknown>;
176 readonly devDependencies: {
177 readonly electron: string;
178 };
180​
181const AzureTrustedSigningOptionsConfig = Config.all({
182 publisherName: Config.string("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
183 endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
184 certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
185 codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
186 fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
187 timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
188 Config.withDefault("SHA256"),
189 ),
190 timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
191 Config.withDefault("http://timestamp.acs.microsoft.com"),
192 ),
193});
194​
195const BuildEnvConfig = Config.all({
196 platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
197 target: Config.string("T3CODE_DESKTOP_TARGET").pipe(Config.option),
198 arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
199 version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
200 outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
201 skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
202 keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
203 signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
204 verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
205});
206​
207const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
208 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
209const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
210 Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
211​
212const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: BuildCliInput) {
213 const path = yield* Path.Path;
214 const repoRoot = yield* RepoRoot;
215 const env = yield* BuildEnvConfig.asEffect();
216​
217 const platform = mergeOptions(
218 input.platform,
219 env.platform,
220 detectHostBuildPlatform(process.platform),
221 );
222​
223 if (!platform) {
224 return yield* new BuildScriptError({
225 message: `Unsupported host platform '${process.platform}'.`,
226 });
227 }
228​
229 const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
230 const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform));
231 const version = mergeOptions(input.buildVersion, env.version, undefined);
232 const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release"));
233​
234 const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
235 const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
236 const signed = resolveBooleanFlag(input.signed, env.signed);
237 const verbose = resolveBooleanFlag(input.verbose, env.verbose);
238​
239 return {
240 platform,
241 target,
242 arch,
243 version,
244 outputDir,
245 skipBuild,
246 keepStage,
247 signed,
248 verbose,
249 } satisfies ResolvedBuildOptions;
250});
251​
252const commandOutputOptions = (verbose: boolean) =>
253 ({
254 stdout: verbose ? "inherit" : "ignore",
255 stderr: "inherit",
256 }) as const;
257​
258const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
259 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
260 const child = yield* commandSpawner.spawn(command);
261 const exitCode = yield* child.exitCode;
262​
263 if (exitCode !== 0) {
264 return yield* new BuildScriptError({
265 message: `Command exited with non-zero exit code (${exitCode})`,
266 });
267 }
268});
269​
270function generateMacIconSet(
271 sourcePng: string,
272 targetIcns: string,
273 tmpRoot: string,
274 path: Path.Path,
275 verbose: boolean,
276) {
277 return Effect.gen(function* () {
278 const fs = yield* FileSystem.FileSystem;
279 const iconsetDir = path.join(tmpRoot, "icon.iconset");
280 yield* fs.makeDirectory(iconsetDir, { recursive: true });
281​
282 const iconSizes = [16, 32, 128, 256, 512] as const;
283 for (const size of iconSizes) {
284 yield* runCommand(
285 ChildProcess.make({
286 ...commandOutputOptions(verbose),
287 })`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
288 );
289​
290 const retinaSize = size * 2;
291 yield* runCommand(
292 ChildProcess.make({
293 ...commandOutputOptions(verbose),
294 })`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
295 );
296 }
297​
298 yield* runCommand(
299 ChildProcess.make({
300 ...commandOutputOptions(verbose),
301 })`iconutil -c icns ${iconsetDir} -o ${targetIcns}`,
302 );
303 });
305​
306function stageMacIcons(stageResourcesDir: string, verbose: boolean) {
307 return Effect.gen(function* () {
308 const fs = yield* FileSystem.FileSystem;
309 const path = yield* Path.Path;
310 const iconSource = yield* ProductionMacIconSource;
311 if (!(yield* fs.exists(iconSource))) {
312 return yield* new BuildScriptError({
313 message: `Production icon source is missing at ${iconSource}`,
314 });
315 }
316​
317 const tmpRoot = yield* fs.makeTempDirectoryScoped({
318 prefix: "t3code-icon-build-",
319 });
320​
321 const iconPngPath = path.join(stageResourcesDir, "icon.png");
322 const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
323​
324 yield* runCommand(
325 ChildProcess.make({
326 ...commandOutputOptions(verbose),
327 })`sips -z 512 512 ${iconSource} --out ${iconPngPath}`,
328 );
329​
330 yield* generateMacIconSet(iconSource, iconIcnsPath, tmpRoot, path, verbose);
331 });
333​
334function stageLinuxIcons(stageResourcesDir: string) {
335 return Effect.gen(function* () {
336 const fs = yield* FileSystem.FileSystem;
337 const path = yield* Path.Path;
338 const iconSource = yield* ProductionLinuxIconSource;
339 if (!(yield* fs.exists(iconSource))) {
340 return yield* new BuildScriptError({
341 message: `Production icon source is missing at ${iconSource}`,
342 });
343 }
344​
345 const iconPath = path.join(stageResourcesDir, "icon.png");
346 yield* fs.copyFile(iconSource, iconPath);
347 });
349​
350function stageWindowsIcons(stageResourcesDir: string) {
351 return Effect.gen(function* () {
352 const fs = yield* FileSystem.FileSystem;
353 const path = yield* Path.Path;
354 const iconSource = yield* ProductionWindowsIconSource;
355 if (!(yield* fs.exists(iconSource))) {
356 return yield* new BuildScriptError({
357 message: `Production Windows icon source is missing at ${iconSource}`,
358 });
359 }
360​
361 const iconPath = path.join(stageResourcesDir, "icon.ico");
362 yield* fs.copyFile(iconSource, iconPath);
363 });
365​
366function validateBundledClientAssets(clientDir: string) {
367 return Effect.gen(function* () {
368 const fs = yield* FileSystem.FileSystem;
369 const path = yield* Path.Path;
370 const indexPath = path.join(clientDir, "index.html");
371 const indexHtml = yield* fs.readFileString(indexPath);
372 const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)]
373 .map((match) => match[1])
374 .filter((value): value is string => value !== undefined);
375 const missing: string[] = [];
376​
377 for (const ref of refs) {
378 const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
379 if (!normalizedRef) continue;
380 if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
381 if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
382​
383 const ext = path.extname(normalizedRef);
384 if (!ext) continue;
385​
386 const relativePath = normalizedRef.replace(/^\/+/, "");
387 const assetPath = path.join(clientDir, relativePath);
388 if (!(yield* fs.exists(assetPath))) {
389 missing.push(normalizedRef);
390 }
391 }
392​
393 if (missing.length > 0) {
394 const preview = missing.slice(0, 6).join(", ");
395 const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
396 return yield* new BuildScriptError({
397 message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
398 });
399 }
400 });
402​
403function resolveDesktopRuntimeDependencies(
404 dependencies: Record<string, unknown> | undefined,
405 catalog: Record<string, unknown>,
406): Record<string, unknown> {
407 if (!dependencies || Object.keys(dependencies).length === 0) {
408 return {};
409 }
410​
411 const runtimeDependencies = Object.fromEntries(
412 Object.entries(dependencies).filter(([dependencyName]) => dependencyName !== "electron"),
413 );
414​
415 return resolveCatalogDependencies(runtimeDependencies, catalog, "apps/desktop");
417​
418function resolveGitHubPublishConfig():
419 | {
420 readonly provider: "github";
421 readonly owner: string;
422 readonly repo: string;
423 readonly releaseType: "release";
424 }
425 | undefined {
426 const rawRepo =
427 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
428 process.env.GITHUB_REPOSITORY?.trim() ||
429 "";
430 if (!rawRepo) return undefined;
431​
432 const [owner, repo, ...rest] = rawRepo.split("/");
433 if (!owner || !repo || rest.length > 0) return undefined;
434​
435 return {
436 provider: "github",
437 owner,
438 repo,
439 releaseType: "release",
440 };
442​
443const createBuildConfig = Effect.fn("createBuildConfig")(function* (
444 platform: typeof BuildPlatform.Type,
445 target: string,
446 productName: string,
447 signed: boolean,
448) {
449 const buildConfig: Record<string, unknown> = {
450 appId: "com.t3tools.t3code",
451 productName,
452 artifactName: "T3-Code-${version}-${arch}.${ext}",
453 directories: {
454 buildResources: "apps/desktop/resources",
455 },
456 };
457 const publishConfig = resolveGitHubPublishConfig();
458 if (publishConfig) {
459 buildConfig.publish = [publishConfig];
460 }
461​
462 if (platform === "mac") {
463 buildConfig.mac = {
464 target: target === "dmg" ? [target, "zip"] : [target],
465 icon: "icon.icns",
466 category: "public.app-category.developer-tools",
467 };
468 }
469​
470 if (platform === "linux") {
471 buildConfig.linux = {
472 target: [target],
473 icon: "icon.png",
474 category: "Development",
475 };
476 }
477​
478 if (platform === "win") {
479 const winConfig: Record<string, unknown> = {
480 target: [target],
481 icon: "icon.ico",
482 };
483 if (signed) {
484 winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
485 }
486 buildConfig.win = winConfig;
487 }
488​
489 return buildConfig;
490});
491​
492const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(function* (
493 platform: typeof BuildPlatform.Type,
494 stageResourcesDir: string,
495 verbose: boolean,
496) {
497 if (platform === "mac") {
498 yield* stageMacIcons(stageResourcesDir, verbose);
499 return;
500 }
501​
502 if (platform === "linux") {
503 yield* stageLinuxIcons(stageResourcesDir);
504 return;
505 }
506​
507 if (platform === "win") {
508 yield* stageWindowsIcons(stageResourcesDir);
509 }
510});
511​
512const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
513 options: ResolvedBuildOptions,
514) {
515 const repoRoot = yield* RepoRoot;
516 const path = yield* Path.Path;
517 const fs = yield* FileSystem.FileSystem;
518​
519 const platformConfig = PLATFORM_CONFIG[options.platform];
520 if (!platformConfig) {
521 return yield* new BuildScriptError({
522 message: `Unsupported platform '${options.platform}'.`,
523 });
524 }
525​
526 const electronVersion = desktopPackageJson.dependencies.electron;
527​
528 const serverDependencies = serverPackageJson.dependencies;
529 if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
530 return yield* new BuildScriptError({
531 message: "Could not resolve production dependencies from apps/server/package.json.",
532 });
533 }
534​
535 const resolvedServerDependencies = yield* Effect.try({
536 try: () =>
537 resolveCatalogDependencies(
538 serverDependencies,
539 rootPackageJson.workspaces.catalog,
540 "apps/server",
541 ),
542 catch: (cause) =>
543 new BuildScriptError({
544 message: "Could not resolve production dependencies from apps/server/package.json.",
545 cause,
546 }),
547 });
548 const resolvedDesktopRuntimeDependencies = yield* Effect.try({
549 try: () =>
550 resolveDesktopRuntimeDependencies(
551 desktopPackageJson.dependencies,
552 rootPackageJson.workspaces.catalog,
553 ),
554 catch: (cause) =>
555 new BuildScriptError({
556 message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
557 cause,
558 }),
559 });
560​
561 const appVersion = options.version ?? serverPackageJson.version;
562 const commitHash = resolveGitCommitHash(repoRoot);
563 const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
564 const stageRoot = yield* mkdir({
565 prefix: `t3code-desktop-${options.platform}-stage-`,
566 });
567​
568 const stageAppDir = path.join(stageRoot, "app");
569 const stageResourcesDir = path.join(stageAppDir, "apps/desktop/resources");
570 const distDirs = {
571 desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
572 desktopResources: path.join(repoRoot, "apps/desktop/resources"),
573 serverDist: path.join(repoRoot, "apps/server/dist"),
574 };
575 const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
576​
577 if (!options.skipBuild) {
578 yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");
579 yield* runCommand(
580 ChildProcess.make({
581 cwd: repoRoot,
582 ...commandOutputOptions(options.verbose),
583 // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
584 shell: process.platform === "win32",
585 })`bun run build:desktop`,
586 );
587 }
588​
589 for (const [label, dir] of Object.entries(distDirs)) {
590 if (!(yield* fs.exists(dir))) {
591 return yield* new BuildScriptError({
592 message: `Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`,
593 });
594 }
595 }
596​
597 if (!(yield* fs.exists(bundledClientEntry))) {
598 return yield* new BuildScriptError({
599 message: `Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
600 });
601 }
602​
603 yield* validateBundledClientAssets(path.dirname(bundledClientEntry));
604​
605 yield* fs.makeDirectory(path.join(stageAppDir, "apps/desktop"), { recursive: true });
606 yield* fs.makeDirectory(path.join(stageAppDir, "apps/server"), { recursive: true });
607​
608 yield* Effect.log("[desktop-artifact] Staging release app...");
609 yield* fs.copy(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"));
610 yield* fs.copy(distDirs.desktopResources, stageResourcesDir);
611 yield* fs.copy(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"));
612​
613 yield* assertPlatformBuildResources(options.platform, stageResourcesDir, options.verbose);
614​
615 const stagePackageJson: StagePackageJson = {
616 name: "t3-code-desktop",
617 version: appVersion,
618 buildVersion: appVersion,
619 t3codeCommitHash: commitHash,
620 private: true,
621 description: "T3 Code desktop build",
622 author: "T3 Tools",
623 main: "apps/desktop/dist-electron/main.js",
624 build: yield* createBuildConfig(
625 options.platform,
626 options.target,
627 desktopPackageJson.productName ?? "T3 Code",
628 options.signed,
629 ),
630 dependencies: {
631 ...resolvedServerDependencies,
632 ...resolvedDesktopRuntimeDependencies,
633 },
634 devDependencies: {
635 electron: electronVersion,
636 },
637 };
638​
639 const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
640 yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
641​
642 yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
643 yield* runCommand(
644 ChildProcess.make({
645 cwd: stageAppDir,
646 ...commandOutputOptions(options.verbose),
647 // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
648 shell: process.platform === "win32",
649 })`bun install --production`,
650 );
651​
652 const buildEnv: NodeJS.ProcessEnv = {
653 ...process.env,
654 };
655 for (const [key, value] of Object.entries(buildEnv)) {
656 if (value === "") {
657 delete buildEnv[key];
658 }
659 }
660 if (!options.signed) {
661 buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
662 delete buildEnv.CSC_LINK;
663 delete buildEnv.CSC_KEY_PASSWORD;
664 delete buildEnv.APPLE_API_KEY;
665 delete buildEnv.APPLE_API_KEY_ID;
666 delete buildEnv.APPLE_API_ISSUER;
667 }
668​
669 if (process.platform === "win32") {
670 const python = resolvePythonForNodeGyp();
671 if (python) {
672 buildEnv.PYTHON = python;
673 buildEnv.npm_config_python = python;
674 }
675 buildEnv.npm_config_msvs_version = buildEnv.npm_config_msvs_version ?? "2022";
676 buildEnv.GYP_MSVS_VERSION = buildEnv.GYP_MSVS_VERSION ?? "2022";
677 }
678​
679 yield* Effect.log(
680 `[desktop-artifact] Building ${options.platform}/${options.target} (arch=${options.arch}, version=${appVersion})...`,
681 );
682 yield* runCommand(
683 ChildProcess.make({
684 cwd: stageAppDir,
685 env: buildEnv,
686 ...commandOutputOptions(options.verbose),
687 // Windows needs shell mode to resolve .cmd shims.
688 shell: process.platform === "win32",
689 })`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
690 );
691​
692 const stageDistDir = path.join(stageAppDir, "dist");
693 if (!(yield* fs.exists(stageDistDir))) {
694 return yield* new BuildScriptError({
695 message: `Build completed but dist directory was not found at ${stageDistDir}`,
696 });
697 }
698​
699 const stageEntries = yield* fs.readDirectory(stageDistDir);
700 yield* fs.makeDirectory(options.outputDir, { recursive: true });
701​
702 const copiedArtifacts: string[] = [];
703 for (const entry of stageEntries) {
704 const from = path.join(stageDistDir, entry);
705 const stat = yield* fs.stat(from).pipe(Effect.catch(() => Effect.succeed(null)));
706 if (!stat || stat.type !== "File") continue;
707​
708 const to = path.join(options.outputDir, entry);
709 yield* fs.copyFile(from, to);
710 copiedArtifacts.push(to);
711 }
712​
713 if (copiedArtifacts.length === 0) {
714 return yield* new BuildScriptError({
715 message: `Build completed but no files were produced in ${stageDistDir}`,
716 });
717 }
718​
719 yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
720 Effect.annotateLogs({ artifacts: copiedArtifacts }),
721 );
722});
723​
724const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
725 platform: Flag.choice("platform", BuildPlatform.literals).pipe(
726 Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
727 Flag.optional,
728 ),
729 target: Flag.string("target").pipe(
730 Flag.withDescription(
731 "Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
732 ),
733 Flag.optional,
734 ),
735 arch: Flag.choice("arch", BuildArch.literals).pipe(
736 Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
737 Flag.optional,
738 ),
739 buildVersion: Flag.string("build-version").pipe(
740 Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),
741 Flag.optional,
742 ),
743 outputDir: Flag.string("output-dir").pipe(
744 Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
745 Flag.optional,
746 ),
747 skipBuild: Flag.boolean("skip-build").pipe(
748 Flag.withDescription(
749 "Skip `bun run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
750 ),
751 Flag.optional,
752 ),
753 keepStage: Flag.boolean("keep-stage").pipe(
754 Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
755 Flag.optional,
756 ),
757 signed: Flag.boolean("signed").pipe(
758 Flag.withDescription(
759 "Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
760 ),
761 Flag.optional,
762 ),
763 verbose: Flag.boolean("verbose").pipe(
764 Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
765 Flag.optional,
766 ),
767}).pipe(
768 Command.withDescription("Build a desktop artifact for T3 Code."),
769 Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
770);
771​
772const cliRuntimeLayer = Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer);
773​
774Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
775 Effect.scoped,
776 Effect.provide(cliRuntimeLayer),
777 NodeRuntime.runMain,
778);