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

build-desktop-artifact.ts

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