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

vite.config.ts

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