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

build-desktop-artifact.ts

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