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

vite.config.ts

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