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