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

cli-external-packages.test.ts

275 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 {
11 CLI_EXTERNAL_PACKAGE_PREFIXES,
12 CLI_EXTERNAL_PACKAGE_UNPACK_GLOBS,
13 CLI_RUNTIME_EXTERNAL_PREFIXES,
14 findInlinedExternalPackages,
15 shouldBundleCliDependency,
16} from "./cli-external-packages.ts";
17​
18// Only the field this test cares about; decoding ignores everything else.
19// optionalDependencies matter as much as dependencies here: every native family
20// in the list declares its actual platform bindings there (ffi-rs -> @yuuang/*,
21// msgpackr-extract -> @msgpackr-extract/*, fff-node -> @ff-labs/fff-bin-*), so
22// reading only `dependencies` would check nothing for exactly those packages.
23const PackageManifest = Schema.Struct({
24 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
25 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
26 peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
27});
28type PackageManifest = typeof PackageManifest.Type;
29​
30const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
31​
32describe("shouldBundleCliDependency", () => {
33 it("bundles ordinary runtime dependencies", () => {
34 for (const id of ["effect", "@effect/platform", "hono", "@t3tools/shared/hostProcess"]) {
35 assert.strictEqual(shouldBundleCliDependency(id), true, id);
36 }
37 });
38​
39 it("never bundles node: builtins", () => {
40 assert.strictEqual(shouldBundleCliDependency("node:fs"), false);
41 });
42​
43 it("leaves native addons and their dlopen wrappers external", () => {
44 for (const id of [
45 "node-pty",
46 "ffi-rs",
47 "@yuuang/ffi-rs-win32-x64-msvc",
48 "@ff-labs/fff-node",
49 "@clerk/electron-passkeys",
50 "msgpackr-extract",
51 "@msgpackr-extract/msgpackr-extract-win32-x64",
52 ]) {
53 assert.strictEqual(shouldBundleCliDependency(id), false, id);
54 }
55 });
56​
57 it("leaves bun-only entry points external", () => {
58 assert.strictEqual(shouldBundleCliDependency("@effect/platform-bun"), false);
59 assert.strictEqual(shouldBundleCliDependency("@effect/sql-sqlite-bun"), false);
60 });
61​
62 // The real package is `node-gyp-build-optional-packages`, reached by prefix.
63 // Matching it as external while failing to unpack it is invisible on the
64 // Windows primary (which reads app.asar) and breaks only under WSL.
65 it("treats prefix-matched siblings as external", () => {
66 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
67 });
68});
69​
70describe("CLI_EXTERNAL_PACKAGE_UNPACK_GLOBS", () => {
71 it("unpacks every external prefix from both the top level and the pnpm store", () => {
72 for (const prefix of CLI_EXTERNAL_PACKAGE_PREFIXES) {
73 assert.include(CLI_EXTERNAL_PACKAGE_UNPACK_GLOBS, `node_modules/${prefix}*/**/*`, prefix);
74 assert.include(
75 CLI_EXTERNAL_PACKAGE_UNPACK_GLOBS,
76 `node_modules/.pnpm/**/node_modules/${prefix}*/**/*`,
77 prefix,
78 );
79 }
80 });
81​
82 // Without the trailing `*` the globs stop covering prefix-matched siblings,
83 // which is exactly how a package ends up external but not unpacked.
84 it("keeps the trailing wildcard that matches prefix siblings", () => {
85 assert.include(CLI_EXTERNAL_PACKAGE_UNPACK_GLOBS, "node_modules/node-gyp-build*/**/*");
86 });
87});
88​
89// The failure this guards is invisible on Windows and fatal under WSL.
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 exists only inside
94// app.asar — which the Windows primary reads transparently under
95// ELECTRON_RUN_AS_NODE, and plain `node` under WSL cannot.
96//
97// Found the hard way: node-gyp-build-optional-packages requires detect-libc,
98// which was bundled. Windows was fine; WSL got 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 (detect-libc, msgpackr-extract, 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 is also what asarUnpack globs target, so this
107 // reads the same tree the build packages.
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 it.effect("finds the runtime-external packages on disk", () =>
154 Effect.gen(function* () {
155 const installed = yield* readInstalledPackages;
156 const found = [...installed.keys()].filter(isRuntimeExternal);
157​
158 // Without this the closure check below can pass vacuously: if nothing is
159 // read, nothing is checked. These are the packages whose closure actually
160 // broke WSL, so require them by name.
161 for (const required of ["node-pty", "node-gyp-build-optional-packages", "detect-libc"]) {
162 assert.ok(
163 found.includes(required),
164 `expected ${required} in the pnpm store; the closure check is only meaningful if it can read these (found ${found.length})`,
165 );
166 }
167 }),
168 );
169​
170 it.effect("keeps every runtime dependency of an external package external too", () =>
171 Effect.gen(function* () {
172 const installed = yield* readInstalledPackages;
173 const violations: string[] = [];
174 const seen = new Set<string>();
175 // Seeded from what is actually installed and matches a prefix, so scoped
176 // prefixes like "@yuuang/" and "@ff-labs/" are covered too. Seeding from
177 // the prefix strings themselves would skip every scoped entry, since a
178 // prefix is not a package name.
179 const queue = [...installed.keys()].filter(isRuntimeExternal);
180​
181 for (const name of queue) {
182 if (seen.has(name)) continue;
183 seen.add(name);
184​
185 const manifest = installed.get(name);
186 if (!manifest) continue;
187​
188 const declared = {
189 ...(manifest.dependencies ?? {}),
190 ...(manifest.optionalDependencies ?? {}),
191 ...(manifest.peerDependencies ?? {}),
192 };
193 for (const dependency of Object.keys(declared)) {
194 if (!isRuntimeExternal(dependency)) {
195 violations.push(`${name} -> ${dependency}`);
196 }
197 if (!seen.has(dependency)) queue.push(dependency);
198 }
199 }
200​
201 assert.deepStrictEqual(
202 violations,
203 [],
204 `these dependencies of external packages would be bundled away and fail to resolve under WSL: ${violations.join(", ")}`,
205 );
206 }),
207 );
208});
209​
210// Configuring the bundler is not the same as checking what it emitted. These
211// exercise the scanner against the marker shape rolldown actually produces.
212describe("findInlinedExternalPackages", () => {
213 const region = (path: string) => `//#region ${path}
214var x = 1;
215//#endregion
216`;
217​
218 it("flags an external package that was inlined", () => {
219 const source =
220 region("../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js") +
221 region(
222 "../../node_modules/.pnpm/msgpackr-extract@3.0.4/node_modules/msgpackr-extract/index.js",
223 );
224 const result = findInlinedExternalPackages(source);
225​
226 assert.deepStrictEqual(result.inlined, ["detect-libc", "msgpackr-extract"]);
227 assert.strictEqual(result.regionCount, 2);
228 });
229​
230 it("flags scoped external packages", () => {
231 const result = findInlinedExternalPackages(
232 region("../../node_modules/@ff-labs/fff-node/dist/src/index.js"),
233 );
234 assert.deepStrictEqual(result.inlined, ["@ff-labs/fff-node"]);
235 });
236​
237 it("ignores packages that are meant to be bundled", () => {
238 const source =
239 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
240 region("../../src/server/main.ts");
241 const result = findInlinedExternalPackages(source);
242​
243 assert.deepStrictEqual(result.inlined, []);
244 assert.strictEqual(result.regionCount, 2);
245 });
246​
247 // regionCount is what separates "clean" from "this scan went blind because the
248 // marker format changed". A caller that ignores it gets a vacuous pass.
249 // The scan has to answer both directions. Checking only that externals are
250 // absent still passes on a bundle that externalized everything, which is the
251 // failure this whole change prevents.
252 it("reports the packages that were inlined, not just the violations", () => {
253 const source =
254 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
255 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
256 region("../../src/server/main.ts");
257 const result = findInlinedExternalPackages(source);
258​
259 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
260 assert.deepStrictEqual(result.inlined, []);
261 });
262​
263 it("does not report the pnpm store directory as a package", () => {
264 const result = findInlinedExternalPackages(
265 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js"),
266 );
267 assert.deepStrictEqual(result.inlinedPackages, ["effect"]);
268 });
269​
270 it("reports no regions when the marker format is absent", () => {
271 const result = findInlinedExternalPackages("var x = 1; // node_modules/detect-libc/lib.js");
272 assert.strictEqual(result.regionCount, 0);
273 assert.deepStrictEqual(result.inlined, []);
274 });
275});