Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

vite.config.ts

110 lines5.1 KB

1import { existsSync } from 'node:fs'
2import { resolve } from 'node:path'
3import { defineConfig } from 'vite'
4import { tanstackStart } from '@tanstack/react-start/plugin/vite'
5import viteReact from '@vitejs/plugin-react'
6import tailwindcss from '@tailwindcss/vite'
7import { nitro } from 'nitro/vite'
8import { devtools } from '@tanstack/devtools-vite'
9import { webSocketChatPlugin } from './src/lib/websocket-chat-plugin.ts'
10​
11// Server routes read process.env. Vite does not copy unprefixed .env keys
12// into the SSR process. Load them here. Already-set vars win.
13for (const name of ['.env.local', '.env']) {
14 const path = resolve(import.meta.dirname, name)
15 if (existsSync(path)) process.loadEnvFile(path)
17​
18// `dockerode` is a server-only dependency that pulls in optional native addons
19// (`ssh2` → `cpu-features`, a `.node` binary that this install does not compile).
20// At runtime `ssh2` catches the missing addon, but the bundlers don't:
21// • esbuild's dev-time dep pre-bundler (`optimizeDeps`) hard-errors trying to
22// resolve `cpufeatures.node` → `optimizeDeps.exclude` keeps it out of the scan.
23// • the SSR build would try to inline it → `ssr.external` keeps it a runtime
24// require.
25// This example uses nitro 3. Its server build (rolldown) externalizes
26// node_modules by default, but must resolve each external to a real path.
27// Under pnpm these server-only deps are only reachable via a workspace
28// adapter's nested store dir, so a bare resolve from this example fails —
29// they are therefore declared as direct dependencies here (dockerode,
30// @anthropic-ai/sdk, @elevenlabs/elevenlabs-js) so nitro can resolve and
31// trace them. The vite-level guards below still cover the client/SSR passes.
32//
33// `@anthropic-ai/sdk` (via @tanstack/ai-claude-code) ships a
34// `tools/agent-toolset/fs-util.mjs` sub-module that imports `node:crypto`,
35// `node:fs`, `node:path` — hard build errors if Rollup tries to resolve them
36// in the client bundle. The SDK is only used server-side; mark it external so
37// both the client Rollup pass and the SSR/nitro build resolve it at runtime.
38// `@ngrok/ngrok` (used by src/ngrok-bridge.ts to tunnel the tool bridge to cloud
39// sandboxes) loads a platform-specific `.node` native binary — esbuild's
40// optimizer has no loader for it and the SSR/nitro builds must not inline it.
41const SERVER_ONLY_NATIVE = ['dockerode', '@anthropic-ai/sdk', '@ngrok/ngrok']
42​
43// Dev-only workaround for a nitro dev-middleware heuristic.
44//
45// `nitro/dist/_build/vite.dev.mjs` decides whether a request is a static asset
46// (and so must NOT reach the server) from `Sec-Fetch-Dest`:
47//
48// isAsset = fetchDest && fetchDest !== 'empty'
49// ? !/^(?:document|iframe|frame)$/.test(fetchDest)
50// : isAssetByExt
51//
52// Anything that isn't a document — `image`, `audio`, `video`, `script`, `font`
53// — is treated as an asset and falls through to vite's static middleware,
54// which has no file to serve and 404s with the connect `Cannot GET` page. The
55// extension branch is only consulted when the header is absent/`empty`, so
56// renaming the route doesn't help.
57//
58// It only bites routes nitro sees under Start's catch-all `/**` (an explicitly
59// registered nitro route short-circuits the check), which is every server route
60// here. So `<img src="/api/artifacts?id=…">` 404s in dev while the same URL
61// fetched from JS returns the bytes — and production is unaffected, since this
62// middleware only exists in the vite dev server.
63//
64// Presenting `empty` for our own API paths routes them back to the server
65// without changing what the browser actually sends.
66const nitroServeApiToSubresources = {
67 name: 'nitro-serve-api-to-subresources',
68 enforce: 'pre',
69 apply: 'serve',
70 configureServer(server) {
71 server.middlewares.use((req, _res, next) => {
72 if (req.url?.startsWith('/api/')) req.headers['sec-fetch-dest'] = 'empty'
73 next()
74 })
75 },
76} as const satisfies import('vite').PluginOption
77​
78const config = defineConfig({
79 optimizeDeps: { exclude: SERVER_ONLY_NATIVE },
80 // Server-side only fix. @elevenlabs/elevenlabs-js ships a top-level
81 // `function getHeader(…)` that collides with h3's auto-imported
82 // `getHeader` when vite inlines it into the SSR bundle. The SDK is
83 // only imported by server-side adapter factories (see
84 // `src/lib/server-audio-adapters.ts`), so tree-shaking already keeps
85 // it out of the client bundle — this option only affects the SSR
86 // build, where we want the SDK resolved at runtime via require()
87 // instead of inlined into the rollup chunk.
88 // `dockerode` is also SSR-externalized (see comment above).
89 ssr: {
90 external: ['@elevenlabs/elevenlabs-js', ...SERVER_ONLY_NATIVE],
91 },
92 // Keep `dockerode` external in every Rollup pass (the Nitro server build has its
93 // own, which `ssr.external` doesn't reach). The client build never imports it, so
94 // this is a no-op there.
95 build: { rollupOptions: { external: SERVER_ONLY_NATIVE } },
96 resolve: { tsconfigPaths: true },
97 plugins: [
98 nitroServeApiToSubresources,
99 devtools(),
100 webSocketChatPlugin(),
101 nitro(),
102 tailwindcss(),
103 tanstackStart({
104 router: { routeFileIgnorePattern: '\\.test\\.ts$' },
105 }),
106 viteReact(),
107 ],
108})
109​
110export default config