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