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

vite.config.ts

234 lines9.5 KB

1import tailwindcss from "@tailwindcss/vite";
2import react, { reactCompilerPreset } from "@vitejs/plugin-react";
3import babel from "@rolldown/plugin-babel";
4import { tanstackRouter } from "@tanstack/router-plugin/vite";
5import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
6import "vite-plus/test/config";
7import { defineConfig } from "vite-plus";
8import pkg from "./package.json" with { type: "json" };
9​
10import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
11​
12import { loadRepoEnv } from "../../scripts/lib/public-config";
13​
14const repoEnv = loadRepoEnv();
15Object.assign(process.env, repoEnv);
16​
17// Single-origin dev is signalled positively, because it cannot be inferred
18// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
19// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
20// a developer with either URL in their `.env` gets it back here. Baking it then
21// pins the client to localhost and breaks every non-localhost origin — the
22// exact failure single-origin mode exists to prevent, and an invisible one
23// since the page still loads.
24const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
25​
26const port = Number(process.env.PORT ?? 5733);
27const explicitHost = process.env.HOST?.trim();
28const host = explicitHost || "localhost";
29const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
30const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
31const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
32const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
33const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
34const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";
35const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
36const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
37const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
38const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
39const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
40const configuredHostedAppUrl = (() => {
41 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
42 if (explicitHostedAppUrl) {
43 return explicitHostedAppUrl;
44 }
45 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
46 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
47 }
48 if (process.env.VERCEL_URL) {
49 return `https://${process.env.VERCEL_URL}`;
50 }
51 return undefined;
52})();
53const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
54​
55// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
56// dev for much faster startup/reload on large module graphs, with HMR served
57// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
58const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
59const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
60​
61const buildSourcemap: boolean | "hidden" =
62 sourcemapEnv === "0" || sourcemapEnv === "false"
63 ? false
64 : sourcemapEnv === "hidden"
65 ? "hidden"
66 : true;
67​
68const unitTestProject = {
69 extends: true,
70 test: {
71 name: "unit",
72 include: ["src/**/*.test.{ts,tsx}"],
73 // The web runtime suite exercises auth bootstrap, saved environments,
74 // and websocket subscription lifecycles. Under the full monorepo test
75 // run, those async tests can exceed Vitest's default 5s budget.
76 hookTimeout: 15_000,
77 testTimeout: 15_000,
78 },
79} satisfies TestProjectInlineConfiguration;
80​
81function resolveDevProxyTarget(
82 backendPort: string | undefined,
83 wsUrl: string | undefined,
84): string | undefined {
85 // Browser dev is single-origin: the backend port is proxied through this
86 // server so the app works from any origin (localhost, tailnet, LAN, phone).
87 // T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
88 const port = Number(backendPort?.trim());
89 if (Number.isInteger(port) && port > 0) {
90 return `http://localhost:${port}/`;
91 }
92​
93 // dev:desktop still points the renderer straight at the backend, so fall
94 // back to deriving the target from the explicit websocket URL.
95 if (!wsUrl) {
96 return undefined;
97 }
98​
99 try {
100 const url = new URL(wsUrl);
101 if (url.protocol === "ws:") {
102 url.protocol = "http:";
103 } else if (url.protocol === "wss:") {
104 url.protocol = "https:";
105 }
106 url.pathname = "";
107 url.search = "";
108 url.hash = "";
109 return url.toString();
110 } catch {
111 return undefined;
112 }
114​
115const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
116​
117// Vite rejects requests whose Host header isn't localhost, which blocks sharing
118// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
119// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
120// Anything else (ngrok, a LAN IP alias) goes through the env var.
121const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
122 .split(",")
123 .map((entry) => entry.trim())
124 .filter((entry) => entry.length > 0);
125const allowedHosts = [".ts.net", ...configuredAllowedHosts];
126​
127export default defineConfig(() => {
128 return {
129 assetsInclude: ["**/*.wasm"],
130 plugins: [
131 tanstackRouter(),
132 react(),
133 babel({
134 // We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0
135 // This is because the babel plugin only automatically parses typescript and jsx based on relative paths (e.g. "**/*.ts")
136 // whereas the previous version of the plugin parsed all files with a .ts extension.
137 // This is causing our packages/ directory to fail to parse, as they are not relative to the CWD.
138 parserOpts: { plugins: ["typescript", "jsx"] },
139 presets: [reactCompilerPreset()],
140 }),
141 tailwindcss(),
142 ],
143 optimizeDeps: {
144 include: [
145 "@clerk/clerk-js",
146 "@clerk/react/internal",
147 "@pierre/diffs",
148 "@pierre/diffs/editor",
149 "@pierre/diffs/react",
150 "@pierre/diffs/worker/worker.js",
151 "effect/Array",
152 "effect/Order",
153 "react-dom/client",
154 ],
155 },
156 define: {
157 // In dev mode, tell the web app where the WebSocket server lives
158 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
159 // Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
160 // under single-origin dev this must stay empty even when a `.env`
161 // supplies it, so the client falls back to window.location.origin.
162 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
163 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
164 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
165 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
166 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
167 configuredClerkCliOAuthClientId,
168 ),
169 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
170 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
171 configuredRelayTracingDataset,
172 ),
173 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
174 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
175 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
176 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
177 },
178 resolve: {
179 tsconfigPaths: true,
180 dedupe: ["react", "react-dom"],
181 },
182 experimental: {
183 bundledDev,
184 },
185 server: {
186 host,
187 port,
188 strictPort: true,
189 allowedHosts,
190 ...(devProxyTarget
191 ? {
192 // One entry per shared prefix; the server's dev catch-all 404s the
193 // same list, so the two sides cannot drift. `/ws` is the app's own
194 // socket — Vite's HMR socket is matched separately and exactly
195 // (path "/" plus a vite-hmr subprotocol), so the two upgrade
196 // handlers don't collide.
197 proxy: Object.fromEntries(
198 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
199 prefix,
200 {
201 target: devProxyTarget,
202 changeOrigin: true,
203 ...(prefix === "/ws" ? { ws: true } : {}),
204 },
205 ]),
206 ),
207 }
208 : {}),
209 // Electron's BrowserWindow needs the HMR socket pinned to an explicit
210 // host to connect reliably; dev:desktop is the only mode that sets HOST.
211 // Everywhere else, leaving this unset lets the client derive it from the
212 // page origin, which is what makes HMR work over Tailscale/LAN instead of
213 // failing an attempt against the wrong machine's localhost first.
214 // (Vite 8 logs connection state via console.debug — enable "Verbose".)
215 ...(explicitHost
216 ? {
217 hmr: {
218 protocol: "ws",
219 host: explicitHost,
220 clientPort: port,
221 },
222 }
223 : {}),
224 },
225 build: {
226 outDir: "dist",
227 emptyOutDir: true,
228 sourcemap: buildSourcemap,
229 },
230 test: {
231 projects: [defineProject(unitTestProject)],
232 },
233 };
234});