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

cli-external-packages.ts

130 lines5.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 "node-gyp-build",
35 "node-addon-api",
36 // ws's optional accelerators. Nothing in this repo declares them, so they are
37 // not in the staged production install and the packaged app does not ship
38 // them either way -- ws wraps the require in try/catch and falls back to its
39 // JS paths. They are listed because they were being inlined from the dev
40 // store: both carry binding.gyp and prebuilds and load through
41 // node-gyp-build, and a native loader inlined into a bundle chunk searches
42 // for prebuilds that cannot be beside it. Listing them keeps that from
43 // becoming real if either is ever declared as a dependency.
44 "bufferutil",
45 "utf-8-validate",
46] as const;
47​
48export function isRuntimeExternalCliDependency(id: string): boolean {
49 return CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => id.startsWith(prefix));
51​
52/**
53 * True when `id` must stay out of the bundle.
54 *
55 * This has to be wired to the bundler's `neverBundle`, not just to
56 * `alwaysBundle`. `alwaysBundle` only forces packages IN — returning false from
57 * it means "no opinion", and the default then applies: a declared dependency
58 * stays external, but a transitive one gets bundled. That is how a native
59 * loader such as node-gyp-build ended up inlined while node-pty (a declared
60 * dependency) stayed external.
61 */
62export function isExternalCliDependency(id: string): boolean {
63 return isRuntimeExternalCliDependency(id);
65​
66/** True when the CLI bundle should inline `id` rather than leave it external. */
67export function shouldBundleCliDependency(id: string): boolean {
68 if (id.startsWith("node:")) return false;
69 return !isExternalCliDependency(id);
71​
72/** Select direct dependency roots whose runtime closure belongs in the sidecar. */
73export function selectCliRuntimeExternalDependencies(
74 dependencies: Readonly<Record<string, string>>,
75): Record<string, string> {
76 return Object.fromEntries(
77 Object.entries(dependencies).filter(([name]) => isRuntimeExternalCliDependency(name)),
78 );
80​
81/**
82 * Scan an emitted bundle chunk for runtime-external packages that were inlined.
83 *
84 * Configuring the bundler is not the same as checking what it produced. The
85 * `alwaysBundle` predicate only forces packages IN; returning false from it
86 * means "no opinion", so a transitive dependency still gets bundled by default.
87 * A native loader and its helper (node-gyp-build-optional-packages and
88 * detect-libc, when msgpackr-extract was still a dependency) were inlined that
89 * way while every list-based test passed, which is why this reads the artifact
90 * instead.
91 *
92 * `regionCount` is reported so the caller can tell "nothing was inlined" apart
93 * from "the marker format changed and this scan no longer sees anything".
94 *
95 * `inlinedPackages` is every package seen in a region, which lets the caller
96 * check the opposite direction too. Verifying only that externals are absent
97 * would still pass if the bundler reverted to leaving everything external: the
98 * scan would see source-file regions, report nothing inlined, and the packaged
99 * backends would then fail with ERR_MODULE_NOT_FOUND because those packages
100 * are not in the selected sidecar closure either.
101 */
102export function findInlinedExternalPackages(source: string): {
103 readonly regionCount: number;
104 readonly inlined: ReadonlyArray<string>;
105 readonly inlinedPackages: ReadonlyArray<string>;
106} {
107 // Rolldown marks each inlined module with a `//#region <path>` comment.
108 const regionPattern = /\/\/#region\s+(\S+)/g;
109 const packagePattern = /node_modules\/((?:@[^/\s]+\/)?[^/\s]+)\//g;
110​
111 let regionCount = 0;
112 const inlined = new Set<string>();
113 const inlinedPackages = new Set<string>();
114 for (const region of source.matchAll(regionPattern)) {
115 regionCount += 1;
116 const regionPath = region[1] ?? "";
117 for (const candidate of regionPath.matchAll(packagePattern)) {
118 const name = candidate[1];
119 if (name === undefined || name === ".pnpm") continue;
120 inlinedPackages.add(name);
121 if (isExternalCliDependency(name)) inlined.add(name);
122 }
123 }
124​
125 return {
126 regionCount,
127 inlined: [...inlined].sort(),
128 inlinedPackages: [...inlinedPackages].sort(),
129 };