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