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