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