Skip to content

Commit e1cb474

Browse files
build(server): make the CLI bundle loadable as a Node single-executable
Inside a Node SEA, import statements and import() can only resolve built-ins, so the two external native packages (fff-node, node-pty) now load through createRequire. fff-node's exports map only declared an import condition, so the existing patch also adds a require condition. Adds a build-exe subcommand that wraps the bundle with tsdown's exe support and fails if the emitted bundle still imports any file-backed package, since that only surfaces at runtime inside the executable. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 7bd7f99 commit e1cb474

12 files changed

Lines changed: 209 additions & 23 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ node_modules
55
*.log
66
*.tsbuildinfo
77
apps/*/dist
8+
apps/*/dist-exe
89
infra/*/dist
910
.astro
1011
packages/*/dist

‎apps/server/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"scripts": {
1818
"dev": "node --watch src/bin.ts",
1919
"build:bundle": "vp pack && vp pack src/service-launcher.ts --out-dir dist --no-clean",
20+
"build:exe": "node scripts/cli.ts build-exe",
2021
"start": "node dist/bin.mjs",
2122
"typecheck": "tsc --noEmit",
2223
"test": "vp test run"

‎apps/server/scripts/cli.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
resolveWebAssetBrandForPackageVersion,
1616
resolveWebIconOverrides,
1717
} from "../../../scripts/lib/brand-assets.ts";
18+
import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-external-packages.ts";
1819
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
1920
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
2021
import { fromYaml } from "@t3tools/shared/schemaYaml";
@@ -25,6 +26,7 @@ import {
2526
ServerCliCommandExitError,
2627
ServerCliDevelopmentIconSourceMissingError,
2728
ServerCliDevelopmentIconTargetMissingError,
29+
ServerCliExecutableImportError,
2830
ServerCliPublishIconSourceMissingError,
2931
ServerCliPublishIconTargetMissingError,
3032
} from "./cliErrors.ts";
@@ -175,6 +177,50 @@ const buildCmd = Command.make(
175177
}),
176178
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
177179

180+
// ---------------------------------------------------------------------------
181+
// build-exe subcommand
182+
// ---------------------------------------------------------------------------
183+
184+
const buildExeCmd = Command.make(
185+
"build-exe",
186+
{
187+
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
188+
},
189+
(config) =>
190+
Effect.gen(function* () {
191+
const path = yield* Path.Path;
192+
const fs = yield* FileSystem.FileSystem;
193+
const repoRoot = yield* RepoRoot;
194+
const serverDir = path.join(repoRoot, "apps/server");
195+
196+
yield* Effect.log("[cli] Building single-executable...");
197+
const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
198+
yield* runCommand(
199+
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
200+
cwd: serverDir,
201+
env: { ...process.env, T3CODE_PACK_EXE: "1" },
202+
stdout: config.verbose ? "inherit" : "ignore",
203+
stderr: "inherit",
204+
shell: spawnCommand.shell,
205+
}),
206+
);
207+
208+
// The executable can only `import` built-ins. A file-backed import
209+
// passes the bundler and `node dist/bin.mjs`, then throws inside the
210+
// binary, so read the emitted module graph rather than trusting config.
211+
const bundlePath = path.join(serverDir, "dist-exe/bin.mjs");
212+
const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
213+
if (specifiers.length > 0) {
214+
return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
215+
}
216+
yield* Effect.log("[cli] Built dist-exe/t3");
217+
}),
218+
).pipe(
219+
Command.withDescription(
220+
"Build the server as a Node single-executable (needs a Node 25.7+ host for --build-sea).",
221+
),
222+
);
223+
178224
// ---------------------------------------------------------------------------
179225
// publish subcommand
180226
// ---------------------------------------------------------------------------
@@ -309,7 +355,7 @@ const publishCmd = Command.make(
309355

310356
const cli = Command.make("cli").pipe(
311357
Command.withDescription("T3 server build & publish CLI."),
312-
Command.withSubcommands([buildCmd, publishCmd]),
358+
Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
313359
);
314360

315361
Command.run(cli, { version: "0.0.0" }).pipe(

‎apps/server/scripts/cliErrors.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,15 @@ export class ServerCliBuildAssetMissingError extends Schema.TaggedError<ServerCl
6868
return `Missing build asset: ${this.assetPath}. Run the build subcommand first.`;
6969
}
7070
}
71+
72+
export class ServerCliExecutableImportError extends Schema.TaggedError<ServerCliExecutableImportError>()(
73+
"ServerCliExecutableImportError",
74+
{
75+
bundlePath: Schema.String,
76+
specifiers: Schema.Array(Schema.String),
77+
},
78+
) {
79+
override get message(): string {
80+
return `${this.bundlePath} imports file-backed packages that a single-executable cannot resolve: ${this.specifiers.join(", ")}. Load them through createRequire instead.`;
81+
}
82+
}

‎apps/server/src/terminal/NodePtyAdapter.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const spawn = vi.fn(() => ({
1919
onExit: vi.fn(() => ({ dispose: vi.fn() })),
2020
}));
2121

22-
vi.mock("node-pty", () => ({ spawn }));
22+
const fakeNodePty = { spawn } as unknown as typeof import("node-pty");
2323

2424
const makeTestLayer = (platform: NodeJS.Platform = "win32") =>
2525
NodePtyAdapter.layer.pipe(
@@ -28,6 +28,7 @@ const makeTestLayer = (platform: NodeJS.Platform = "win32") =>
2828
NodeServices.layer,
2929
Layer.succeed(HostProcessPlatform, platform),
3030
Layer.succeed(HostProcessArchitecture, "x64"),
31+
Layer.succeed(NodePtyAdapter.NodePtyModuleLoaderRef, () => Promise.resolve(fakeNodePty)),
3132
),
3233
),
3334
);
@@ -125,7 +126,10 @@ it.effect("preserves a caller-provided TERM in the spawn env on win32", () =>
125126
it.effect("reports native module load failures as structured startup defects", () =>
126127
Effect.gen(function* () {
127128
const cause = new Error("native binding could not be loaded");
128-
const exit = yield* NodePtyAdapter.make(() => Promise.reject(cause)).pipe(Effect.exit);
129+
const exit = yield* NodePtyAdapter.make().pipe(
130+
Effect.provideService(NodePtyAdapter.NodePtyModuleLoaderRef, () => Promise.reject(cause)),
131+
Effect.exit,
132+
);
129133

130134
assert.isTrue(Exit.isFailure(exit));
131135
if (Exit.isFailure(exit)) {

‎apps/server/src/terminal/NodePtyAdapter.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as NodeModule from "node:module";
22

3+
import * as Context from "effect/Context";
34
import * as Effect from "effect/Effect";
45
import * as FileSystem from "effect/FileSystem";
56
import * as Layer from "effect/Layer";
@@ -24,10 +25,24 @@ export class NodePtyModuleLoadError extends Schema.TaggedError<NodePtyModuleLoad
2425

2526
type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
2627

28+
// node-pty stays external to the CLI bundle because it dlopens a native
29+
// addon. Inside a Node single-executable, `import()` cannot load files from
30+
// disk (only built-ins resolve), while `require` always reads the real
31+
// filesystem, so both the module and its spawn-helper resolve through it.
32+
const requireForNodePty = NodeModule.createRequire(import.meta.url);
33+
34+
const loadNodePty: NodePtyModuleLoader = () =>
35+
Promise.resolve().then(() => requireForNodePty("node-pty") as typeof import("node-pty"));
36+
37+
/** Injectable so tests can substitute a fake module; `require` bypasses module mocks. */
38+
export const NodePtyModuleLoaderRef = Context.Reference<NodePtyModuleLoader>(
39+
"server/terminal/NodePtyModuleLoader",
40+
{ defaultValue: () => loadNodePty },
41+
);
42+
2743
let didEnsureSpawnHelperExecutable = false;
2844

2945
const resolveNodePtySpawnHelperPath = Effect.gen(function* () {
30-
const requireForNodePty = NodeModule.createRequire(import.meta.url);
3146
const path = yield* Path.Path;
3247
const fs = yield* FileSystem.FileSystem;
3348
const platform = yield* HostProcessPlatform;
@@ -113,9 +128,8 @@ class NodePtyProcess implements PtyAdapter.PtyProcess {
113128
}
114129
}
115130

116-
export const make = Effect.fn("NodePtyAdapter.make")(function* (
117-
loadNodePtyModule: NodePtyModuleLoader = () => import("node-pty"),
118-
) {
131+
export const make = Effect.fn("NodePtyAdapter.make")(function* () {
132+
const loadNodePtyModule = yield* NodePtyModuleLoaderRef;
119133
const fs = yield* FileSystem.FileSystem;
120134
const path = yield* Path.Path;
121135
const platform = yield* HostProcessPlatform;

‎apps/server/src/workspace/WorkspaceSearchIndex.ts‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
import {
2-
type DirItem,
3-
type DirSearchResult,
4-
type FileItem,
5-
FileFinder,
6-
type GrepCursor,
7-
type MixedItem,
8-
type MixedSearchResult,
9-
type Result,
10-
type SearchResult,
1+
import * as NodeModule from "node:module";
2+
3+
import type {
4+
DirItem,
5+
DirSearchResult,
6+
FileItem,
7+
FileFinder as FileFinderType,
8+
GrepCursor,
9+
MixedItem,
10+
MixedSearchResult,
11+
Result,
12+
SearchResult,
1113
} from "@ff-labs/fff-node";
1214
import * as Context from "effect/Context";
1315
import * as Effect from "effect/Effect";
@@ -25,6 +27,13 @@ import type {
2527
} from "@t3tools/contracts";
2628
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
2729

30+
// fff-node stays external to the CLI bundle because it dlopens a native
31+
// library. A static `import` of an external package is a hard error inside a
32+
// Node single-executable (only built-ins resolve there), so load it through
33+
// `require`, which reads from the real filesystem in every runtime.
34+
const requireForFff = NodeModule.createRequire(import.meta.url);
35+
const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
36+
2837
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
2938
const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
3039
const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
@@ -330,7 +339,7 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
330339

331340
const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
332341
cwd: string,
333-
finder: FileFinder,
342+
finder: FileFinderType,
334343
onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
335344
): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
336345
const result = yield* Effect.tryPromise({

‎apps/server/vite.config.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ export { shouldBundleCliDependency };
2323
const repoEnv = loadRepoEnv();
2424
const cliBuildChannel = packageJson.version.includes("-nightly.") ? "nightly" : "latest";
2525

26+
// `build:exe` wraps the same bundle in a Node single-executable. tsdown's exe
27+
// step refuses multi-chunk output and counts the sourcemap as a chunk, and the
28+
// executable needs a host Node that supports `--build-sea` (25.7+), so this is
29+
// a separate mode rather than a second entry in the default build.
30+
const packExecutable = process.env.T3CODE_PACK_EXE === "1";
31+
2632
export default mergeConfig(
2733
baseConfig,
2834
defineConfig({
@@ -37,9 +43,20 @@ export default mergeConfig(
3743
},
3844
pack: {
3945
entry: ["src/bin.ts"],
40-
outDir: "dist",
41-
sourcemap: true,
46+
outDir: packExecutable ? "dist-exe" : "dist",
47+
sourcemap: !packExecutable,
4248
clean: true,
49+
...(packExecutable
50+
? {
51+
exe: {
52+
fileName: "t3",
53+
outDir: "dist-exe",
54+
// The code cache only loads on the platform that produced it, so
55+
// executables are always built natively, never cross-compiled.
56+
seaConfig: { useCodeCache: true },
57+
},
58+
}
59+
: {}),
4360
deps: {
4461
// Both halves are required. `alwaysBundle` forces the JS dependencies in
4562
// (declared deps are external by default, which is what this change is

‎patches/@[email protected]‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,17 @@ index ee181aef5007e4bf34a49479c089ca30f73a320b..327e2c55c83cc4c50d396a3109190ef1
3737
}
3838
}
3939
catch {
40+
diff --git a/package.json b/package.json
41+
--- a/package.json
42+
+++ b/package.json
43+
@@ -8,8 +8,9 @@
44+
"types": "dist/src/index.d.ts",
45+
"exports": {
46+
".": {
47+
+ "types": "./dist/src/index.d.ts",
48+
"import": "./dist/src/index.js",
49+
- "types": "./dist/src/index.d.ts"
50+
+ "require": "./dist/src/index.js"
51+
}
52+
},
53+
"files": [

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)