Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

build-cli-archive.ts

627 lines24.4 KB

1#!/usr/bin/env node
2/** Runtime archives must run without host Node, npm, or compilers. */
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as Config from "effect/Config";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as PlatformError from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14import { Command, Flag } from "effect/cli";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16​
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { fromYaml } from "@t3tools/shared/schemaYaml";
19import { resolveSpawnCommand } from "@t3tools/shared/shell";
20import rootPackageJson from "../package.json" with { type: "json" };
21import serverPackageJson from "../apps/server/package.json" with { type: "json" };
22​
23import {
24 createStagePatchedDependencies,
25 createStageWorkspaceConfig,
26 resolveFffNativeDependencies,
27 STAGE_INSTALL_ARGS,
28} from "./build-desktop-artifact.ts";
29import { assertLinuxArm64PageCompatibility } from "./lib/linux-arm64-sea.ts";
30import { selectCliRuntimeExternalDependencies } from "./lib/cli-external-packages.ts";
31import { signWithJsign } from "./lib/windows-jsign.ts";
32import { windowsSystemTar } from "./lib/windows-tar.ts";
33import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
34​
35const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
36const BuildArch = Schema.Literals(["arm64", "x64"]);
37type BuildPlatform = typeof BuildPlatform.Type;
38type BuildArch = typeof BuildArch.Type;
39​
40const WorkspaceConfig = Schema.Struct({
41 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
42 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
43 patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
44 allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
45});
46const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
47const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
48const StageWorkspaceConfig = Schema.Struct({
49 supportedArchitectures: Schema.Struct({
50 os: Schema.Array(Schema.String),
51 cpu: Schema.Array(Schema.String),
52 libc: Schema.optional(Schema.Array(Schema.String)),
53 }),
54 allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
55 patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
56 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
57 nodeLinker: Schema.optional(Schema.Literals(["hoisted"])),
58});
59const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));
60​
61const RepoRoot = Effect.service(Path.Path).pipe(
62 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
63);
64​
65export class CliArchiveLinuxArm64PageError extends Schema.TaggedError<CliArchiveLinuxArm64PageError>()(
66 "CliArchiveLinuxArm64PageError",
67 { executablePath: Schema.String, cause: Schema.Defect() },
68) {
69 override get message(): string {
70 return `${this.executablePath} is not page-compatible with Linux arm64.`;
71 }
73​
74export class CliArchiveCommandFailedError extends Schema.TaggedError<CliArchiveCommandFailedError>()(
75 "CliArchiveCommandFailedError",
76 { command: Schema.String, exitCode: Schema.Int },
77) {
78 override get message(): string {
79 return `${this.command} exited with code ${this.exitCode}.`;
80 }
82​
83export class CliArchiveInputMissingError extends Schema.TaggedError<CliArchiveInputMissingError>()(
84 "CliArchiveInputMissingError",
85 { inputPath: Schema.String, hint: Schema.String },
86) {
87 override get message(): string {
88 return `Missing ${this.inputPath}. ${this.hint}`;
89 }
91​
92export function cliArchivePlatformKey(platform: BuildPlatform, arch: BuildArch): string {
93 const nodePlatform = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
94 return `${nodePlatform}-${arch}`;
96​
97export function cliArchiveStem(version: string, platform: BuildPlatform, arch: BuildArch): string {
98 return `t3-${version}-${cliArchivePlatformKey(platform, arch)}`;
100​
101export function cliArchiveFileName(version: string, platform: BuildPlatform, arch: BuildArch) {
102 // Minimal hosts may lack xz, but tar and Node zlib handle gzip without it.
103 return `${cliArchiveStem(version, platform, arch)}.${platform === "win" ? "zip" : "tar.gz"}`;
105​
106const runCommand = Effect.fn("runCommand")(function* (
107 command: ChildProcess.Command,
108 label: string,
109) {
110 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
111 const child = yield* spawner.spawn(
112 ChildProcess.isStandardCommand(command)
113 ? ChildProcess.make(command.command, command.args, {
114 ...command.options,
115 stdout: "inherit",
116 stderr: "inherit",
117 })
118 : command,
119 );
120 const exitCode = Number(yield* child.exitCode);
121 if (exitCode !== 0) {
122 return yield* new CliArchiveCommandFailedError({ command: label, exitCode });
123 }
124});
125​
126const requireInput = Effect.fn("requireInput")(function* (inputPath: string, hint: string) {
127 const fs = yield* FileSystem.FileSystem;
128 if (!(yield* fs.exists(inputPath))) {
129 return yield* new CliArchiveInputMissingError({ inputPath, hint });
130 }
131});
132​
133/** Installed runtimes cannot rely on pnpm's store layout surviving archival. */
134const stageRuntimeExternals = Effect.fn("stageRuntimeExternals")(function* (input: {
135 readonly repoRoot: string;
136 readonly stageDir: string;
137 readonly platform: BuildPlatform;
138 readonly arch: BuildArch;
139 readonly version: string;
140}) {
141 const fs = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 const workspace = yield* decodeWorkspaceConfig(
144 yield* fs.readFileString(path.join(input.repoRoot, "pnpm-workspace.yaml")),
145 );
146 const catalog = workspace.catalog ?? {};
147 const serverDependencies = resolveCatalogDependencies(
148 serverPackageJson.dependencies,
149 catalog,
150 "apps/server",
151 );
152 const fffNodeVersion = serverDependencies["@ff-labs/fff-node"];
153 if (fffNodeVersion === undefined) {
154 return yield* new CliArchiveInputMissingError({
155 inputPath: "apps/server/package.json#dependencies['@ff-labs/fff-node']",
156 hint: "The archive stages fff's platform binary from this version.",
157 });
158 }
159 const dependencies = {
160 ...selectCliRuntimeExternalDependencies(serverDependencies),
161 ...resolveFffNativeDependencies(input.platform, input.arch, fffNodeVersion),
162 };
163 const patchedDependencies = createStagePatchedDependencies(
164 workspace.patchedDependencies ?? {},
165 dependencies,
166 );
167​
168 yield* fs.writeFileString(
169 path.join(input.stageDir, "package.json"),
170 `${yield* encodeJsonString({
171 name: "t3-runtime",
172 version: input.version,
173 private: true,
174 packageManager: rootPackageJson.packageManager,
175 dependencies,
176 })}\n`,
177 );
178 yield* fs.writeFileString(
179 path.join(input.stageDir, "pnpm-workspace.yaml"),
180 yield* encodeStageWorkspaceConfig({
181 ...createStageWorkspaceConfig({
182 platform: input.platform,
183 arch: input.arch,
184 ...(workspace.allowBuilds ? { allowBuilds: workspace.allowBuilds } : {}),
185 patchedDependencies,
186 overrides: resolveCatalogDependencies(workspace.overrides ?? {}, catalog, "apps/server"),
187 }),
188 nodeLinker: "hoisted",
189 }),
190 );
191 if (Object.keys(patchedDependencies).length > 0) {
192 yield* fs.copy(path.join(input.repoRoot, "patches"), path.join(input.stageDir, "patches"));
193 }
194​
195 const install = yield* resolveSpawnCommand("vp", [...STAGE_INSTALL_ARGS]);
196 yield* runCommand(
197 ChildProcess.make(install.command, install.args, {
198 cwd: input.stageDir,
199 shell: install.shell,
200 stdout: "inherit",
201 stderr: "inherit",
202 }),
203 "vp install --prod (cli archive runtime externals)",
204 );
205​
206 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
207 const prebuildsDir = path.join(input.stageDir, "node_modules/node-pty/prebuilds");
208 const foreignPrebuilds = (yield* fs
209 .readDirectory(prebuildsDir)
210 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter(
211 (entry) => entry !== platformKey,
212 );
213 for (const entry of [
214 "package.json",
215 "pnpm-workspace.yaml",
216 "pnpm-lock.yaml",
217 "patches",
218 "node_modules/.pnpm",
219 "node_modules/.modules.yaml",
220 "node_modules/.pnpm-workspace-state-v1.json",
221 "node_modules/.bin",
222 ...foreignPrebuilds.map((entry) => `node_modules/node-pty/prebuilds/${entry}`),
223 ]) {
224 yield* fs.remove(path.join(input.stageDir, entry), { recursive: true, force: true });
225 }
226 // Nested .bin shims are unused symlinks, which the npm registry rejects in tarballs.
227 yield* removeNestedBinDirectories(fs, path, path.join(input.stageDir, "node_modules"));
228});
229​
230const removeNestedBinDirectories = Effect.fn("build-cli-archive.removeNestedBinDirectories")(
231 function* (
232 fs: FileSystem.FileSystem,
233 path: Path.Path,
234 root: string,
235 ): Effect.fn.Return<void, PlatformError.PlatformError> {
236 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
237 for (const entry of entries) {
238 const child = path.join(root, entry);
239 if (entry === ".bin") {
240 yield* fs.remove(child, { recursive: true, force: true });
241 continue;
242 }
243 const info = yield* fs.stat(child).pipe(Effect.option);
244 if (Option.isSome(info) && info.value.type === "Directory") {
245 yield* removeNestedBinDirectories(fs, path, child);
246 }
247 }
248 },
249);
250​
251const stageWebClient = Effect.fn("stageWebClient")(function* (source: string, target: string) {
252 const fs = yield* FileSystem.FileSystem;
253 const path = yield* Path.Path;
254 yield* fs.copy(source, target);
255 const maps = (yield* fs.readDirectory(target, { recursive: true })).filter((entry) =>
256 entry.endsWith(".map"),
257 );
258 for (const entry of maps) {
259 yield* fs.remove(path.join(target, entry), { force: true });
260 }
261});
262​
263/** Node links libatomic.so.1, which Ubuntu server and container images lack, so t3 carries its own. */
264const bundleLinuxLibatomic = Effect.fn("bundleLinuxLibatomic")(function* (input: {
265 readonly repoRoot: string;
266 readonly contentDir: string;
267 readonly executablePath: string;
268}) {
269 const fs = yield* FileSystem.FileSystem;
270 const path = yield* Path.Path;
271 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
272 const ldd = yield* spawner.string(ChildProcess.make("ldd", [input.executablePath]));
273 const source = /libatomic\.so\.1 => (\/\S+)/.exec(ldd)?.[1];
274 if (source === undefined) {
275 return yield* new CliArchiveInputMissingError({
276 inputPath: "libatomic.so.1",
277 hint: `ldd did not resolve it for ${input.executablePath}. Install libatomic1 on the build host.`,
278 });
279 }
280 yield* fs.makeDirectory(path.join(input.contentDir, "lib"));
281 yield* fs.copyFile(source, path.join(input.contentDir, "lib/libatomic.so.1"));
282​
283 // libatomic is GPL-3.0-or-later WITH GCC-exception-3.1, so its terms and source travel with it.
284 const owner = yield* spawner.string(
285 ChildProcess.make("dpkg-query", ["-S", yield* fs.realPath(source)]),
286 );
287 // Keep the arch qualifier so a second installed arch cannot add its own line.
288 const [, qualifiedPkg, pkg] = /^(([^:\s]+)(?::[^:\s]+)?): /.exec(owner) ?? [];
289 const versions = qualifiedPkg
290 ? yield* spawner.string(
291 ChildProcess.make("dpkg-query", [
292 "-W",
293 "-f=${Version} ${source:Package} ${source:Version}",
294 qualifiedPkg,
295 ]),
296 )
297 : "";
298 const [version, sourcePackage, sourceVersion] = versions.trim().split(" ");
299 if (!pkg || !version || !sourcePackage || !sourceVersion) {
300 return yield* new CliArchiveInputMissingError({
301 inputPath: `dpkg package for ${source}`,
302 hint: "The archive copies libatomic's license and source reference from its Ubuntu package.",
303 });
304 }
305 const header = [
306 `libatomic.so.1 is copied from the Ubuntu package ${pkg} ${version}.`,
307 `Source: https://launchpad.net/ubuntu/+source/${sourcePackage}/${sourceVersion}`,
308 ].join("\n");
309 // Vendored because CI runner images strip /usr/share/doc.
310 const license = yield* fs.readFileString(
311 path.join(input.repoRoot, "scripts/licenses/libatomic.LICENSE"),
312 );
313 yield* fs.writeFileString(
314 path.join(input.contentDir, "lib/libatomic.so.1.LICENSE"),
315 `${header}\n\n${license}`,
316 );
317​
318 // RUNPATH resolves through symlinks and is not inherited by child processes, unlike LD_LIBRARY_PATH.
319 yield* runCommand(
320 ChildProcess.make("patchelf", ["--set-rpath", "$ORIGIN/lib", input.executablePath]),
321 "patchelf --set-rpath",
322 );
323 yield* Effect.log(`[cli-archive] Bundled ${source} as lib/libatomic.so.1.`);
324});
325​
326const MacSigningConfig = Config.all({
327 identity: Config.String("T3CODE_CLI_MAC_SIGN_IDENTITY").pipe(Config.option),
328 appleApiKey: Config.String("APPLE_API_KEY").pipe(Config.option),
329 appleApiKeyId: Config.String("APPLE_API_KEY_ID").pipe(Config.option),
330 appleApiIssuer: Config.String("APPLE_API_ISSUER").pipe(Config.option),
331});
332​
333/** Apple Silicon requires signed binaries; notarization's hardened runtime also requires every native addon signed. */
334const signMacArchiveContents = Effect.fn("signMacArchiveContents")(function* (input: {
335 readonly repoRoot: string;
336 readonly contentDir: string;
337 readonly executablePath: string;
338}) {
339 const fs = yield* FileSystem.FileSystem;
340 const path = yield* Path.Path;
341 const signing = yield* MacSigningConfig;
342 const identity = Option.getOrUndefined(signing.identity)?.trim() || "-";
343​
344 const entitlements = path.join(input.repoRoot, "apps/server/resources/cli-entitlements.plist");
345 const libraries = (yield* fs.readDirectory(input.contentDir, { recursive: true }))
346 .filter(
347 (entry) =>
348 entry.endsWith(".node") ||
349 entry.endsWith(".dylib") ||
350 entry.endsWith("spawn-helper") ||
351 entry.endsWith("t3-resource-monitor"),
352 )
353 .map((entry) => path.join(input.contentDir, entry));
354​
355 for (const target of [...libraries, input.executablePath]) {
356 yield* runCommand(
357 ChildProcess.make("codesign", [
358 "--force",
359 "--sign",
360 identity,
361 ...(identity === "-" ? [] : ["--options", "runtime", "--timestamp"]),
362 ...(target === input.executablePath ? ["--entitlements", entitlements] : []),
363 target,
364 ]),
365 `codesign ${path.relative(input.contentDir, target)}`,
366 );
367 }
368 if (identity === "-") {
369 yield* Effect.log("[cli-archive] Signed ad hoc (no T3CODE_CLI_MAC_SIGN_IDENTITY).");
370 return;
371 }
372​
373 const apiKey = Option.getOrUndefined(signing.appleApiKey);
374 const apiKeyId = Option.getOrUndefined(signing.appleApiKeyId);
375 const apiIssuer = Option.getOrUndefined(signing.appleApiIssuer);
376 if (!apiKey || !apiKeyId || !apiIssuer) {
377 yield* Effect.logWarning(
378 "[cli-archive] Developer ID signed but not notarized (missing APPLE_API_KEY*).",
379 );
380 return;
381 }
382 // notarytool requires an archive; bare executables rely on online tickets because they cannot be stapled.
383 const notarizeZip = path.join(path.dirname(input.executablePath), ".notarize-t3.zip");
384 yield* runCommand(
385 ChildProcess.make("ditto", ["-c", "-k", "--keepParent", input.executablePath, notarizeZip]),
386 "ditto (notarization zip)",
387 );
388 yield* runCommand(
389 ChildProcess.make("xcrun", [
390 "notarytool",
391 "submit",
392 notarizeZip,
393 "--key",
394 apiKey,
395 "--key-id",
396 apiKeyId,
397 "--issuer",
398 apiIssuer,
399 "--wait",
400 ]),
401 "notarytool submit",
402 ).pipe(Effect.ensuring(fs.remove(notarizeZip, { force: true }).pipe(Effect.ignore)));
403 yield* Effect.log("[cli-archive] Notarized t3.");
404});
405​
406const WindowsSigningConfig = Config.all({
407 endpoint: Config.String("AZURE_TRUSTED_SIGNING_ENDPOINT").pipe(Config.option),
408 accountName: Config.String("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME").pipe(Config.option),
409 certificateProfileName: Config.String("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME").pipe(
410 Config.option,
411 ),
412});
413​
414/** Node's Windows --build-sea leaves a stale Authenticode offset pointing into rebuilt resources instead of certificates. */
415const stripStaleAuthenticodeEntry = Effect.fn("stripStaleAuthenticodeEntry")(function* (
416 executablePath: string,
417) {
418 const fs = yield* FileSystem.FileSystem;
419 const bytes = yield* fs.readFile(executablePath);
420 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
421 const peOffset = view.getUint32(0x3c, true);
422 if (view.getUint32(peOffset, true) !== 0x00004550) {
423 return yield* new CliArchiveInputMissingError({
424 inputPath: executablePath,
425 hint: "Expected a PE executable to strip the stale signature entry from.",
426 });
427 }
428 const optionalHeader = peOffset + 24;
429 const magic = view.getUint16(optionalHeader, true);
430 // PE data directories start at +112 (PE32+) or +96 (PE32); index 4 holds the certificate offset and size.
431 const securityEntry = optionalHeader + (magic === 0x20b ? 112 : 96) + 4 * 8;
432 const offset = view.getUint32(securityEntry, true);
433 const size = view.getUint32(securityEntry + 4, true);
434 if (offset === 0 && size === 0) return;
435 if (offset + size === bytes.byteLength) {
436 // Let signtool replace intact certificate tables ending at EOF.
437 return;
438 }
439 view.setUint32(securityEntry, 0, true);
440 view.setUint32(securityEntry + 4, 0, true);
441 yield* fs.writeFile(executablePath, bytes);
442 yield* Effect.log(
443 `[cli-archive] Cleared the stale Authenticode entry (offset ${String(offset)}, size ${String(size)}) left by --build-sea.`,
444 );
445});
446​
447const signWindowsExecutable = Effect.fn("signWindowsExecutable")(function* (
448 executablePath: string,
449) {
450 const signing = yield* WindowsSigningConfig;
451 const endpoint = Option.getOrUndefined(signing.endpoint);
452 const accountName = Option.getOrUndefined(signing.accountName);
453 const profile = Option.getOrUndefined(signing.certificateProfileName);
454 if (!endpoint || !accountName || !profile) {
455 yield* Effect.log("[cli-archive] Windows signing disabled (missing Azure Trusted Signing).");
456 return;
457 }
458 yield* stripStaleAuthenticodeEntry(executablePath);
459 if ((yield* HostProcess.Platform) !== "win32") {
460 yield* signWithJsign(executablePath);
461 yield* Effect.log("[cli-archive] Signed t3.exe (Azure Trusted Signing via jsign).");
462 return;
463 }
464 const quote = (value: string) => `'${value.replaceAll("'", "''")}'`;
465 const script = [
466 "$ErrorActionPreference = 'Stop';",
467 "Invoke-TrustedSigning",
468 `-Endpoint ${quote(endpoint)}`,
469 `-CodeSigningAccountName ${quote(accountName)}`,
470 `-CertificateProfileName ${quote(profile)}`,
471 "-FileDigest 'SHA256'",
472 "-TimestampRfc3161 'http://timestamp.acs.microsoft.com'",
473 "-TimestampDigest 'SHA256'",
474 `-Files ${quote(executablePath)}`,
475 ].join(" ");
476 yield* runCommand(
477 ChildProcess.make("pwsh", ["-NoProfile", "-NonInteractive", "-Command", script]),
478 "Invoke-TrustedSigning t3.exe",
479 );
480 yield* Effect.log("[cli-archive] Signed t3.exe (Azure Trusted Signing).");
481});
482​
483const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: {
484 readonly platform: BuildPlatform;
485 readonly arch: BuildArch;
486 readonly version: string;
487 readonly outputDir: string;
488 readonly resourceMonitorDir: Option.Option<string>;
489}) {
490 const fs = yield* FileSystem.FileSystem;
491 const path = yield* Path.Path;
492 const repoRoot = yield* RepoRoot;
493 const serverDir = path.join(repoRoot, "apps/server");
494 const executableName = input.platform === "win" ? "t3.exe" : "t3";
495 // tsdown suffixes cross-built executables; prefer the exact target over the plain host build.
496 const targetKey = `${input.platform === "mac" ? "darwin" : input.platform}-${input.arch}`;
497 const targetExecutable = path.join(
498 serverDir,
499 "dist-exe",
500 `t3-${targetKey}${input.platform === "win" ? ".exe" : ""}`,
501 );
502 // The unsuffixed executable is valid only for the host platform and architecture.
503 const hostPlatform = yield* HostProcess.Platform;
504 const hostKey = `${hostPlatform === "win32" ? "win" : hostPlatform}-${yield* HostProcess.Architecture}`;
505 const builtExecutable = (yield* fs.exists(targetExecutable))
506 ? targetExecutable
507 : targetKey === hostKey
508 ? path.join(serverDir, "dist-exe", executableName)
509 : targetExecutable;
510 const webClient = path.join(serverDir, "dist/client");
511 const resourceMonitorDir = Option.getOrElse(input.resourceMonitorDir, () =>
512 path.join(serverDir, "dist/resource-monitor"),
513 );
514​
515 yield* requireInput(
516 builtExecutable,
517 `Run \`node apps/server/scripts/cli.ts build-exe${targetKey === hostKey ? "" : ` --target ${targetKey}`}\` first.`,
518 );
519 yield* requireInput(path.join(webClient, "index.html"), "Run `vp run --filter t3 build` first.");
520 yield* requireInput(
521 resourceMonitorDir,
522 "Build the resource monitor or pass --resource-monitor-dir.",
523 );
524​
525 const stem = cliArchiveStem(input.version, input.platform, input.arch);
526 const stageRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-archive-" });
527 const contentDir = path.join(stageRoot, stem);
528 yield* fs.makeDirectory(contentDir, { recursive: true });
529​
530 yield* Effect.log(`[cli-archive] Staging ${stem}...`);
531 yield* fs.copyFile(builtExecutable, path.join(contentDir, executableName));
532 yield* stageWebClient(webClient, path.join(contentDir, "client"));
533 yield* fs.copy(resourceMonitorDir, path.join(contentDir, "resource-monitor"));
534 yield* stageRuntimeExternals({
535 repoRoot,
536 stageDir: contentDir,
537 platform: input.platform,
538 arch: input.arch,
539 version: input.version,
540 });
541​
542 const executablePath = path.join(contentDir, executableName);
543 if (input.platform === "linux") {
544 yield* bundleLinuxLibatomic({ repoRoot, contentDir, executablePath });
545 }
546 // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048
547 if (input.platform === "linux" && input.arch === "arm64") {
548 const bytes = yield* fs.readFile(executablePath);
549 yield* Effect.try({
550 try: () => assertLinuxArm64PageCompatibility(bytes),
551 catch: (cause) => new CliArchiveLinuxArm64PageError({ executablePath, cause }),
552 });
553 }
554 if (input.platform === "mac") {
555 yield* signMacArchiveContents({ repoRoot, contentDir, executablePath });
556 } else if (input.platform === "win") {
557 yield* signWindowsExecutable(executablePath);
558 }
559 if (input.platform !== "win") {
560 yield* fs.chmod(executablePath, 0o755);
561 }
562​
563 yield* fs.makeDirectory(input.outputDir, { recursive: true });
564 const archivePath = path.join(
565 input.outputDir,
566 cliArchiveFileName(input.version, input.platform, input.arch),
567 );
568 yield* fs.remove(archivePath, { force: true });
569 if (input.platform === "win" && hostPlatform !== "win32") {
570 yield* runCommand(
571 ChildProcess.make("zip", ["-q", "-r", "-X", path.resolve(archivePath), stem], {
572 cwd: stageRoot,
573 }),
574 "zip",
575 );
576 } else if (input.platform === "win") {
577 // Windows ships bsdtar, which writes zip natively. Name it by path: under
578 // the Git Bash shell CI uses, a bare `tar` is GNU tar, which neither
579 // writes zip nor accepts a drive-letter path.
580 yield* runCommand(
581 ChildProcess.make(windowsSystemTar(), ["-a", "-c", "-f", archivePath, "-C", stageRoot, stem]),
582 "tar (zip)",
583 );
584 } else {
585 // npm rejects Linux hardlink entries; macOS pnpm clones and bsdtar lacks this flag.
586 yield* runCommand(
587 ChildProcess.make("tar", [
588 ...(input.platform === "linux" ? ["--hard-dereference"] : []),
589 "-czf",
590 archivePath,
591 "-C",
592 stageRoot,
593 stem,
594 ]),
595 "tar (gzip)",
596 );
597 }
598 const stat = yield* fs.stat(archivePath);
599 yield* Effect.log(`[cli-archive] Wrote ${archivePath} (${String(stat.size)} bytes).`);
600 return archivePath;
601});
602​
603const command = Command.make(
604 "build-cli-archive",
605 {
606 platform: Flag.Literals("platform", BuildPlatform.literals),
607 arch: Flag.Literals("arch", BuildArch.literals),
608 version: Flag.String("version").pipe(
609 Flag.withDescription("Release version for the archive name."),
610 ),
611 outputDir: Flag.String("output-dir").pipe(Flag.withDefault("release-cli")),
612 resourceMonitorDir: Flag.String("resource-monitor-dir").pipe(
613 Flag.withDescription(
614 "Directory laid out like dist/resource-monitor (defaults to apps/server/dist/resource-monitor).",
615 ),
616 Flag.optional,
617 ),
618 },
619 (input) => buildCliArchive(input).pipe(Effect.scoped),
620).pipe(Command.withDescription("Package the t3 single-executable into a per-platform archive."));
621​
622if (import.meta.main) {
623 Command.run(command, { version: "0.0.0" }).pipe(
624 Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
625 NodeRuntime.runMain,
626 );