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

cli-external-packages.ts

222 lines9.5 KB

1/**
2 * The single source of truth for packages the server CLI bundle must NOT inline.
3 *
4 * Two consumers derive from this list, and they must never disagree:
5 *
6 * - apps/server/vite.config.ts decides what stays external to the bundle.
7 * - scripts/build-desktop-artifact.ts selects the runtime dependency roots for
8 * the Windows server sidecar.
9 *
10 * A runtime package that is external but absent from the sidecar fails as soon
11 * as Node resolves it from the emitted bundle. Keeping both consumers on one
12 * list prevents packaging from drifting away from the bundle boundary.
13 *
14 * Entries are matched as prefixes (`id.startsWith(prefix)`), so they also cover
15 * a package's platform-specific siblings — `node-gyp-build` covers
16 * `node-gyp-build-optional-packages`, `@yuuang/` covers every `ffi-rs-*` binding.
17 */
18/**
19 * External because Node actually loads them from disk at runtime.
20 *
21 * Native addons (.node), the JS wrappers that dlopen them by real path, and —
22 * critically — the ordinary JS packages those wrappers require. An external
23 * package is loaded from the real filesystem, so its own `require` also
24 * resolves from the real filesystem; a dependency that was bundled away exists
25 * only inside the emitted bundle and is unreachable there. This closure is
26 * enforced by a test, not by inspection.
27 */
28export const CLI_RUNTIME_EXTERNAL_PREFIXES = [
29 "node-pty",
30 "ffi-rs",
31 "@yuuang/",
32 "@ff-labs/",
33 "@clerk/electron-passkeys",
34 "@msgpackr-extract/",
35 "msgpackr-extract",
36 "node-gyp-build",
37 "node-addon-api",
38 // Required by node-gyp-build-optional-packages. Not native, but in the
39 // closure: without it, WSL gets MODULE_NOT_FOUND while Windows is fine.
40 "detect-libc",
41 // ws's optional accelerators. Nothing in this repo declares them, so they are
42 // not in the staged production install and the packaged app does not ship
43 // them either way -- ws wraps the require in try/catch and falls back to its
44 // JS paths. They are listed because they were being inlined from the dev
45 // store: both carry binding.gyp and prebuilds and load through
46 // node-gyp-build, and a native loader inlined into a bundle chunk searches
47 // for prebuilds that cannot be beside it. Listing them keeps that from
48 // becoming real if either is ever declared as a dependency.
49 "bufferutil",
50 "utf-8-validate",
51] as const;
52​
53export function isRuntimeExternalCliDependency(id: string): boolean {
54 return CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => id.startsWith(prefix));
56​
57/**
58 * Bun's own module namespace, supplied by the Bun runtime rather than by disk.
59 *
60 * `@effect/platform-bun` and `@effect/sql-sqlite-bun` used to be external for
61 * exactly one reason: they import `bun` and `bun:sqlite`, which cannot resolve
62 * while bundling for Node. Externalizing the packages to dodge that was wrong.
63 * Both import `effect`, so a Bun-hosted server loaded a *second* `effect` from
64 * node_modules beside the bundle. Effect hangs each request's pre-response
65 * handler off a module-level WeakMap, so the bundled copy wrote handlers the
66 * platform server's copy never read: CORS headers, gzip and auth headers all
67 * vanished from real responses while OPTIONS preflight (answered inline, no
68 * WeakMap) kept working.
69 *
70 * Externalizing the `bun:*` specifiers instead keeps a single `effect` graph.
71 * Nothing has to resolve them at build time, and nothing has to resolve them
72 * under Node either: every import of a Bun module sits behind a
73 * `typeof Bun !== "undefined"` dynamic import, so it lands in a chunk that only
74 * a Bun-hosted server loads.
75 */
76export function isBunRuntimeModule(id: string): boolean {
77 return id === "bun" || id.startsWith("bun:");
79​
80/**
81 * True when `id` must stay out of the bundle.
82 *
83 * This has to be wired to the bundler's `neverBundle`, not just to
84 * `alwaysBundle`. `alwaysBundle` only forces packages IN — returning false from
85 * it means "no opinion", and the default then applies: a declared dependency
86 * stays external, but a transitive one gets bundled. That is how
87 * msgpackr-extract, node-gyp-build-optional-packages and detect-libc ended up
88 * inlined while node-pty (a declared dependency) stayed external.
89 */
90export function isExternalCliDependency(id: string): boolean {
91 return isBunRuntimeModule(id) || isRuntimeExternalCliDependency(id);
93​
94/** True when the CLI bundle should inline `id` rather than leave it external. */
95export function shouldBundleCliDependency(id: string): boolean {
96 if (id.startsWith("node:")) return false;
97 return !isExternalCliDependency(id);
99​
100/** Select direct dependency roots whose runtime closure belongs in the sidecar. */
101export function selectCliRuntimeExternalDependencies(
102 dependencies: Readonly<Record<string, string>>,
103): Record<string, string> {
104 return Object.fromEntries(
105 Object.entries(dependencies).filter(([name]) => isRuntimeExternalCliDependency(name)),
106 );
108​
109/**
110 * Scan an emitted bundle chunk for runtime-external packages that were inlined.
111 *
112 * Configuring the bundler is not the same as checking what it produced. The
113 * `alwaysBundle` predicate only forces packages IN; returning false from it
114 * means "no opinion", so a transitive dependency still gets bundled by default.
115 * msgpackr-extract, node-gyp-build-optional-packages and detect-libc were
116 * inlined that way while every list-based test passed, which is why this reads
117 * the artifact instead.
118 *
119 * `regionCount` is reported so the caller can tell "nothing was inlined" apart
120 * from "the marker format changed and this scan no longer sees anything".
121 *
122 * `inlinedPackages` is every package seen in a region, which lets the caller
123 * check the opposite direction too. Verifying only that externals are absent
124 * would still pass if the bundler reverted to leaving everything external: the
125 * scan would see source-file regions, report nothing inlined, and the packaged
126 * backends would then fail with ERR_MODULE_NOT_FOUND because those packages
127 * are not in the selected sidecar closure either.
128 */
129export function findInlinedExternalPackages(source: string): {
130 readonly regionCount: number;
131 readonly inlined: ReadonlyArray<string>;
132 readonly inlinedPackages: ReadonlyArray<string>;
133} {
134 // Rolldown marks each inlined module with a `//#region <path>` comment.
135 const regionPattern = /\/\/#region\s+(\S+)/g;
136 const packagePattern = /node_modules\/((?:@[^/\s]+\/)?[^/\s]+)\//g;
137​
138 let regionCount = 0;
139 const inlined = new Set<string>();
140 const inlinedPackages = new Set<string>();
141 for (const region of source.matchAll(regionPattern)) {
142 regionCount += 1;
143 const regionPath = region[1] ?? "";
144 for (const candidate of regionPath.matchAll(packagePattern)) {
145 const name = candidate[1];
146 if (name === undefined || name === ".pnpm") continue;
147 inlinedPackages.add(name);
148 if (isExternalCliDependency(name)) inlined.add(name);
149 }
150 }
151​
152 return {
153 regionCount,
154 inlined: [...inlined].sort(),
155 inlinedPackages: [...inlinedPackages].sort(),
156 };
158​
159/**
160 * Walk the emitted chunk graph and report Bun modules the Node runtime can reach.
161 *
162 * Bundling `@effect/platform-bun` and `@effect/sql-sqlite-bun` moved a
163 * `bun:sqlite` import from node_modules into the bundle. That is only safe
164 * because rolldown keeps it in a chunk reached solely through `import()`, which
165 * Node never evaluates. Nothing else enforces that: a stray static import of
166 * `@effect/sql-sqlite-bun/SqliteClient` from an eagerly loaded module would
167 * hoist `bun:sqlite` into the entry chunk and every `node bin.mjs` would die
168 * with ERR_UNSUPPORTED_ESM_URL_SCHEME. Rolldown only warns about the merge
169 * (INEFFECTIVE_DYNAMIC_IMPORT) and still exits 0.
170 *
171 * So this follows static edges only — `import`/`export ... from "./chunk.mjs"`
172 * — from the entry chunks, exactly the graph Node loads eagerly, and reports
173 * any Bun specifier inside it. Dynamic `import("./chunk.mjs")` is deliberately
174 * not an edge.
175 *
176 * `chunks` maps chunk file name to source; `reachable` is returned so a caller
177 * can tell "no violations" apart from "the walk never left the entry".
178 */
179export function findEagerBunRuntimeImports(
180 chunks: ReadonlyMap<string, string>,
181 entryChunks: Iterable<string>,
182): {
183 readonly reachable: ReadonlyArray<string>;
184 readonly violations: ReadonlyArray<{ readonly chunk: string; readonly specifier: string }>;
185} {
186 // Anchored at a line start so `import(...)` and specifier strings inside
187 // bundled code cannot match. `[^;]*?` keeps a match inside one statement
188 // while still spanning the line breaks rolldown puts in long import lists.
189 const staticImportPattern =
190 /^[ \t]*(?:import|export)\s[^;]*?\bfrom\s*["']([^"']+)["']|^[ \t]*import\s*["']([^"']+)["']/gm;
191​
192 const seen = new Set<string>();
193 const queue = [...entryChunks];
194 const violations: Array<{ chunk: string; specifier: string }> = [];
195​
196 for (const chunk of queue) {
197 if (seen.has(chunk)) continue;
198 seen.add(chunk);
199​
200 const source = chunks.get(chunk);
201 if (source === undefined) continue;
202​
203 for (const match of source.matchAll(staticImportPattern)) {
204 const specifier = match[1] ?? match[2];
205 if (specifier === undefined) continue;
206​
207 if (specifier.startsWith(".")) {
208 // Chunks are emitted flat beside their entry, so the basename is the key.
209 const target = specifier.slice(specifier.lastIndexOf("/") + 1);
210 if (!seen.has(target)) queue.push(target);
211 continue;
212 }
213​
214 if (isBunRuntimeModule(specifier)) violations.push({ chunk, specifier });
215 }
216 }
217​
218 return {
219 reachable: [...seen].filter((chunk) => chunks.has(chunk)).sort(),
220 violations,
221 };