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

vite.config.ts

349 lines13.5 KB

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