GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — t3code/scripts/build-desktop-artifact.ts at main · abmone/t3code Expand file tree/ Copy pathbuild-desktop-artifact.tsMore file actions 3172 lines (2903 loc) · 113 KB / Copy pathbuild-desktop-artifact.tsFile metadata and controls3172 lines (2903 loc) · 113 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #!/usr/bin/env node // @effect-diagnostics nodeBuiltinImport:off - Node's typed junction API avoids Windows symlink privileges while keeping the probe isolated. import * as NodeFSP from "node:fs/promises"; import * as NodeModule from "node:module"; import { createPackageWithOptions, extractAll, getRawHeader, statFile, type DirectoryRecord, } from "@electron/asar"; import { fromYaml } from "@t3tools/shared/schemaYaml"; import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess"; import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import rootPackageJson from "../package.json" with { type: "json" }; import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" }; import serverPackageJson from "../apps/server/package.json" with { type: "json" }; import { applyWebBrandAssets } from "./apply-web-brand-assets.ts"; import { BRAND_ASSET_PATHS, resolveWebAssetBrandForChannel, type WebAssetBrand, } from "./lib/brand-assets.ts"; import { getDefaultBuildArch } from "./lib/build-target-arch.ts"; import { findInlinedExternalPackages, selectCliRuntimeExternalDependencies, } from "./lib/cli-external-packages.ts"; import { loadRepoEnv } from "./lib/public-config.ts"; import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Config from "effect/Config"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import type { PlatformError } from "effect/PlatformError"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { Command, Flag } from "effect/unstable/cli"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; const LINUX_ICON_SIZES = [16, 22, 24, 32, 48, 64, 128, 256, 512] as const; const DESKTOP_APP_ID = "com.t3tools.t3code"; const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u; const BuildPlatform = Schema.Literals(["mac", "linux", "win"]); const BuildArch = Schema.Literals(["arm64", "x64", "universal"]); const WorkspaceConfig = Schema.Struct({ catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)), overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)), patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)), allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)), }); type WorkspaceConfig = typeof WorkspaceConfig.Type; const StageWorkspaceConfig = Schema.Struct({ supportedArchitectures: Schema.Struct({ os: Schema.Array(Schema.String), cpu: Schema.Array(Schema.String), libc: Schema.optional(Schema.Array(Schema.String)), }), // pnpm 11 only reads these from pnpm-workspace.yaml (not package.json#pnpm). // Without allowBuilds the staged `vp install --prod` fails with // ERR_PNPM_IGNORED_BUILDS for packages that have lifecycle scripts. allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)), patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)), overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)), nodeLinker: Schema.optional(Schema.Literals(["hoisted"])), }); type StageWorkspaceConfig = typeof StageWorkspaceConfig.Type; const RepoRoot = Effect.service(Path.Path).pipe( Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))), ); const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig)); const decodeNodePtyManifest = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ version: Schema.String })), ); const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig)); const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const repoRoot = yield* RepoRoot; const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml")); return yield* decodeWorkspaceConfig(workspaceYaml); }); interface DesktopBuildIconAssets { readonly macIconPng: string; readonly linuxIconPng: string; readonly windowsIconIco: string; } interface PlatformConfig { readonly cliFlag: "--mac" | "--linux" | "--win"; readonly defaultTarget: string; readonly archChoices: ReadonlyArray<typeof BuildArch.Type>; } export function resolveResourceMonitorRustTargets( platform: typeof BuildPlatform.Type, arch: typeof BuildArch.Type, ): ReadonlyArray<string> { if (platform === "mac") { if (arch === "universal") { return ["aarch64-apple-darwin", "x86_64-apple-darwin"]; } return [arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin"]; } if (platform === "linux") { return [arch === "arm64" ? "aarch64-unknown-linux-gnu" : "x86_64-unknown-linux-gnu"]; } return [arch === "arm64" ? "aarch64-pc-windows-msvc" : "x86_64-pc-windows-msvc"]; } export function resourceMonitorExecutableName(platform: typeof BuildPlatform.Type): string { return platform === "win" ? "t3-resource-monitor.exe" : "t3-resource-monitor"; } const PLATFORM_CONFIG: Record<typeof BuildPlatform.Type, PlatformConfig> = { mac: { cliFlag: "--mac", defaultTarget: "dmg", archChoices: ["arm64", "x64", "universal"], }, linux: { cliFlag: "--linux", defaultTarget: "AppImage", archChoices: ["x64", "arm64"], }, win: { cliFlag: "--win", defaultTarget: "nsis", archChoices: ["x64", "arm64"], }, }; interface BuildCliInput { readonly platform: Option.Option<typeof BuildPlatform.Type>; readonly target: Option.Option<string>; readonly arch: Option.Option<typeof BuildArch.Type>; readonly buildVersion: Option.Option<string>; readonly outputDir: Option.Option<string>; readonly skipBuild: Option.Option<boolean>; readonly keepStage: Option.Option<boolean>; readonly signed: Option.Option<boolean>; readonly verbose: Option.Option<boolean>; readonly mockUpdates: Option.Option<boolean>; readonly mockUpdateServerPort: Option.Option<number>; readonly wslPrebuild: Option.Option<string>; } function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined { if (hostPlatform === "darwin") return "mac"; if (hostPlatform === "linux") return "linux"; if (hostPlatform === "win32") return "win"; return undefined; } const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof BuildPlatform.Type) { const config = PLATFORM_CONFIG[platform]; if (!config) { return "x64"; } return yield* getDefaultBuildArch(platform, config); }); export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedErrorClass<MacPasskeySigningConfigurationResolutionError>()( "MacPasskeySigningConfigurationResolutionError", { cause: Schema.Defect(), }, ) { static fromCause( cause: unknown, ): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError { return isMacPasskeySigningConfigurationError(cause) ? cause : new MacPasskeySigningConfigurationResolutionError({ cause }); } override get message(): string { return "Failed to resolve macOS passkey signing configuration."; } } export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedErrorClass<ClerkPasskeyNativePackageMissingError>()( "ClerkPasskeyNativePackageMissingError", { packageName: Schema.String, binaryFileName: Schema.String, packageEntryPath: Schema.String, platform: BuildPlatform, arch: BuildArch, cause: Schema.Defect(), }, ) { override get message(): string { return `Clerk passkey native package is missing: ${this.packageName}`; } } export class UnsupportedHostBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedHostBuildPlatformError>()( "UnsupportedHostBuildPlatformError", { hostPlatform: Schema.String, }, ) { override get message(): string { return `Unsupported host platform '${this.hostPlatform}'.`; } } export class UnsupportedDesktopBuildArchitectureError extends Schema.TaggedErrorClass<UnsupportedDesktopBuildArchitectureError>()( "UnsupportedDesktopBuildArchitectureError", { platform: BuildPlatform, arch: BuildArch, supportedArchitectures: Schema.Array(BuildArch), }, ) { override get message(): string { return `Unsupported architecture '${this.arch}' for ${this.platform}.`; } } const InvalidMockUpdateServerPortReason = Schema.Literals([ "not-numeric", "not-integer", "out-of-range", ]); export class InvalidMockUpdateServerPortError extends Schema.TaggedErrorClass<InvalidMockUpdateServerPortError>()( "InvalidMockUpdateServerPortError", { reason: InvalidMockUpdateServerPortReason, inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), cause: Schema.Defect(), }, ) { override get message(): string { return "Invalid mock update server port."; } static fromConfigValue(configuredPort: string, cause: unknown) { return new InvalidMockUpdateServerPortError({ reason: invalidMockUpdateServerPortReason(configuredPort), inputLength: configuredPort.length, cause, }); } } export class BuildCommandFailedError extends Schema.TaggedErrorClass<BuildCommandFailedError>()( "BuildCommandFailedError", { command: Schema.String, exitCode: Schema.Int, stdoutTail: Schema.optionalKey(Schema.String), stderrTail: Schema.optionalKey(Schema.String), }, ) { override get message(): string { const outputSections = [ `Command: ${this.command}`, formatOutputSection("stdout", this.stdoutTail ?? ""), formatOutputSection("stderr", this.stderrTail ?? ""), ].filter((section): section is string => section !== undefined); const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : ""; return `Command exited with non-zero exit code (${this.exitCode})${outputSuffix}`; } } export class ResourceMonitorBuildOutputMissingError extends Schema.TaggedErrorClass<ResourceMonitorBuildOutputMissingError>()( "ResourceMonitorBuildOutputMissingError", { binaryPath: Schema.String, rustTarget: Schema.String, platform: BuildPlatform, arch: BuildArch, }, ) { override get message(): string { return `Resource monitor build for ${this.rustTarget} did not produce ${this.binaryPath}.`; } } const desktopIconPlatformNames = { mac: "macOS", linux: "Linux", win: "Windows", } satisfies Record<typeof BuildPlatform.Type, string>; export class DesktopIconSourceMissingError extends Schema.TaggedErrorClass<DesktopIconSourceMissingError>()( "DesktopIconSourceMissingError", { platform: BuildPlatform, sourcePath: Schema.String, }, ) { override get message(): string { return `Desktop ${desktopIconPlatformNames[this.platform]} icon source is missing at ${this.sourcePath}`; } } export class DesktopDmgBackgroundSourceMissingError extends Schema.TaggedErrorClass<DesktopDmgBackgroundSourceMissingError>()( "DesktopDmgBackgroundSourceMissingError", { channel: Schema.Literals(["latest", "nightly"]), sourcePath: Schema.String, }, ) { override get message(): string { return `Desktop ${this.channel} DMG background source is missing at ${this.sourcePath}`; } } export class BundledClientAssetsMissingError extends Schema.TaggedErrorClass<BundledClientAssetsMissingError>()( "BundledClientAssetsMissingError", { indexPath: Schema.String, missingFiles: Schema.Array(Schema.String), }, ) { override get message(): string { const preview = this.missingFiles.slice(0, 6).join(", "); const suffix = this.missingFiles.length > 6 ? ` (+${this.missingFiles.length - 6} more)` : ""; return `Bundled client references missing files in ${this.indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`; } } export class UnsupportedDesktopBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedDesktopBuildPlatformError>()( "UnsupportedDesktopBuildPlatformError", { platform: Schema.String, }, ) { override get message(): string { return `Unsupported platform '${this.platform}'.`; } } const dependencyResolutionDescriptions = { "server-production": "production dependencies", "workspace-overrides": "overrides", "desktop-runtime": "desktop runtime dependencies", } as const; const DependencyResolutionKind = Schema.Literals([ "server-production", "workspace-overrides", "desktop-runtime", ]); export class DesktopBuildDependencyResolutionError extends Schema.TaggedErrorClass<DesktopBuildDependencyResolutionError>()( "DesktopBuildDependencyResolutionError", { kind: DependencyResolutionKind, manifestPath: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { return `Could not resolve ${dependencyResolutionDescriptions[this.kind]} from ${this.manifestPath}.`; } } export class MissingServerProductionDependenciesError extends Schema.TaggedErrorClass<MissingServerProductionDependenciesError>()( "MissingServerProductionDependenciesError", { manifestPath: Schema.String, }, ) { override get message(): string { return `Could not resolve production dependencies from ${this.manifestPath}.`; } } const DesktopBuildInputArtifact = Schema.Literals([ "desktop-dist", "desktop-resources", "server-dist", "bundled-server-client", ]); type DesktopBuildInputArtifact = typeof DesktopBuildInputArtifact.Type; const desktopBuildInputArtifactNames = { "desktop-dist": "desktopDist", "desktop-resources": "desktopResources", "server-dist": "serverDist", "bundled-server-client": "bundled server client", } satisfies Record<DesktopBuildInputArtifact, string>; /** * Imported by every server module, so it is inlined in any correctly bundled * build. Its absence means the bundle went back to externalizing its * dependencies, which the sidecar's selected runtime closure does not cover. */ const BUNDLE_SELF_CONTAINED_SENTINEL = "effect"; const BUNDLE_SELF_CHECK_TIMEOUT = Duration.seconds(120); const WINDOWS_PRIMARY_NATIVE_PROBE_TIMEOUT = Duration.seconds(30); const WINDOWS_PRIMARY_FFF_PROBE_SOURCE = ` const { join } = await import("node:path"); const { pathToFileURL } = await import("node:url"); const { FileFinder } = await import(pathToFileURL(process.argv[1]).href); const probeRoot = process.argv[2]; const result = FileFinder.create({ basePath: probeRoot, frecencyDbPath: join(probeRoot, "frecency.mdb"), historyDbPath: join(probeRoot, "history.mdb"), disableWatch: true, disableMmapCache: true, disableContentIndexing: true, }); if (!result.ok) throw new Error(result.error); result.value.destroy(); `; export class ExternalizedBundleError extends Schema.TaggedErrorClass<ExternalizedBundleError>()( "ExternalizedBundleError", { sentinel: Schema.String, inlinedPackageCount: Schema.Number }, ) { override get message(): string { return `The server bundle did not inline "${this.sentinel}" (${this.inlinedPackageCount} packages inlined). The bundle is meant to be self-contained apart from the runtime externals; if its dependencies are external again they will be absent from the sidecar, and the backend will fail with ERR_MODULE_NOT_FOUND. Check the deps.alwaysBundle wiring in apps/server/vite.config.ts.`; } } export class BundleNotSelfContainedError extends Schema.TaggedErrorClass<BundleNotSelfContainedError>()( "BundleNotSelfContainedError", { exitCode: Schema.Number, output: Schema.String }, ) { override get message(): string { return `The packaged server bundle could not load from the isolated, extracted sidecar (exit ${this.exitCode}). Anything it imports that is neither a Node built-in nor in the selected runtime-external closure is unavailable to both backends. Output: ${this.output}`; } } export class InlinedNativePackageError extends Schema.TaggedErrorClass<InlinedNativePackageError>()( "InlinedNativePackageError", { packages: Schema.Array(Schema.String) }, ) { override get message(): string { return `The server bundle inlined packages that load native binaries: ${this.packages.join(", ")}. A node-gyp-build style loader resolves prebuilds relative to its own file, so inlined into a chunk it finds none and the importer quietly falls back to a slower JS path. Add them to CLI_RUNTIME_EXTERNAL_PREFIXES in scripts/lib/cli-external-packages.ts so they stay external and are staged in the sidecar.`; } } export class InlinedExternalPackageError extends Schema.TaggedErrorClass<InlinedExternalPackageError>()( "InlinedExternalPackageError", { packages: Schema.Array(Schema.String) }, ) { override get message(): string { return `The server bundle inlined packages that must stay external: ${this.packages.join(", ")}. These are native addons or their loaders; inlined, they resolve prebuilds relative to the bundle and silently lose native acceleration. Check the deps.neverBundle wiring in apps/server/vite.config.ts.`; } } export class MissingDesktopBuildInputError extends Schema.TaggedErrorClass<MissingDesktopBuildInputError>()( "MissingDesktopBuildInputError", { artifact: DesktopBuildInputArtifact, artifactPath: Schema.String, buildCommand: Schema.Literal("vp run build:desktop"), }, ) { override get message(): string { return `Missing ${desktopBuildInputArtifactNames[this.artifact]} at ${this.artifactPath}. Run '${this.buildCommand}' first.`; } } export class MacProvisioningProfileNotFoundError extends Schema.TaggedErrorClass<MacProvisioningProfileNotFoundError>()( "MacProvisioningProfileNotFoundError", { provisioningProfilePath: Schema.String, }, ) { override get message(): string { return `macOS provisioning profile not found: ${this.provisioningProfilePath}`; } } export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedErrorClass<DesktopBuildDistDirectoryMissingError>()( "DesktopBuildDistDirectoryMissingError", { distPath: Schema.String, platform: BuildPlatform, arch: BuildArch, }, ) { override get message(): string { return `Build completed but dist directory was not found at ${this.distPath}`; } } export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedErrorClass<DesktopBuildNoArtifactsProducedError>()( "DesktopBuildNoArtifactsProducedError", { distPath: Schema.String, platform: BuildPlatform, arch: BuildArch, }, ) { override get message(): string { return `Build completed but no files were produced in ${this.distPath}`; } } export class WslNodePtyPrebuildMissingError extends Schema.TaggedErrorClass<WslNodePtyPrebuildMissingError>()( "WslNodePtyPrebuildMissingError", { prebuildPath: Schema.String, }, ) { override get message(): string { return `WSL node-pty prebuild not found at ${this.prebuildPath}.`; } } export class WindowsServerSidecarPackError extends Schema.TaggedErrorClass<WindowsServerSidecarPackError>()( "WindowsServerSidecarPackError", { asarPath: Schema.String, cause: Schema.optionalKey(Schema.Defect()), }, ) { override get message(): string { return `Failed to pack the Windows server sidecar at ${this.asarPath}.`; } } export class WindowsPrimaryNativeProbeError extends Schema.TaggedErrorClass<WindowsPrimaryNativeProbeError>()( "WindowsPrimaryNativeProbeError", { executablePath: Schema.String, exitCode: Schema.Number, output: Schema.String, }, ) { override get message(): string { return `The packaged Windows primary could not load fff from server.asar (exit ${this.exitCode}). Output:\n${this.output}`; } } const WindowsPackagedPayloadValidationReason = Schema.Literals([ "packaged-app-missing", "sidecar-missing", "sidecar-invalid", "unpacked-native-missing", "resource-monitor-missing", "file-limit-exceeded", ]); export class WindowsPackagedPayloadValidationError extends Schema.TaggedErrorClass<WindowsPackagedPayloadValidationError>()( "WindowsPackagedPayloadValidationError", { reason: WindowsPackagedPayloadValidationReason, packagedAppDir: Schema.String, missingFiles: Schema.optionalKey(Schema.Array(Schema.String)), fileCount: Schema.optionalKey(Schema.Int), fileLimit: Schema.optionalKey(Schema.Int), cause: Schema.optionalKey(Schema.Defect()), }, ) { override get message(): string { if (this.reason === "file-limit-exceeded") { return `Windows packaged payload contains ${String(this.fileCount)} files; expected at most ${String(this.fileLimit)}.`; } if (this.reason === "unpacked-native-missing") { return `Windows server sidecar is missing ${String(this.missingFiles?.length ?? 0)} unpacked native files.`; } if (this.reason === "resource-monitor-missing") { return "Windows packaged payload is missing the resource monitor executable."; } if (this.reason === "sidecar-invalid") { return "Windows packaged payload contains an invalid server.asar sidecar."; } if (this.reason === "sidecar-missing") { return "Windows packaged payload is missing resources/server.asar."; } return `Windows packaged application directory was not found at ${this.packagedAppDir}.`; } } export class WslNodePtyManifestReadError extends Schema.TaggedErrorClass<WslNodePtyManifestReadError>()( "WslNodePtyManifestReadError", { manifestPath: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { return `Could not read node-pty version from ${this.manifestPath}.`; } } export class LinuxIconResizeError extends Schema.TaggedErrorClass<LinuxIconResizeError>()( "LinuxIconResizeError", { operation: Schema.Literal("resize"), iconSize: Schema.Int, primaryTool: Schema.Literal("magick"), fallbackTool: Schema.Literal("convert"), cause: Schema.Defect(), }, ) { override get message(): string { return `Failed to ${this.operation} the Linux desktop icon to ${this.iconSize}x${this.iconSize} with \`${this.primaryTool}\` or \`${this.fallbackTool}\`. Install ImageMagick so either tool is available.`; } } const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> => stream.pipe( Stream.decodeText(), Stream.runFold( () => "", (acc, chunk) => acc + chunk, ), ); const COMMAND_OUTPUT_TAIL_LENGTH = 20_000; function appendOutputTail(acc: string, chunk: string): string { const next = acc + chunk; return next.length > COMMAND_OUTPUT_TAIL_LENGTH ? next.slice(-COMMAND_OUTPUT_TAIL_LENGTH) : next; } function formatOutputSection(label: string, output: string): string | undefined { const trimmed = output.trim(); if (!trimmed) return undefined; return `${label} tail:\n${trimmed}`; } const collectCommandStream = <E>( stream: Stream.Stream<Uint8Array, E>, output: NodeJS.WriteStream, verbose: boolean, ): Effect.Effect<string, E> => stream.pipe( Stream.decodeText(), Stream.runFoldEffect( () => "", (acc, chunk) => Effect.as( verbose ? Effect.sync(() => output.write(chunk)) : Effect.void, appendOutputTail(acc, chunk), ), ), ); const spawnAndCollectOutput = Effect.fn("spawnAndCollectOutput")(function* ( command: ChildProcess.Command, ) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const child = yield* spawner.spawn(command); const [stdout, stderr, exitCode] = yield* Effect.all( [ collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode.pipe(Effect.map(Number)), ], { concurrency: "unbounded" }, ); return { stdout, stderr, exitCode } as const; }); const resolveGitCommitHash = Effect.fn("resolveGitCommitHash")(function* (repoRoot: string) { const result = yield* spawnAndCollectOutput( ChildProcess.make("git", ["rev-parse", "--short=12", "HEAD"], { cwd: repoRoot, }), ).pipe( Effect.orElseSucceed(() => ({ stdout: "", stderr: "", exitCode: 1, })), ); if (result.exitCode !== 0) { return "unknown"; } const hash = result.stdout.trim(); if (!/^[0-9a-f]{7,40}$/i.test(hash)) { return "unknown"; } return hash.toLowerCase(); }); const resolvePythonForNodeGyp = Effect.fn("resolvePythonForNodeGyp")(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const hostPlatform = yield* HostProcessPlatform; const env = yield* Config.all({ configuredPython: Config.string("npm_config_python").pipe( Config.orElse(() => Config.string("PYTHON")), Config.option, ), localAppData: Config.string("LOCALAPPDATA").pipe(Config.option), }); const configured = Option.getOrUndefined(env.configuredPython); if (configured && (yield* fs.exists(configured))) { return configured; } if (hostPlatform === "win32") { const localAppData = Option.getOrUndefined(env.localAppData); if (localAppData) { for (const version of ["Python313", "Python312", "Python311", "Python310"]) { const candidate = path.join(localAppData, "Programs", "Python", version, "python.exe"); if (yield* fs.exists(candidate)) { return candidate; } } } } const probe = yield* spawnAndCollectOutput( ChildProcess.make("python", ["-c", "import sys;print(sys.executable)"]), ).pipe( Effect.orElseSucceed(() => ({ stdout: "", stderr: "", exitCode: 1, })), ); if (probe.exitCode !== 0) { return undefined; } const executable = probe.stdout.trim(); if (!executable || !(yield* fs.exists(executable))) { return undefined; } return executable; }); interface ResolvedBuildOptions { readonly platform: typeof BuildPlatform.Type; readonly target: string; readonly arch: typeof BuildArch.Type; readonly version: string | undefined; readonly outputDir: string; readonly skipBuild: boolean; readonly keepStage: boolean; readonly signed: boolean; readonly verbose: boolean; readonly mockUpdates: boolean; readonly mockUpdateServerPort: number | undefined; readonly wslPrebuild: string | undefined; } interface StagePackageJson { readonly name: string; readonly version: string; readonly buildVersion: string; readonly t3codeCommitHash: string; readonly private: true; readonly packageManager: string; readonly description: string; readonly author: string; readonly main: string; readonly build: Record<string, unknown>; readonly dependencies: Record<string, unknown>; readonly devDependencies: { readonly electron: string; }; } export const STAGE_INSTALL_ARGS = ["install", "--prod"] as const; export const DESKTOP_ELECTRON_LANGUAGES = ["en-US"] as const; export const DESKTOP_FILE_EXCLUSIONS = [ // T3 Code always passes the user's installed Claude executable to the SDK, // so the SDK's optional platform packages (each a ~200MB bundled executable) // are dead weight. The trailing dash keeps the SDK's own JS package. "!**/node_modules/@anthropic-ai/claude-agent-sdk-*/**/*", // Windows stages the server sidecar below prod-resources so electron-builder // can copy it using project-relative extraResources matchers. Keep those // staging inputs out of app.asar; they are emitted once at resources/. "!apps/desktop/prod-resources/windows-server", "!apps/desktop/prod-resources/windows-server/**/*", ] as const; // Windows ships the server tree (bundle + node_modules) as a separate // resources/server.asar sidecar instead of loose files: the NSIS installer // then extracts a handful of large archives instead of thousands of small // files, which dominates install (and update) time. The Windows primary runs // the server from inside server.asar via the asar-aware ELECTRON_RUN_AS_NODE // runtime; the WSL backend cannot read asar archives, so enabling WSL lazily // extracts the sidecar to a version-keyed directory (see DesktopWslServerTree). export const WINDOWS_SERVER_ASAR_RESOURCE = "server.asar"; // dlopen/spawn need real files, so native modules, shared libraries, and // helper executables live in the server.asar.unpacked sibling (the standard // asar redirect convention). Everything else stays packed. export const WINDOWS_SERVER_ASAR_UNPACK_GLOB = "{**/*.node,**/*.dll,**/*.exe,**/*.so,**/*.so.*,**/*.dylib}"; // Mirrors DESKTOP_FILE_EXCLUSIONS for the hand-packed sidecar: the Claude SDK // platform packages are dead weight (see above), and node_modules/.bin shims // are never spawned at runtime (and are symlinks on POSIX build hosts, which // the asar extraction path deliberately does not support). export const WINDOWS_SERVER_ASAR_IGNORE_GLOBS = [ "**/node_modules/@anthropic-ai/claude-agent-sdk-*", "**/node_modules/@anthropic-ai/claude-agent-sdk-*/**", "**/node_modules/.bin", "**/node_modules/.bin/**", ] as const; export const WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT = 80; export const WINDOWS_SERVER_RESOURCE_SOURCE_DIR = "apps/desktop/prod-resources/windows-server"; export const WINDOWS_SERVER_EXTRA_RESOURCES = [ { // Copy the archive and its .unpacked sibling from one parent directory. // Mapping the .unpacked directory as an independent FileSet silently // omitted it from Windows packages even though electron-builder copied // the adjacent archive. from: WINDOWS_SERVER_RESOURCE_SOURCE_DIR, to: ".", filter: [WINDOWS_SERVER_ASAR_RESOURCE, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked/**/*`], }, ] as const; export const DESKTOP_EXTRA_RESOURCES = [ { from: "apps/desktop/prod-resources/resource-monitor", to: "resource-monitor", }, ] as const; export interface MacPasskeySigningConfiguration { readonly appId: string; readonly teamId: string; readonly rpDomains: readonly string[]; readonly provisioningProfilePath: string; } export const InvalidMacPasskeyRpDomainReason = Schema.Literals([ "empty", "scheme-not-allowed", "parse-failed", "credentials-not-allowed", "port-not-allowed", "path-not-allowed", "query-not-allowed", "fragment-not-allowed", "hostname-mismatch", ]); export type InvalidMacPasskeyRpDomainReason = typeof InvalidMacPasskeyRpDomainReason.Type; export class InvalidMacPasskeyRpDomainError extends Schema.TaggedErrorClass<InvalidMacPasskeyRpDomainError>()( "InvalidMacPasskeyRpDomainError", { reason: InvalidMacPasskeyRpDomainReason, inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), cause: Schema.optionalKey(Schema.Defect()), }, ) { override get message(): string { return `Invalid passkey RP domain (${this.reason}).`; } } export class InvalidAppleTeamIdError extends Schema.TaggedErrorClass<InvalidAppleTeamIdError>()( "InvalidAppleTeamIdError", { teamId: Schema.String, }, ) { override get message(): string { return `T3CODE_APPLE_TEAM_ID '${this.teamId}' must be a 10-character Apple Developer Team ID.`; } } export class MissingMacPasskeyProvisioningProfileError extends Schema.TaggedErrorClass<MissingMacPasskeyProvisioningProfileError>()( "MissingMacPasskeyProvisioningProfileError", {}, ) { override get message(): string { return "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile."; } } export class MissingMacPasskeyDomainConfigurationError extends Schema.TaggedErrorClass<MissingMacPasskeyDomainConfigurationError>()( "MissingMacPasskeyDomainConfigurationError", {}, ) { override get message(): string { return "T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds."; } } export class InvalidMacPasskeyPublishableKeyError extends Schema.TaggedErrorClass<InvalidMacPasskeyPublishableKeyError>()( "InvalidMacPasskeyPublishableKeyError", { cause: Schema.Defect(), }, ) { override get message(): string { return "T3CODE_CLERK_PUBLISHABLE_KEY is invalid."; } } export class MissingMacPasskeyRpDomainError extends Schema.TaggedErrorClass<MissingMacPasskeyRpDomainError>()( "MissingMacPasskeyRpDomainError", {}, ) { override get message(): string { return "At least one Clerk passkey RP domain is required."; } } export const MacPasskeySigningConfigurationError = Schema.Union([ InvalidMacPasskeyRpDomainError, InvalidAppleTeamIdError, MissingMacPasskeyProvisioningProfileError, MissingMacPasskeyDomainConfigurationError, InvalidMacPasskeyPublishableKeyError, MissingMacPasskeyRpDomainError, ]); export type MacPasskeySigningConfigurationError = typeof MacPasskeySigningConfigurationError.Type; export const isMacPasskeySigningConfigurationError = Schema.is(MacPasskeySigningConfigurationError); function normalizePasskeyRpDomain(value: string): string { const normalized = value.trim().toLowerCase(); const inputLength = value.length; if (normalized.length === 0) { throw new InvalidMacPasskeyRpDomainError({ reason: "empty", inputLength }); } if (/^[a-z][a-z\d+.-]*:\/\//u.test(normalized)) { throw new InvalidMacPasskeyRpDomainError({ reason: "scheme-not-allowed", inputLength, }); } let parsed: URL; try { parsed = new URL(`https://${normalized}`); } catch (cause) { throw new InvalidMacPasskeyRpDomainError({ reason: "parse-failed", inputLength, cause }); } let reason: InvalidMacPasskeyRpDomainReason | undefined; if (parsed.username.length > 0 || parsed.password.length > 0) { reason = "credentials-not-allowed"; } else if (parsed.port.length > 0) { reason = "port-not-allowed"; } else if (parsed.pathname !== "/") { reason = "path-not-allowed"; } else if (parsed.search.length > 0) { reason = "query-not-allowed"; } else if (parsed.hash.length > 0) { reason = "fragment-not-allowed"; } else if (parsed.host !== normalized) { reason = "hostname-mismatch"; } if (reason) { throw new InvalidMacPasskeyRpDomainError({ reason, inputLength }); } return parsed.hostname; } export function resolveMacPasskeySigningConfiguration( env: Readonly<Record<string, string | undefined>>, ): MacPasskeySigningConfiguration { const teamId = env.T3CODE_APPLE_TEAM_ID?.trim().toUpperCase() ?? ""; if (!APPLE_TEAM_ID_PATTERN.test(teamId)) { throw new InvalidAppleTeamIdError({ teamId }); } const provisioningProfilePath = env.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ?? ""; if (provisioningProfilePath.length === 0) { throw new MissingMacPasskeyProvisioningProfileError(); } const configuredRpDomains = env.T3CODE_CLERK_PASSKEY_RP_DOMAINS?.trim(); let rpDomains: readonly string[]; if (configuredRpDomains) { rpDomains = configuredRpDomains.split(",").map(normalizePasskeyRpDomain); } else { const publishableKey = env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim(); if (!publishableKey) { throw new MissingMacPasskeyDomainConfigurationError(); } let hostname: string; try { hostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey); |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |