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