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

cli-external-packages.test.ts

310 lines11.4 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 { findEsmImportsOfExternalPackages } from "./cli-executable-imports.ts";
13​
14import {
15 isRuntimeExternalCliDependency,
16 findInlinedExternalPackages,
17 selectCliRuntimeExternalDependencies,
18 shouldBundleCliDependency,
19} from "./cli-external-packages.ts";
20​
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// fff-node -> @ff-labs/fff-bin-*), so reading only `dependencies` would check
24// 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 "@napi-rs/keyring",
52 "@clerk/electron-passkeys",
53 "node-addon-api",
54 ]) {
55 assert.strictEqual(shouldBundleCliDependency(id), false, id);
56 }
57 });
58​
59 it("treats prefix-matched siblings as external", () => {
60 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
61 });
62});
63​
64describe("selectCliRuntimeExternalDependencies", () => {
65 it("keeps only runtime-external dependency roots for the Windows sidecar", () => {
66 assert.deepStrictEqual(
67 selectCliRuntimeExternalDependencies({
68 "@ff-labs/fff-node": "2.0.0",
69 effect: "3.0.0",
70 "node-pty": "4.0.0",
71 }),
72 {
73 "@ff-labs/fff-node": "2.0.0",
74 "node-pty": "4.0.0",
75 },
76 );
77 });
78​
79 it("selects every external root declared by the server", () => {
80 assert.deepStrictEqual(
81 Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
82 [
83 "@cursor/sdk",
84 "@ff-labs/fff-node",
85 "@napi-rs/keyring",
86 "node-pty",
87 "playwright-core",
88 "undici",
89 ],
90 );
91 });
92});
93​
94it.layer(NodeServices.layer)("external package dependency closure", (it) => {
95 // Read manifests off disk from the pnpm store rather than resolving them.
96 // `require("<name>/package.json")` cannot do this job: under pnpm isolation a
97 // transitive package (node-addon-api, ffi-rs) is not reachable by name from
98 // this file at all, and an `exports` map can refuse the `/package.json`
99 // subpath outright (@ff-labs/fff-node).
100 const readInstalledPackages = Effect.gen(function* () {
101 const fileSystem = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const storeDir = path.resolve(
104 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
105 "../../node_modules/.pnpm",
106 );
107​
108 // The store holds regular files too (lock.yaml), so a path built under one
109 // raises ENOTDIR rather than reporting absence.
110 const isPresent = (candidate: string) =>
111 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
112​
113 const installed = new Map<string, PackageManifest>();
114 if (!(yield* isPresent(storeDir))) return installed;
115​
116 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
117 const modulesDir = path.join(storeDir, entry, "node_modules");
118 if (!(yield* isPresent(modulesDir))) continue;
119​
120 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
121 const names = owner.startsWith("@")
122 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
123 (scoped) => `${owner}/${scoped}`,
124 )
125 : [owner];
126​
127 for (const name of names) {
128 if (installed.has(name)) continue;
129 const manifestPath = path.join(modulesDir, name, "package.json");
130 if (!(yield* isPresent(manifestPath))) continue;
131 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
132 }
133 }
134 }
135 return installed;
136 }).pipe(Effect.cached, Effect.runSync);
137​
138 // Runtime-external only. The build-only entries resolve `bun:*` and are never
139 // loaded by Node, so their closure genuinely does not need to be external.
140 const isRuntimeExternal = isRuntimeExternalCliDependency;
141​
142 // A cold walk of the pnpm store can exceed the root timeout when the Windows
143 // lane runs four filesystem-heavy workspace suites at once.
144 it.effect(
145 "finds the runtime-external packages on disk",
146 () =>
147 Effect.gen(function* () {
148 const installed = yield* readInstalledPackages;
149 const found = [...installed.keys()].filter(isRuntimeExternal);
150​
151 for (const required of ["node-pty", "node-addon-api"]) {
152 assert.ok(
153 found.includes(required),
154 `expected ${required} in the pnpm store; the closure check is only meaningful if it can read these (found ${found.length})`,
155 );
156 }
157 }),
158 120_000,
159 );
160​
161 it.effect("keeps every runtime dependency of an external package external too", () =>
162 Effect.gen(function* () {
163 const installed = yield* readInstalledPackages;
164 const violations: string[] = [];
165 const seen = new Set<string>();
166 const queue = [...installed.keys()].filter(isRuntimeExternal);
167​
168 for (const name of queue) {
169 if (seen.has(name)) continue;
170 seen.add(name);
171​
172 const manifest = installed.get(name);
173 if (!manifest) continue;
174​
175 const declared = {
176 ...(manifest.dependencies ?? {}),
177 ...(manifest.optionalDependencies ?? {}),
178 ...(manifest.peerDependencies ?? {}),
179 };
180 for (const dependency of Object.keys(declared)) {
181 if (!isRuntimeExternal(dependency)) {
182 violations.push(`${name} -> ${dependency}`);
183 }
184 if (!seen.has(dependency)) queue.push(dependency);
185 }
186 }
187​
188 assert.deepStrictEqual(
189 violations,
190 [],
191 `these dependencies of external packages would be bundled away and fail to resolve under WSL: ${violations.join(", ")}`,
192 );
193 }),
194 );
195});
196​
197describe("findInlinedExternalPackages", () => {
198 const region = (path: string) => `//#region ${path}
199var x = 1;
200//#endregion
201`;
202​
203 it("flags an external package that was inlined", () => {
204 const source =
205 region("../../node_modules/.pnpm/node-addon-api@7.1.1/node_modules/node-addon-api/index.js") +
206 region(
207 "../../node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js",
208 );
209 const result = findInlinedExternalPackages(source);
210​
211 assert.deepStrictEqual(result.inlined, ["node-addon-api", "node-gyp-build-optional-packages"]);
212 assert.strictEqual(result.regionCount, 2);
213 });
214​
215 it("flags scoped external packages", () => {
216 const result = findInlinedExternalPackages(
217 region("../../node_modules/@ff-labs/fff-node/dist/src/index.js"),
218 );
219 assert.deepStrictEqual(result.inlined, ["@ff-labs/fff-node"]);
220 });
221​
222 it("ignores packages that are meant to be bundled", () => {
223 const source =
224 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
225 region("../../src/server/main.ts");
226 const result = findInlinedExternalPackages(source);
227​
228 assert.deepStrictEqual(result.inlined, []);
229 assert.strictEqual(result.regionCount, 2);
230 });
231​
232 it("reports the packages that were inlined, not just the violations", () => {
233 const source =
234 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
235 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
236 region("../../src/server/main.ts");
237 const result = findInlinedExternalPackages(source);
238​
239 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
240 assert.deepStrictEqual(result.inlined, []);
241 });
242​
243 it("does not report the pnpm store directory as a package", () => {
244 const result = findInlinedExternalPackages(
245 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js"),
246 );
247 assert.deepStrictEqual(result.inlinedPackages, ["effect"]);
248 });
249​
250 it("reports no regions when the marker format is absent", () => {
251 const result = findInlinedExternalPackages("var x = 1; // node_modules/node-pty/lib.js");
252 assert.strictEqual(result.regionCount, 0);
253 assert.deepStrictEqual(result.inlined, []);
254 });
255});
256​
257describe("findEsmImportsOfExternalPackages", () => {
258 it("flags static and dynamic imports of file-backed packages", () => {
259 const source = [
260 'import { FileFinder } from "@ff-labs/fff-node";',
261 'import * as fs from "fs";',
262 'import { createRequire } from "node:module";',
263 'const pty = () => import("node-pty");',
264 'const data = () => import("@ff-labs/fff-bin-linux-x64-gnu", { with: { type: "json" } });',
265 'const lazy = () => import(/* @vite-ignore */ "ffi-rs");',
266 'const local = () => import("./chunk-abc.mjs");',
267 ].join("\n");
268​
269 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
270 "@ff-labs/fff-bin-linux-x64-gnu",
271 "@ff-labs/fff-node",
272 "ffi-rs",
273 "node-pty",
274 ]);
275 });
276​
277 it("flags side-effect imports and re-exports too", () => {
278 const source = ['import "msgpackr-extract";', 'export { load } from "ffi-rs";'].join("\n");
279 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
280 "ffi-rs",
281 "msgpackr-extract",
282 ]);
283 });
284​
285 it("ignores imports inside generated extension source and comments", () => {
286 const source = [
287 'const extension = `import { Type } from "typebox";\nimport type { ExtensionAPI } from "@earendil-works/pi-coding-agent";`;',
288 '// import "comment-only";',
289 "const example = 'import(\"string-only\")';",
290 'const interpolated = `source ${import("real-package")}`;',
291 ].join("\n");
292 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), ["real-package"]);
293 });
294​
295 it("allows optional dynamic Bun built-ins but rejects static imports", () => {
296 assert.deepStrictEqual(
297 findEsmImportsOfExternalPackages('const load = () => import("bun:sqlite");'),
298 [],
299 );
300 assert.deepStrictEqual(
301 findEsmImportsOfExternalPackages('import { Database } from "bun:sqlite";'),
302 ["bun:sqlite"],
303 );
304 });
305​
306 it("does not mistake createRequire calls for imports", () => {
307 const source = 'const { FileFinder } = createRequire(import.meta.url)("@ff-labs/fff-node");';
308 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), []);
309 });
310});