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

vite.config.ts

293 lines12.3 KB

1import * as NodeZlib from "node:zlib";
2​
3import react, { reactCompilerPreset } from "@vitejs/plugin-react";
4import babel from "@rolldown/plugin-babel";
5import { tanstackRouter } from "@tanstack/router-plugin/vite";
6import compression from "compression";
7import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
8import "vite-plus/test/config";
9import { defineConfig, type Connect, type Plugin } from "vite-plus";
10import pkg from "./package.json" with { type: "json" };
11​
12import {
13 DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,
14 DEV_PROXIED_PATH_PREFIXES,
15} from "@t3tools/shared/devProxy";
16​
17import { loadRepoEnv } from "../../scripts/lib/public-config";
18import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
19import { tailwindPlugins } from "./vite/tailwind";
20​
21const repoEnv = loadRepoEnv();
22Object.assign(process.env, repoEnv);
23​
24// Single-origin dev is signalled positively, because it cannot be inferred
25// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
26// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
27// a developer with either URL in their `.env` gets it back here. Baking it then
28// pins the client to localhost and breaks every non-localhost origin — the
29// exact failure single-origin mode exists to prevent, and an invisible one
30// since the page still loads.
31const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
32​
33const port = Number(process.env.PORT ?? 5733);
34const explicitHost = process.env.HOST?.trim();
35const host = explicitHost || "localhost";
36const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
37const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
38const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
39const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
40const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
41const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";
42const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
43const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
44const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
45const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
46const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
47const configuredHostedAppUrl = (() => {
48 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
49 if (explicitHostedAppUrl) {
50 return explicitHostedAppUrl;
51 }
52 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
53 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
54 }
55 if (process.env.VERCEL_URL) {
56 return `https://${process.env.VERCEL_URL}`;
57 }
58 return undefined;
59})();
60const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
61​
62// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
63// dev for much faster startup/reload on large module graphs, with HMR served
64// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
65// The dev runner defaults this on for --share runs (remote browsers pay a
66// round trip per import level in unbundled dev); T3CODE_BUNDLED_DEV=0 opts out.
67const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
68const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
69​
70const buildSourcemap: boolean | "hidden" =
71 sourcemapEnv === "0" || sourcemapEnv === "false"
72 ? false
73 : sourcemapEnv === "hidden"
74 ? "hidden"
75 : true;
76​
77const unitTestProject = {
78 extends: true,
79 test: {
80 name: "unit",
81 include: ["src/**/*.test.{ts,tsx}"],
82 // The web runtime suite exercises auth bootstrap, saved environments,
83 // and websocket subscription lifecycles. Under the full monorepo test
84 // run, those async tests can exceed Vitest's default 5s budget.
85 hookTimeout: 15_000,
86 testTimeout: 15_000,
87 setupFiles: ["../../packages/shared/src/testing/longTempDir.ts"],
88 },
89} satisfies TestProjectInlineConfiguration;
90​
91function resolveDevProxyTarget(
92 backendPort: string | undefined,
93 wsUrl: string | undefined,
94): string | undefined {
95 // Browser dev is single-origin: the backend port is proxied through this
96 // server so the app works from any origin (localhost, tailnet, LAN, phone).
97 // T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
98 const port = Number(backendPort?.trim());
99 if (Number.isInteger(port) && port > 0) {
100 return `http://localhost:${port}/`;
101 }
102​
103 // dev:desktop still points the renderer straight at the backend, so fall
104 // back to deriving the target from the explicit websocket URL.
105 if (!wsUrl) {
106 return undefined;
107 }
108​
109 try {
110 const url = new URL(wsUrl);
111 if (url.protocol === "ws:") {
112 url.protocol = "http:";
113 } else if (url.protocol === "wss:") {
114 url.protocol = "https:";
115 }
116 url.pathname = "";
117 url.search = "";
118 url.hash = "";
119 return url.toString();
120 } catch {
121 return undefined;
122 }
124​
125const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
126​
127// Vite's dev server sends JS uncompressed. On localhost that is free; over a
128// shared origin (tailnet, LAN) it is the whole cold-start: bundled dev serves
129// one ~25 MB chunk, and a typical uplink moves that in about a minute while
130// both machines sit idle. Compressing turns it into a few seconds of CPU.
131// Brotli quality 5 keeps encode time in the hundreds of ms; the default
132// (quality 11) would trade the transfer stall for an equally long encode stall.
133function devCompressionPlugin(): Plugin {
134 return {
135 name: "t3code:dev-compression",
136 apply: "serve",
137 configureServer(server) {
138 // compression() is typed against Express's req/res, which extend the
139 // node http objects Connect actually passes — safe to narrow.
140 server.middlewares.use(
141 compression({
142 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
143 }) as unknown as Connect.NextHandleFunction,
144 );
145 },
146 };
148​
149// Vite rejects requests whose Host header isn't localhost, which blocks sharing
150// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
151// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
152// Anything else (ngrok, a LAN IP alias) goes through the env var.
153const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
154 .split(",")
155 .map((entry) => entry.trim())
156 .filter((entry) => entry.length > 0);
157const allowedHosts = [".ts.net", ...configuredAllowedHosts];
158​
159export default defineConfig(() => {
160 return {
161 assetsInclude: ["**/*.wasm"],
162 plugins: [
163 devCompressionPlugin(),
164 thirdPartyLicensesPlugin({
165 bundleName: "web",
166 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
167 packageManifests: [
168 { bundle: "web", path: new URL("./package.json", import.meta.url) },
169 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
170 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
171 ],
172 }),
173 // Route components load as split chunks so settings, pull-request, and
174 // usage code stay out of the cold-start payload; the router prefetches
175 // them on navigation intent (see getRouter's defaultPreload).
176 tanstackRouter({ autoCodeSplitting: true }),
177 react(),
178 babel({
179 // We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0
180 // This is because the babel plugin only automatically parses typescript and jsx based on relative paths (e.g. "**/*.ts")
181 // whereas the previous version of the plugin parsed all files with a .ts extension.
182 // This is causing our packages/ directory to fail to parse, as they are not relative to the CWD.
183 parserOpts: { plugins: ["typescript", "jsx"] },
184 presets: [reactCompilerPreset()],
185 }),
186 tailwindPlugins(bundledDev),
187 ],
188 optimizeDeps: {
189 include: [
190 "@clerk/clerk-js",
191 "@clerk/react/internal",
192 "@pierre/diffs",
193 "@pierre/diffs/edit",
194 "@pierre/diffs/react",
195 "@pierre/diffs/worker/worker.js",
196 "effect/Array",
197 "effect/Order",
198 "react-dom/client",
199 ],
200 },
201 define: {
202 // In dev mode, tell the web app where the WebSocket server lives
203 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
204 // Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
205 // under single-origin dev this must stay empty even when a `.env`
206 // supplies it, so the client falls back to window.location.origin.
207 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
208 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
209 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
210 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
211 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
212 configuredClerkCliOAuthClientId,
213 ),
214 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
215 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
216 configuredRelayTracingDataset,
217 ),
218 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
219 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
220 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
221 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
222 },
223 resolve: {
224 tsconfigPaths: true,
225 dedupe: ["react", "react-dom"],
226 },
227 experimental: {
228 bundledDev,
229 },
230 server: {
231 host,
232 port,
233 strictPort: true,
234 allowedHosts,
235 // Transform the whole module graph at server start instead of on the
236 // first request. Without this, a cold worktree discovers and transforms
237 // modules one import-level at a time while the browser waits — which
238 // over a tailnet origin turns into minutes of waterfall.
239 warmup: {
240 clientFiles: ["./src/main.tsx"],
241 },
242 ...(devProxyTarget
243 ? {
244 // One entry per shared prefix; the server's dev catch-all 404s the
245 // same list, so the two sides cannot drift. `/ws` is the app's own
246 // socket and `/api` carries the device hub's stream sockets —
247 // Vite's HMR socket is matched separately and exactly (path "/"
248 // plus a vite-hmr subprotocol), so the upgrade handlers don't
249 // collide.
250 proxy: Object.fromEntries(
251 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
252 prefix,
253 {
254 target: devProxyTarget,
255 changeOrigin: !DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES.has(prefix),
256 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
257 },
258 ]),
259 ),
260 }
261 : {}),
262 // Electron's BrowserWindow needs the HMR socket pinned to an explicit
263 // host to connect reliably; dev:desktop is the only mode that sets HOST.
264 // Everywhere else, leaving this unset lets the client derive it from the
265 // page origin, which is what makes HMR work over Tailscale/LAN instead of
266 // failing an attempt against the wrong machine's localhost first.
267 // (Vite 8 logs connection state via console.debug — enable "Verbose".)
268 ...(explicitHost
269 ? {
270 hmr: {
271 protocol: "ws",
272 host: explicitHost,
273 clientPort: port,
274 },
275 }
276 : {}),
277 },
278 // @tailwindcss/vite only emits a CSS sourcemap when devSourcemap is on; without it
279 // rolldown flags the transform as SOURCEMAP_BROKEN on every sourcemapped build.
280 css: {
281 devSourcemap: buildSourcemap !== false,
282 },
283 build: {
284 outDir: "dist",
285 emptyOutDir: true,
286 manifest: true,
287 sourcemap: buildSourcemap,
288 },
289 test: {
290 projects: [defineProject(unitTestProject)],
291 },
292 };
293});