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

startupChunks.ts

191 lines7.5 KB

1// @effect-diagnostics nodeBuiltinImport:off - Vite resolves module paths before an Effect runtime exists.
2import * as NodePath from "node:path";
3​
4import { normalizePath, type HtmlTagDescriptor, type Plugin, type Rolldown } from "vite-plus";
5​
6// Keep the initial route graphs in sync with src/routes.
7const STARTUP_MODULES = {
8 main: "src/main.tsx",
9 chat: "src/routes/_chat.tsx?tsr-split=component",
10 "chat-index": "src/routes/_chat.index.tsx?tsr-split=component",
11 "chat-draft": "src/routes/_chat.draft.$draftId.tsx?tsr-split=component",
12 "chat-thread": "src/routes/_chat.$environmentId.$threadId.tsx?tsr-split=component",
13};
14// Group static startup graphs without pulling chat-only code into other routes.
15// Bootstrap stays separate so it can report main's chunk-load failures.
16​
17export function startupChunksPlugin(): Plugin {
18 let root = process.cwd();
19 let base = "/";
20 let bootstrapModules: ReadonlySet<string> = new Set();
21 let startupModuleOwners: ReadonlyMap<string, string> = new Map();
22 let startupFiles: ReadonlyArray<string> = [];
23 let startupFileSet: ReadonlySet<string> = new Set();
24 let startupCss: ReadonlyArray<string> = [];
25​
26 return {
27 name: "t3code:startup-chunks",
28 apply: "build",
29 config: (config) => {
30 root = normalizePath(NodePath.resolve(config.root ?? process.cwd()));
31 return {
32 build: {
33 modulePreload: {
34 resolveDependencies: (_file, deps, { hostType }) =>
35 hostType === "js" ? deps.filter((dep) => !startupFileSet.has(dep)) : deps,
36 },
37 rolldownOptions: {
38 input: {
39 index: normalizePath(NodePath.join(root, "index.html")),
40 ...Object.fromEntries(
41 Object.entries(STARTUP_MODULES).map(([name, id]) => [
42 name,
43 normalizePath(NodePath.join(root, id)),
44 ]),
45 ),
46 },
47 output: {
48 codeSplitting: {
49 // Keep each graph whole: size splitting creates chunk cycles inside Effect's
50 // eagerly initialized runtime and can run consumers before their dependencies.
51 groups: [
52 ...Object.keys(STARTUP_MODULES).map((name) => ({
53 name: `startup-${name}`,
54 tags: ["$initial" as const],
55 test: (id: string) =>
56 !id.startsWith("\0") && startupModuleOwners.get(normalizePath(id)) === name,
57 // Dynamic settings/theme entries must not fragment the startup graphs.
58 entriesAware: false,
59 // Otherwise excluded bootstrap helpers are recaptured through main's imports.
60 includeDependenciesRecursively: false,
61 })),
62 ],
63 },
64 },
65 },
66 },
67 };
68 },
69 configResolved(config) {
70 base = config.base;
71 },
72 buildEnd(error) {
73 if (error) return;
74 const moduleIds = new Map([...this.getModuleIds()].map((id) => [normalizePath(id), id]));
75 const staticClosure = (...entryIds: ReadonlyArray<string>) => {
76 const closure = new Set<string>();
77 const pending = entryIds.flatMap((entryId) => moduleIds.get(entryId) ?? []);
78 for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
79 const normalizedId = normalizePath(id);
80 if (closure.has(normalizedId)) continue;
81 closure.add(normalizedId);
82 pending.push(...(this.getModuleInfo(id)?.importedIds ?? []));
83 }
84 return closure;
85 };
86 bootstrapModules = staticClosure(normalizePath(NodePath.join(root, "index.html")));
87 const owners = new Map<string, string>();
88 for (const [name, entry] of Object.entries(STARTUP_MODULES)) {
89 for (const id of staticClosure(normalizePath(NodePath.join(root, entry)))) {
90 if (!bootstrapModules.has(id) && !owners.has(id)) owners.set(id, name);
91 }
92 }
93 startupModuleOwners = owners;
94 },
95 generateBundle: {
96 order: "pre",
97 handler(_options, bundle) {
98 const chunks = Object.values(bundle).filter(
99 (output): output is Rolldown.OutputChunk => output.type === "chunk",
100 );
101 const importClosure = (roots: ReadonlyArray<Rolldown.OutputChunk>) => {
102 const files = new Set<string>();
103 const pending = roots.map((chunk) => chunk.fileName);
104 for (let file = pending.pop(); file !== undefined; file = pending.pop()) {
105 const chunk = bundle[file];
106 if (chunk?.type !== "chunk" || files.has(file)) continue;
107 files.add(file);
108 pending.push(...chunk.imports);
109 }
110 return files;
111 };
112 const bootstrapFiles = importClosure(
113 chunks.filter(
114 (chunk) => chunk.facadeModuleId === normalizePath(NodePath.join(root, "index.html")),
115 ),
116 );
117 const mainId = normalizePath(NodePath.join(root, STARTUP_MODULES.main));
118 if (
119 [...bootstrapFiles].some((file) => {
120 const chunk = bundle[file];
121 return (
122 chunk?.type === "chunk" &&
123 chunk.moduleIds.some(
124 (id) => !id.startsWith("\0") && !bootstrapModules.has(normalizePath(id)),
125 )
126 );
127 })
128 ) {
129 this.error(
130 "The boot entry must catch main's chunk load failures before importing app code.",
131 );
132 }
133 // Main may become a facade; routes retain their own preload lists.
134 const files = [
135 ...importClosure(
136 chunks.filter(
137 (chunk) => chunk.facadeModuleId === mainId || chunk.moduleIds.includes(mainId),
138 ),
139 ),
140 ].filter((file) => !bootstrapFiles.has(file));
141 const chunkAt = (file: string) => {
142 const chunk = bundle[file];
143 return chunk?.type === "chunk" ? chunk : undefined;
144 };
145 startupFiles = files.toSorted(
146 (left, right) => (chunkAt(right)?.code.length ?? 0) - (chunkAt(left)?.code.length ?? 0),
147 );
148 startupFileSet = new Set(startupFiles);
149 startupCss = [
150 ...new Set(
151 files.flatMap((file) => [...(chunkAt(file)?.viteMetadata?.importedCss ?? [])]),
152 ),
153 ];
154 },
155 },
156 transformIndexHtml: {
157 order: "post",
158 handler: (): HtmlTagDescriptor[] => [
159 // A stylesheet link would hold the splash until the CSS arrives; the
160 // runtime still inserts the stylesheet before main runs.
161 ...startupCss.map((file): HtmlTagDescriptor => ({
162 tag: "link",
163 attrs: { rel: "preload", as: "style", crossorigin: true, href: `${base}${file}` },
164 injectTo: "head",
165 })),
166 ...startupFiles.map((file): HtmlTagDescriptor => ({
167 tag: "link",
168 attrs: { rel: "modulepreload", crossorigin: true, href: `${base}${file}` },
169 injectTo: "head",
170 })),
171 ],
172 },
173 };
175​
176// Separate dynamic icon ids so static icons don't each become a startup chunk.
177export function lucideDynamicIconsPlugin(): Plugin {
178 const suffix = "?lucide-dynamic";
179 return {
180 name: "t3code:lucide-dynamic-icons",
181 apply: "build",
182 enforce: "pre",
183 async resolveId(source, importer) {
184 if (!source.startsWith("./icons/") || !importer?.endsWith("/dynamicIconImports.js")) {
185 return null;
186 }
187 const resolved = await this.resolve(source, importer, { skipSelf: true });
188 return resolved ? `${resolved.id}${suffix}` : null;
189 },
190 };