Open History to see the last commit
1import * as NodeURL from "node:url";
2
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9
10import serverPackageJson from "../../apps/server/package.json" with { type: "json" };
11
12import { findEsmImportsOfExternalPackages } from "./cli-executable-imports.ts";
13
14import {
15 CLI_RUNTIME_EXTERNAL_PREFIXES,
16 findInlinedExternalPackages,
17 selectCliRuntimeExternalDependencies,
18 shouldBundleCliDependency,
19} from "./cli-external-packages.ts";
20
21// Only the field this test cares about; decoding ignores everything else.
22// optionalDependencies matter as much as dependencies here: every native family
23// in the list declares its actual platform bindings there (ffi-rs -> @yuuang/*,
24// fff-node -> @ff-labs/fff-bin-*), so reading only `dependencies` would check
25// nothing for exactly those packages.
26const PackageManifest = Schema.Struct({
27 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
28 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
29 peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
30});
31type PackageManifest = typeof PackageManifest.Type;
32
33const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
34
35describe("shouldBundleCliDependency", () => {
36 it("bundles ordinary runtime dependencies", () => {
37 for (const id of ["effect", "@effect/platform", "hono", "@t3tools/shared/hostProcess"]) {
38 assert.strictEqual(shouldBundleCliDependency(id), true, id);
39 }
40 });
41
42 it("never bundles node: builtins", () => {
43 assert.strictEqual(shouldBundleCliDependency("node:fs"), false);
44 });
45
46 it("leaves native addons and their dlopen wrappers external", () => {
47 for (const id of [
48 "node-pty",
49 "ffi-rs",
50 "@yuuang/ffi-rs-win32-x64-msvc",
51 "@ff-labs/fff-node",
52 "@napi-rs/keyring",
53 "@clerk/electron-passkeys",
54 "node-addon-api",
55 ]) {
56 assert.strictEqual(shouldBundleCliDependency(id), false, id);
57 }
58 });
59
60 // The real package is `node-gyp-build-optional-packages`, reached by prefix.
61 // It is transitive to a selected dependency root, so the runtime closure test
62 // below ensures it follows that root into the sidecar.
63 it("treats prefix-matched siblings as external", () => {
64 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
65 });
66});
67
68describe("selectCliRuntimeExternalDependencies", () => {
69 it("keeps only runtime-external dependency roots for the Windows sidecar", () => {
70 assert.deepStrictEqual(
71 selectCliRuntimeExternalDependencies({
72 "@ff-labs/fff-node": "2.0.0",
73 effect: "3.0.0",
74 "node-pty": "4.0.0",
75 }),
76 {
77 "@ff-labs/fff-node": "2.0.0",
78 "node-pty": "4.0.0",
79 },
80 );
81 });
82
83 it("selects every external root declared by the server", () => {
84 assert.deepStrictEqual(
85 Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
86 ["@ff-labs/fff-node", "@napi-rs/keyring", "node-pty"],
87 );
88 });
89});
90
91// An external package is loaded from the real filesystem, so its own `require`
92// also resolves from the real filesystem. If one of its dependencies was
93// bundled away instead of left external, that dependency does not follow the
94// selected root into the sidecar.
95//
96// Found the hard way: msgpackr-extract's node-gyp-build-optional-packages
97// required detect-libc, which was bundled. Windows was fine; WSL got
98// MODULE_NOT_FOUND.
99it.layer(NodeServices.layer)("external package dependency closure", (it) => {
100 // Read manifests off disk from the pnpm store rather than resolving them.
101 // `require("<name>/package.json")` cannot do this job: under pnpm isolation a
102 // transitive package (node-addon-api, ffi-rs) is not reachable
103 // by name from this file at all, and an `exports` map can refuse the
104 // `/package.json` subpath outright (@ff-labs/fff-node). Both surface as "not
105 // installed", which would let this test skip everything and pass while
106 // checking nothing. The store contains the dependency graph the sidecar's
107 // minimal production install resolves.
108 const readInstalledPackages = Effect.gen(function* () {
109 const fileSystem = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111 const storeDir = path.resolve(
112 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
113 "../../node_modules/.pnpm",
114 );
115
116 // The store holds regular files too (lock.yaml), so a path built under one
117 // raises ENOTDIR rather than reporting absence. That throws on Linux while
118 // Windows quietly returns false, which is exactly the kind of difference
119 // this test exists to catch, so treat any failure as "not there".
120 const isPresent = (candidate: string) =>
121 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
122
123 const installed = new Map<string, PackageManifest>();
124 if (!(yield* isPresent(storeDir))) return installed;
125
126 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
127 const modulesDir = path.join(storeDir, entry, "node_modules");
128 if (!(yield* isPresent(modulesDir))) continue;
129
130 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
131 const names = owner.startsWith("@")
132 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
133 (scoped) => `${owner}/${scoped}`,
134 )
135 : [owner];
136
137 for (const name of names) {
138 if (installed.has(name)) continue;
139 const manifestPath = path.join(modulesDir, name, "package.json");
140 if (!(yield* isPresent(manifestPath))) continue;
141 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
142 }
143 }
144 }
145 return installed;
146 }).pipe(Effect.cached, Effect.runSync);
147
148 // Runtime-external only. The build-only entries resolve `bun:*` and are never
149 // loaded by Node, so their closure genuinely does not need to be external.
150 const isRuntimeExternal = (name: string) =>
151 CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => name.startsWith(prefix));
152
153 // A cold walk of the pnpm store can exceed the root timeout when the Windows
154 // lane runs four filesystem-heavy workspace suites at once.
155 it.effect(
156 "finds the runtime-external packages on disk",
157 () =>
158 Effect.gen(function* () {
159 const installed = yield* readInstalledPackages;
160 const found = [...installed.keys()].filter(isRuntimeExternal);
161
162 // Without this the closure check below can pass vacuously: if nothing is
163 // read, nothing is checked. node-pty is the one native root every
164 // platform ships, and node-addon-api is its transitive runtime
165 // dependency, so require them by name.
166 for (const required of ["node-pty", "node-addon-api"]) {
167 assert.ok(
168 found.includes(required),
169 `expected ${required} in the pnpm store; the closure check is only meaningful if it can read these (found ${found.length})`,
170 );
171 }
172 }),
173 120_000,
174 );
175
176 it.effect("keeps every runtime dependency of an external package external too", () =>
177 Effect.gen(function* () {
178 const installed = yield* readInstalledPackages;
179 const violations: string[] = [];
180 const seen = new Set<string>();
181 // Seeded from what is actually installed and matches a prefix, so scoped
182 // prefixes like "@yuuang/" and "@ff-labs/" are covered too. Seeding from
183 // the prefix strings themselves would skip every scoped entry, since a
184 // prefix is not a package name.
185 const queue = [...installed.keys()].filter(isRuntimeExternal);
186
187 for (const name of queue) {
188 if (seen.has(name)) continue;
189 seen.add(name);
190
191 const manifest = installed.get(name);
192 if (!manifest) continue;
193
194 const declared = {
195 ...(manifest.dependencies ?? {}),
196 ...(manifest.optionalDependencies ?? {}),
197 ...(manifest.peerDependencies ?? {}),
198 };
199 for (const dependency of Object.keys(declared)) {
200 if (!isRuntimeExternal(dependency)) {
201 violations.push(`${name} -> ${dependency}`);
202 }
203 if (!seen.has(dependency)) queue.push(dependency);
204 }
205 }
206
207 assert.deepStrictEqual(
208 violations,
209 [],
210 `these dependencies of external packages would be bundled away and fail to resolve under WSL: ${violations.join(", ")}`,
211 );
212 }),
213 );
214});
215
216// Configuring the bundler is not the same as checking what it emitted. These
217// exercise the scanner against the marker shape rolldown actually produces.
218describe("findInlinedExternalPackages", () => {
219 const region = (path: string) => `//#region ${path}
220var x = 1;
221//#endregion
222`;
223
224 it("flags an external package that was inlined", () => {
225 const source =
226 region("../../node_modules/.pnpm/node-addon-api@7.1.1/node_modules/node-addon-api/index.js") +
227 region(
228 "../../node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js",
229 );
230 const result = findInlinedExternalPackages(source);
231
232 assert.deepStrictEqual(result.inlined, ["node-addon-api", "node-gyp-build-optional-packages"]);
233 assert.strictEqual(result.regionCount, 2);
234 });
235
236 it("flags scoped external packages", () => {
237 const result = findInlinedExternalPackages(
238 region("../../node_modules/@ff-labs/fff-node/dist/src/index.js"),
239 );
240 assert.deepStrictEqual(result.inlined, ["@ff-labs/fff-node"]);
241 });
242
243 it("ignores packages that are meant to be bundled", () => {
244 const source =
245 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
246 region("../../src/server/main.ts");
247 const result = findInlinedExternalPackages(source);
248
249 assert.deepStrictEqual(result.inlined, []);
250 assert.strictEqual(result.regionCount, 2);
251 });
252
253 // regionCount is what separates "clean" from "this scan went blind because the
254 // marker format changed". A caller that ignores it gets a vacuous pass.
255 // The scan has to answer both directions. Checking only that externals are
256 // absent still passes on a bundle that externalized everything, which is the
257 // failure this whole change prevents.
258 it("reports the packages that were inlined, not just the violations", () => {
259 const source =
260 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
261 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
262 region("../../src/server/main.ts");
263 const result = findInlinedExternalPackages(source);
264
265 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
266 assert.deepStrictEqual(result.inlined, []);
267 });
268
269 it("does not report the pnpm store directory as a package", () => {
270 const result = findInlinedExternalPackages(
271 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js"),
272 );
273 assert.deepStrictEqual(result.inlinedPackages, ["effect"]);
274 });
275
276 it("reports no regions when the marker format is absent", () => {
277 const result = findInlinedExternalPackages("var x = 1; // node_modules/node-pty/lib.js");
278 assert.strictEqual(result.regionCount, 0);
279 assert.deepStrictEqual(result.inlined, []);
280 });
281});
282
283// The single-executable build can only `import` built-ins. A file-backed
284// import of an external package passes every bundler check and the regular
285// `node dist/bin.mjs` path, then fails inside the executable, so the scan
286// reads the emitted module graph instead.
287describe("findEsmImportsOfExternalPackages", () => {
288 it("flags static and dynamic imports of file-backed packages", () => {
289 const source = [
290 'import { FileFinder } from "@ff-labs/fff-node";',
291 'import * as fs from "fs";',
292 'import { createRequire } from "node:module";',
293 'const pty = () => import("node-pty");',
294 'const data = () => import("@ff-labs/fff-bin-linux-x64-gnu", { with: { type: "json" } });',
295 'const lazy = () => import(/* @vite-ignore */ "ffi-rs");',
296 'const local = () => import("./chunk-abc.mjs");',
297 ].join("\n");
298
299 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
300 "@ff-labs/fff-bin-linux-x64-gnu",
301 "@ff-labs/fff-node",
302 "ffi-rs",
303 "node-pty",
304 ]);
305 });
306
307 it("flags side-effect imports and re-exports too", () => {
308 const source = ['import "msgpackr-extract";', 'export { load } from "ffi-rs";'].join("\n");
309 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
310 "ffi-rs",
311 "msgpackr-extract",
312 ]);
313 });
314
315 it("ignores imports inside generated extension source and comments", () => {
316 const source = [
317 'const extension = `import { Type } from "typebox";\nimport type { ExtensionAPI } from "@earendil-works/pi-coding-agent";`;',
318 '// import "comment-only";',
319 "const example = 'import(\"string-only\")';",
320 'const interpolated = `source ${import("real-package")}`;',
321 ].join("\n");
322 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), ["real-package"]);
323 });
324
325 it("allows optional dynamic Bun built-ins but rejects static imports", () => {
326 assert.deepStrictEqual(
327 findEsmImportsOfExternalPackages('const load = () => import("bun:sqlite");'),
328 [],
329 );
330 assert.deepStrictEqual(
331 findEsmImportsOfExternalPackages('import { Database } from "bun:sqlite";'),
332 ["bun:sqlite"],
333 );
334 });
335
336 it("does not mistake createRequire calls for imports", () => {
337 const source = 'const { FileFinder } = createRequire(import.meta.url)("@ff-labs/fff-node");';
338 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), []);
339 });
340});