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

vite.config.ts

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