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

vite.config.ts

304 lines11.8 KB

1import * as NodeZlib from "node:zlib";
2​
3import react from "@vitejs/plugin-react";
4import { tanstackRouter } from "@tanstack/router-plugin/vite";
5import compression from "compression";
6import { playwright } from "vite-plus/test/browser-playwright";
7import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
8import "vite-plus/test/config";
9import { defineConfig, type Connect, type Plugin } from "vite-plus";
10import * as Hash from "effect/Hash";
11import pkg from "./package.json" with { type: "json" };
12​
13import {
14 DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,
15 DEV_PROXIED_PATH_PREFIXES,
16} from "@t3tools/shared/devProxy";
17​
18import { loadRepoEnv } from "../../scripts/lib/public-config";
19import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
20import { tailwindPlugins } from "./vite/tailwind";
21import { warmBundledDevPlugin } from "./vite/warmBundledDev";
22​
23const repoEnv = loadRepoEnv();
24Object.assign(process.env, repoEnv);
25​
26// Single-origin dev is signalled positively, because it cannot be inferred from
27// the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys but
28// `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so a
29// developer with either URL in their `.env` gets it back here.
30const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
31​
32const port = Number(process.env.PORT ?? 5733);
33const explicitHost = process.env.HOST?.trim();
34const host = explicitHost || "localhost";
35const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
36const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
37const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
38const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
39const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
40const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";
41const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
42const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
43const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
44const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
45const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
46const configuredDesktopUpdateRepository =
47 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
48 process.env.GITHUB_REPOSITORY?.trim() ||
49 "";
50const configuredHostedAppUrl = (() => {
51 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
52 if (explicitHostedAppUrl) {
53 return explicitHostedAppUrl;
54 }
55 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
56 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
57 }
58 if (process.env.VERCEL_URL) {
59 return `https://${process.env.VERCEL_URL}`;
60 }
61 return undefined;
62})();
63const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
64​
65const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
66const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
67​
68const buildSourcemap: boolean | "hidden" =
69 sourcemapEnv === "0" || sourcemapEnv === "false"
70 ? false
71 : sourcemapEnv === "hidden"
72 ? "hidden"
73 : true;
74​
75const unitTestProject = {
76 extends: true,
77 test: {
78 name: "unit",
79 include: ["src/**/*.test.{ts,tsx}"],
80 exclude: ["src/**/*.browser.test.{ts,tsx}"],
81 hookTimeout: 15_000,
82 testTimeout: 15_000,
83 setupFiles: ["../../packages/shared/src/testing/longTempDir.ts"],
84 },
85} satisfies TestProjectInlineConfiguration;
86​
87// Anything that renders React or touches the DOM is named *.browser.test.{ts,tsx} and runs
88// in headless Chromium through the same plugins as the app, so it exercises compiled code.
89// Vitest's fixed browser API port (63315) collides when two checkouts run
90// browser tests at once, and `server.strictPort` above is inherited, so the
91// second run fails instead of moving on. Hash the checkout path like
92// scripts/dev-runner.ts does, into 61000-64999 (above Linux's ephemeral range).
93const browserTestApiPort = 61_000 + ((Hash.string(import.meta.dirname) >>> 0) % 4_000);
94​
95const browserTestProject = {
96 extends: true,
97 // Pre-bundled so a late first import does not trigger a mid-run reload. The
98 // dependency scan misses autocomplete because tests reach it only through lazy imports.
99 optimizeDeps: { include: ["vite-plus/test/browser", "@base-ui/react/autocomplete"] },
100 test: {
101 name: "browser",
102 include: ["src/**/*.browser.test.{ts,tsx}"],
103 hookTimeout: 15_000,
104 testTimeout: 15_000,
105 setupFiles: ["./test/browserSetup.ts"],
106 api: { port: browserTestApiPort, strictPort: false },
107 browser: {
108 enabled: true,
109 headless: true,
110 provider: playwright(),
111 instances: [{ browser: "chromium" }],
112 screenshotFailures: false,
113 commands: {
114 // Playwright's mouse outlives each test, so whatever mounts under its last
115 // position starts hovered. test/browserSetup.ts parks it off the page before each test.
116 resetPointer: async ({ page }) => {
117 await page.mouse.move(-1, -1);
118 },
119 },
120 },
121 },
122} satisfies TestProjectInlineConfiguration;
123​
124function resolveDevProxyTarget(
125 backendPort: string | undefined,
126 wsUrl: string | undefined,
127): string | undefined {
128 const port = Number(backendPort?.trim());
129 if (Number.isInteger(port) && port > 0) {
130 return `http://localhost:${port}/`;
131 }
132​
133 // dev:desktop still points the renderer straight at the backend, so fall
134 // back to deriving the target from the explicit websocket URL.
135 if (!wsUrl) {
136 return undefined;
137 }
138​
139 try {
140 const url = new URL(wsUrl);
141 if (url.protocol === "ws:") {
142 url.protocol = "http:";
143 } else if (url.protocol === "wss:") {
144 url.protocol = "https:";
145 }
146 url.pathname = "";
147 url.search = "";
148 url.hash = "";
149 return url.toString();
150 } catch {
151 return undefined;
152 }
154​
155const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
156​
157// Brotli quality 5 keeps encode time in the hundreds of ms; the default
158// (quality 11) would trade the transfer stall for an equally long encode stall.
159function devCompressionPlugin(): Plugin {
160 return {
161 name: "t3code:dev-compression",
162 apply: "serve",
163 configureServer(server) {
164 server.middlewares.use(
165 compression({
166 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
167 }) as unknown as Connect.NextHandleFunction,
168 );
169 },
170 };
172​
173// Vite rejects requests whose Host header isn't localhost, which blocks sharing
174// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
175// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
176const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
177 .split(",")
178 .map((entry) => entry.trim())
179 .filter((entry) => entry.length > 0);
180const allowedHosts = [".ts.net", ...configuredAllowedHosts];
181​
182export default defineConfig(() => {
183 return {
184 assetsInclude: ["**/*.wasm"],
185 plugins: [
186 devCompressionPlugin(),
187 thirdPartyLicensesPlugin({
188 bundleName: "web",
189 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
190 packageManifests: [
191 { bundle: "web", path: new URL("./package.json", import.meta.url) },
192 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
193 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
194 ],
195 }),
196 tanstackRouter({ autoCodeSplitting: true }),
197 react({ compiler: true }),
198 tailwindPlugins(bundledDev),
199 warmBundledDevPlugin(),
200 ],
201 optimizeDeps: {
202 include: [
203 "@clerk/clerk-js",
204 "@clerk/react/internal",
205 "@pierre/diffs",
206 "@pierre/diffs/edit",
207 "@pierre/diffs/react",
208 "@pierre/diffs/worker/worker.js",
209 "effect/Array",
210 "effect/Order",
211 "react-dom/client",
212 ],
213 },
214 define: {
215 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
216 // Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
217 // under single-origin dev this must stay empty even when a `.env`
218 // supplies it, so the client falls back to window.location.origin.
219 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
220 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
221 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
222 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
223 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
224 configuredClerkCliOAuthClientId,
225 ),
226 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
227 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
228 configuredRelayTracingDataset,
229 ),
230 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
231 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
232 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
233 "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(
234 configuredDesktopUpdateRepository,
235 ),
236 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
237 },
238 resolve: {
239 tsconfigPaths: true,
240 dedupe: ["react", "react-dom"],
241 },
242 experimental: {
243 bundledDev,
244 },
245 server: {
246 host,
247 port,
248 strictPort: true,
249 allowedHosts,
250 // Transform the whole module graph at server start instead of on the
251 // first request. Without this, a cold worktree discovers and transforms
252 // modules one import-level at a time while the browser waits — which
253 // over a tailnet origin turns into minutes of waterfall. Bundled dev
254 // ignores this; warmBundledDevPlugin covers it there.
255 warmup: {
256 clientFiles: ["./src/main.tsx"],
257 },
258 ...(devProxyTarget
259 ? {
260 // One entry per shared prefix; the server's dev catch-all 404s the
261 // same list, so the two sides cannot drift.
262 proxy: Object.fromEntries(
263 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
264 prefix,
265 {
266 target: devProxyTarget,
267 changeOrigin: !DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES.has(prefix),
268 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
269 },
270 ]),
271 ),
272 }
273 : {}),
274 // Electron's BrowserWindow needs the HMR socket pinned to an explicit
275 // host to connect reliably; dev:desktop is the only mode that sets HOST.
276 // Everywhere else, leaving this unset lets the client derive it from the
277 // page origin, which is what makes HMR work over Tailscale/LAN instead of
278 // failing an attempt against the wrong machine's localhost first.
279 ...(explicitHost
280 ? {
281 hmr: {
282 protocol: "ws",
283 host: explicitHost,
284 clientPort: port,
285 },
286 }
287 : {}),
288 },
289 // @tailwindcss/vite only emits a CSS sourcemap when devSourcemap is on; without it
290 // rolldown flags the transform as SOURCEMAP_BROKEN on every sourcemapped build.
291 css: {
292 devSourcemap: buildSourcemap !== false,
293 },
294 build: {
295 outDir: "dist",
296 emptyOutDir: true,
297 manifest: true,
298 sourcemap: buildSourcemap,
299 },
300 test: {
301 projects: [defineProject(unitTestProject), defineProject(browserTestProject)],
302 },
303 };
304});