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

vite.config.ts

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