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