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

vite.config.ts

336 lines12.5 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Vite config runs before any Effect runtime.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeZlib from "node:zlib";
4​
5import react from "@vitejs/plugin-react";
6import { tanstackRouter } from "@tanstack/router-plugin/vite";
7import compression from "compression";
8import { playwright } from "vite-plus/test/browser-playwright";
9import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config";
10import "vite-plus/test/config";
11import { defineConfig, type Connect, type Plugin } from "vite-plus";
12import * as Hash from "effect/Hash";
13import pkg from "./package.json" with { type: "json" };
14​
15import {
16 DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,
17 DEV_PROXIED_PATH_PREFIXES,
18} from "@t3tools/shared/devProxy";
19​
20import { loadRepoEnv } from "../../scripts/lib/public-config";
21import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
22import { tailwindPlugins } from "./vite/tailwind";
23import { warmBundledDevPlugin } from "./vite/warmBundledDev";
24​
25const repoEnv = loadRepoEnv();
26Object.assign(process.env, repoEnv);
27​
28// Signal single-origin dev explicitly; loadRepoEnv can restore deleted URL keys from .env.
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 configuredReleaseChannel =
45 process.env.T3CODE_BUILT_DEV === "1" ? "dev" : process.env.VITE_RELEASE_CHANNEL?.trim() || "";
46const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
47const configuredDesktopUpdateRepository =
48 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
49 process.env.GITHUB_REPOSITORY?.trim() ||
50 "";
51const configuredHostedAppUrl = (() => {
52 const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
53 if (explicitHostedAppUrl) {
54 return explicitHostedAppUrl;
55 }
56 if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
57 return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
58 }
59 if (process.env.VERCEL_URL) {
60 return `https://${process.env.VERCEL_URL}`;
61 }
62 return undefined;
63})();
64const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
65​
66// `vp run dev --share --built` rebuilds on every change. The license manifest
67// is about 2 s of each build, and nothing in that mode reads it.
68const builtDev = process.env.T3CODE_BUILT_DEV === "1";
69​
70const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
71const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
72​
73const buildSourcemap: boolean | "hidden" =
74 sourcemapEnv === "0" || sourcemapEnv === "false"
75 ? false
76 : sourcemapEnv === "hidden"
77 ? "hidden"
78 : true;
79​
80const unitTestProject = {
81 extends: true,
82 test: {
83 name: "unit",
84 include: ["src/**/*.test.{ts,tsx}"],
85 exclude: ["src/**/*.browser.test.{ts,tsx}"],
86 hookTimeout: 15_000,
87 testTimeout: 15_000,
88 setupFiles: [
89 "../../packages/shared/src/testing/longTempDir.ts",
90 "../../packages/shared/src/testing/providerEnv.ts",
91 ],
92 },
93} satisfies TestProjectInlineConfiguration;
94​
95// Hash checkout paths to ports 61000-64999; Vitest's fixed port collides under inherited strictPort.
96const browserTestApiPort = 61_000 + ((Hash.string(import.meta.dirname) >>> 0) % 4_000);
97​
98const browserTestProject = {
99 extends: true,
100 // Pre-bundled so a late first import does not trigger a mid-run reload. The
101 // dependency scan misses autocomplete because tests reach it only through lazy imports.
102 optimizeDeps: { include: ["vite-plus/test/browser", "@base-ui/react/autocomplete"] },
103 test: {
104 name: "browser",
105 include: ["src/**/*.browser.test.{ts,tsx}"],
106 hookTimeout: 15_000,
107 testTimeout: 15_000,
108 setupFiles: ["./test/browserSetup.ts"],
109 api: { port: browserTestApiPort, strictPort: false },
110 browser: {
111 enabled: true,
112 headless: true,
113 provider: playwright(),
114 instances: [{ browser: "chromium" }],
115 screenshotFailures: false,
116 commands: {
117 // Playwright's mouse outlives each test, so whatever mounts under its last
118 // position starts hovered. test/browserSetup.ts parks it off the page before each test.
119 resetPointer: async ({ page }) => {
120 await page.mouse.move(-1, -1);
121 },
122 },
123 },
124 },
125} satisfies TestProjectInlineConfiguration;
126​
127// Render scenarios count React commits; they run only through scripts/render-metrics.ts,
128// which reads the per-scenario reports this command writes.
129const renderScenariosProject = {
130 ...browserTestProject,
131 test: {
132 ...browserTestProject.test,
133 name: "renders",
134 include: ["test/*.renders.tsx"],
135 // App scenarios mount the whole app per test, which outlasts 15s on a loaded machine.
136 hookTimeout: 60_000,
137 testTimeout: 60_000,
138 setupFiles: ["./test/renderCounter.ts", ...browserTestProject.test.setupFiles],
139 browser: {
140 ...browserTestProject.test.browser,
141 // Vitest names each instance in place, so a shared array would clash with the browser project.
142 instances: [{ browser: "chromium" }],
143 commands: {
144 ...browserTestProject.test.browser.commands,
145 writeRenderReport: async (_context, scenario: string, json: string) => {
146 const directory = process.env.T3CODE_RENDER_REPORT_DIR;
147 if (!directory) throw new Error("T3CODE_RENDER_REPORT_DIR is not set");
148 await NodeFSP.writeFile(`${directory}/${scenario}.json`, json);
149 },
150 },
151 },
152 },
153} satisfies TestProjectInlineConfiguration;
154​
155function resolveDevProxyTarget(
156 backendPort: string | undefined,
157 wsUrl: string | undefined,
158): string | undefined {
159 const port = Number(backendPort?.trim());
160 if (Number.isInteger(port) && port > 0) {
161 return `http://localhost:${port}/`;
162 }
163​
164 // dev:desktop connects directly to the backend; derive its target from the explicit WebSocket URL.
165 if (!wsUrl) {
166 return undefined;
167 }
168​
169 try {
170 const url = new URL(wsUrl);
171 if (url.protocol === "ws:") {
172 url.protocol = "http:";
173 } else if (url.protocol === "wss:") {
174 url.protocol = "https:";
175 }
176 url.pathname = "";
177 url.search = "";
178 url.hash = "";
179 return url.toString();
180 } catch {
181 return undefined;
182 }
184​
185const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
186​
187// Brotli quality 5 encodes in hundreds of ms; default quality 11 would replace transfer stalls with encode stalls.
188function devCompressionPlugin(): Plugin {
189 return {
190 name: "t3code:dev-compression",
191 apply: "serve",
192 configureServer(server) {
193 server.middlewares.use(
194 compression({
195 brotli: { params: { [NodeZlib.constants.BROTLI_PARAM_QUALITY]: 5 } },
196 }) as unknown as Connect.NextHandleFunction,
197 );
198 },
199 };
201​
202// Allow Tailnet hosts for sharing; Tailscale-controlled DNS prevents attacker rebinding.
203const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
204 .split(",")
205 .map((entry) => entry.trim())
206 .filter((entry) => entry.length > 0);
207const allowedHosts = [".ts.net", ...configuredAllowedHosts];
208​
209export default defineConfig(() => {
210 return {
211 run: {
212 tasks: {
213 // tsc (tsc-rs) rewrites the tsbuildinfo it reads, which keeps a task out of the cache.
214 typecheck: {
215 command: "tsc --noEmit",
216 cache: { input: [{ auto: true }, "!*.tsbuildinfo"] },
217 },
218 },
219 },
220 assetsInclude: ["**/*.wasm"],
221 plugins: [
222 devCompressionPlugin(),
223 builtDev
224 ? undefined
225 : thirdPartyLicensesPlugin({
226 bundleName: "web",
227 configFile: new URL("../../third-party-licenses.config.json", import.meta.url),
228 packageManifests: [
229 { bundle: "web", path: new URL("./package.json", import.meta.url) },
230 { bundle: "server", path: new URL("../server/package.json", import.meta.url) },
231 { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },
232 ],
233 }),
234 tanstackRouter({ autoCodeSplitting: true }),
235 react({ compiler: true }),
236 tailwindPlugins(bundledDev),
237 warmBundledDevPlugin(),
238 ],
239 optimizeDeps: {
240 include: [
241 "@clerk/clerk-js",
242 "@clerk/react/internal",
243 "@pierre/diffs",
244 "@pierre/diffs/edit",
245 "@pierre/diffs/react",
246 "@pierre/diffs/worker/worker.js",
247 "effect/Array",
248 "effect/Order",
249 "react-dom/client",
250 ],
251 },
252 define: {
253 "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
254 // Override .env URLs with empty values in single-origin dev so clients use window.location.origin.
255 "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
256 "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
257 "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
258 "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
259 "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
260 configuredClerkCliOAuthClientId,
261 ),
262 "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
263 "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
264 configuredRelayTracingDataset,
265 ),
266 "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
267 "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
268 "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
269 "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(
270 configuredDesktopUpdateRepository,
271 ),
272 "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel),
273 "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
274 },
275 resolve: {
276 tsconfigPaths: true,
277 dedupe: ["react", "react-dom"],
278 },
279 experimental: {
280 bundledDev,
281 },
282 server: {
283 host,
284 port,
285 strictPort: true,
286 allowedHosts,
287 // Warm the module graph before first request to avoid serial import transforms over tailnet.
288 // Bundled dev ignores this; warmBundledDevPlugin handles it there.
289 warmup: {
290 clientFiles: ["./src/main.tsx"],
291 },
292 ...(devProxyTarget
293 ? {
294 // Share prefixes with the backend catch-all so the proxy and 404 lists cannot drift.
295 proxy: Object.fromEntries(
296 DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
297 prefix,
298 {
299 target: devProxyTarget,
300 changeOrigin: !DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES.has(prefix),
301 ...(prefix === "/ws" || prefix === "/api" ? { ws: true } : {}),
302 },
303 ]),
304 ),
305 }
306 : {}),
307 // Electron needs an explicit HMR host; elsewhere derive it from page origin for Tailscale/LAN.
308 ...(explicitHost
309 ? {
310 hmr: {
311 protocol: "ws",
312 host: explicitHost,
313 clientPort: port,
314 },
315 }
316 : {}),
317 },
318 // Tailwind needs devSourcemap to avoid Rolldown SOURCEMAP_BROKEN on sourcemapped builds.
319 css: {
320 devSourcemap: buildSourcemap !== false,
321 },
322 build: {
323 outDir: "dist",
324 emptyOutDir: true,
325 manifest: true,
326 sourcemap: buildSourcemap,
327 },
328 test: {
329 projects: [
330 defineProject(unitTestProject),
331 defineProject(browserTestProject),
332 defineProject(renderScenariosProject),
333 ],
334 },
335 };
336});