Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cli-external-packages.test.ts

283 lines11.5 KB

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