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