Open History to see the last commit
1import { joinPaths } from '@tanstack/router-core'
2import { VIRTUAL_MODULES } from '@tanstack/start-server-core'
3import { TanStackServerFnPlugin } from '@tanstack/server-functions-plugin'
4import * as vite from 'vite'
5import { crawlFrameworkPkgs } from 'vitefu'
6import { join } from 'pathe'
7import { escapePath } from 'tinyglobby'
8import { startManifestPlugin } from './start-manifest-plugin/plugin'
9import { startCompilerPlugin } from './start-compiler-plugin/plugin'
10import { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from './constants'
11import { tanStackStartRouter } from './start-router-plugin/plugin'
12import { loadEnvPlugin } from './load-env-plugin/plugin'
13import { devServerPlugin } from './dev-server-plugin/plugin'
14import { parseStartConfig } from './schema'
15import { resolveEntry } from './resolve-entries'
16import {
17 getClientOutputDirectory,
18 getServerOutputDirectory,
19} from './output-directory'
20import { postServerBuild } from './post-server-build'
21import { createServerFnPlugin } from './create-server-fn-plugin/plugin'
22import type { ViteEnvironmentNames } from './constants'
23import type {
24 TanStackStartInputConfig,
25 TanStackStartOutputConfig,
26} from './schema'
27import type { PluginOption } from 'vite'
28import type { CompileStartFrameworkOptions } from './start-compiler-plugin/compilers'
29β
30export interface TanStackStartVitePluginCoreOptions {
31 framework: CompileStartFrameworkOptions
32 defaultEntryPaths: {
33 client: string
34 server: string
35 start: string
36 }
37}
38β
39export interface ResolvedStartConfig {
40 root: string
41 startFilePath: string | undefined
42 routerFilePath: string
43 srcDirectory: string
44 viteAppBase: string
45}
46β
47export type GetConfigFn = () => {
48 startConfig: TanStackStartOutputConfig
49 resolvedStartConfig: ResolvedStartConfig
50}
51β
52function isFullUrl(str: string): boolean {
53 try {
54 new URL(str)
55 return true
56 } catch {
57 return false
58 }
59}
60β
61export function TanStackStartVitePluginCore(
62 corePluginOpts: TanStackStartVitePluginCoreOptions,
63 startPluginOpts: TanStackStartInputConfig,
64): Array<PluginOption> {
65 const resolvedStartConfig: ResolvedStartConfig = {
66 root: '',
67 startFilePath: undefined,
68 routerFilePath: '',
69 srcDirectory: '',
70 viteAppBase: '',
71 }
72β
73 let startConfig: TanStackStartOutputConfig | null
74 const getConfig: GetConfigFn = () => {
75 if (!resolvedStartConfig.root) {
76 throw new Error(`Cannot get config before root is resolved`)
77 }
78 if (!startConfig) {
79 startConfig = parseStartConfig(
80 startPluginOpts,
81 corePluginOpts,
82 resolvedStartConfig.root,
83 )
84 }
85 return { startConfig, resolvedStartConfig }
86 }
87β
88 const capturedBundle: Partial<
89 Record<ViteEnvironmentNames, vite.Rollup.OutputBundle>
90 > = {}
91β
92 function getBundle(envName: ViteEnvironmentNames): vite.Rollup.OutputBundle {
93 const bundle = capturedBundle[envName]
94 if (!bundle) {
95 throw new Error(`No bundle captured for environment: ${envName}`)
96 }
97 return bundle
98 }
99β
100 return [
101 {
102 name: 'tanstack-start-core:config',
103 enforce: 'pre',
104 async config(viteConfig, { command }) {
105 resolvedStartConfig.viteAppBase = viteConfig.base ?? '/'
106 if (!isFullUrl(resolvedStartConfig.viteAppBase)) {
107 resolvedStartConfig.viteAppBase = joinPaths([
108 '/',
109 viteConfig.base,
110 '/',
111 ])
112 }
113 const root = viteConfig.root || process.cwd()
114 resolvedStartConfig.root = root
115β
116 const { startConfig } = getConfig()
117 if (startConfig.router.basepath === undefined) {
118 if (!isFullUrl(resolvedStartConfig.viteAppBase)) {
119 startConfig.router.basepath =
120 resolvedStartConfig.viteAppBase.replace(/^\/|\/$/g, '')
121 } else {
122 startConfig.router.basepath = '/'
123 }
124 } else {
125 if (command === 'serve' && !viteConfig.server?.middlewareMode) {
126 // when serving, we must ensure that router basepath and viteAppBase are aligned
127 if (
128 !joinPaths(['/', startConfig.router.basepath, '/']).startsWith(
129 joinPaths(['/', resolvedStartConfig.viteAppBase, '/']),
130 )
131 ) {
132 this.error(
133 '[tanstack-start]: During `vite dev`, `router.basepath` must start with the vite `base` config value',
134 )
135 }
136 }
137 }
138β
139 const TSS_SERVER_FN_BASE = joinPaths([
140 '/',
141 startConfig.router.basepath,
142 startConfig.serverFns.base,
143 '/',
144 ])
145 const resolvedSrcDirectory = join(root, startConfig.srcDirectory)
146 resolvedStartConfig.srcDirectory = resolvedSrcDirectory
147β
148 const startFilePath = resolveEntry({
149 type: 'start entry',
150 configuredEntry: startConfig.start.entry,
151 defaultEntry: 'start',
152 resolvedSrcDirectory,
153 required: false,
154 })
155 resolvedStartConfig.startFilePath = startFilePath
156β
157 const routerFilePath = resolveEntry({
158 type: 'router entry',
159 configuredEntry: startConfig.router.entry,
160 defaultEntry: 'router',
161 resolvedSrcDirectory,
162 required: true,
163 })
164 resolvedStartConfig.routerFilePath = routerFilePath
165β
166 const clientEntryPath = resolveEntry({
167 type: 'client entry',
168 configuredEntry: startConfig.client.entry,
169 defaultEntry: 'client',
170 resolvedSrcDirectory,
171 required: false,
172 })
173β
174 const serverEntryPath = resolveEntry({
175 type: 'server entry',
176 configuredEntry: startConfig.server.entry,
177 defaultEntry: 'server',
178 resolvedSrcDirectory,
179 required: false,
180 })
181β
182 const clientAlias = vite.normalizePath(
183 clientEntryPath ?? corePluginOpts.defaultEntryPaths.client,
184 )
185 const serverAlias = vite.normalizePath(
186 serverEntryPath ?? corePluginOpts.defaultEntryPaths.server,
187 )
188 const startAlias = vite.normalizePath(
189 startFilePath ?? corePluginOpts.defaultEntryPaths.start,
190 )
191 const routerAlias = vite.normalizePath(routerFilePath)
192β
193 const entryAliasConfiguration: Record<
194 (typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS],
195 string
196 > = {
197 [ENTRY_POINTS.client]: clientAlias,
198 [ENTRY_POINTS.server]: serverAlias,
199 [ENTRY_POINTS.start]: startAlias,
200 [ENTRY_POINTS.router]: routerAlias,
201 }
202β
203 const startPackageName =
204 `@tanstack/${corePluginOpts.framework}-start` as const
205β
206 // crawl packages that have start in "peerDependencies"
207 // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101
208β
209 // this is currently uncached; could be implemented similarly as vite handles lock file changes
210 // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282
211β
212 const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({
213 root: process.cwd(),
214 isBuild: command === 'build',
215 isFrameworkPkgByJson(pkgJson) {
216 const peerDependencies = pkgJson['peerDependencies']
217β
218 if (peerDependencies) {
219 return startPackageName in peerDependencies
220 }
221β
222 return false
223 },
224 })
225β
226 return {
227 // see https://vite.dev/config/shared-options.html#apptype
228 // this will prevent vite from injecting middlewares that we don't want
229 appType: viteConfig.appType ?? 'custom',
230 environments: {
231 [VITE_ENVIRONMENT_NAMES.client]: {
232 consumer: 'client',
233 build: {
234 rollupOptions: {
235 input: {
236 main: ENTRY_POINTS.client,
237 },
238 },
239 outDir: getClientOutputDirectory(viteConfig),
240 },
241 optimizeDeps: {
242 // Ensure user code can be crawled for dependencies
243 entries: [clientAlias, routerAlias].map((entry) =>
244 // Entries are treated as `tinyglobby` patterns so need to be escaped
245 escapePath(entry),
246 ),
247 },
248 },
249 [VITE_ENVIRONMENT_NAMES.server]: {
250 consumer: 'server',
251 build: {
252 ssr: true,
253 rollupOptions: {
254 input:
255 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
256 ?.build?.rollupOptions?.input ?? ENTRY_POINTS.server,
257 },
258 outDir: getServerOutputDirectory(viteConfig),
259 commonjsOptions: {
260 include: [/node_modules/],
261 },
262 copyPublicDir:
263 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
264 ?.build?.copyPublicDir ?? false,
265 },
266 optimizeDeps: {
267 // Ensure user code can be crawled for dependencies
268 entries: [serverAlias, startAlias, routerAlias].map((entry) =>
269 // Entries are treated as `tinyglobby` patterns so need to be escaped
270 escapePath(entry),
271 ),
272 },
273 },
274 },
275β
276 resolve: {
277 noExternal: [
278 // ENTRY_POINTS.start,
279 '@tanstack/start**',
280 `@tanstack/${corePluginOpts.framework}-start**`,
281 ...crawlFrameworkPkgsResult.ssr.noExternal.sort(),
282 ],
283 alias: {
284 ...entryAliasConfiguration,
285 },
286 },
287 /* prettier-ignore */
288 define: {
289 // define is an esbuild function that replaces the any instances of given keys with the given values
290 // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify("TanStack Start")
291 // This is not the same as injecting environment variables.
292β
293 ...defineReplaceEnv('TSS_SERVER_FN_BASE', TSS_SERVER_FN_BASE),
294 ...defineReplaceEnv('TSS_CLIENT_OUTPUT_DIR', getClientOutputDirectory(viteConfig)),
295 ...defineReplaceEnv('TSS_ROUTER_BASEPATH', startConfig.router.basepath),
296 ...(command === 'serve' ? defineReplaceEnv('TSS_SHELL', startConfig.spa?.enabled ? 'true' : 'false') : {}),
297 ...defineReplaceEnv('TSS_DEV_SERVER', command === 'serve' ? 'true' : 'false'),
298 },
299 builder: {
300 sharedPlugins: true,
301 async buildApp(builder) {
302 const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]
303 const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]
304β
305 if (!client) {
306 throw new Error('Client environment not found')
307 }
308β
309 if (!server) {
310 throw new Error('SSR environment not found')
311 }
312β
313 if (!client.isBuilt) {
314 // Build the client bundle first
315 await builder.build(client)
316 }
317 if (!server.isBuilt) {
318 // Build the SSR bundle
319 await builder.build(server)
320 }
321 const serverBundle = getBundle(VITE_ENVIRONMENT_NAMES.server)
322 await postServerBuild({ builder, startConfig, serverBundle })
323 },
324 },
325 }
326 },
327 },
328 tanStackStartRouter(startPluginOpts, getConfig, corePluginOpts),
329 // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPlugin
330 startCompilerPlugin(corePluginOpts.framework),
331 createServerFnPlugin(corePluginOpts.framework),
332β
333 TanStackServerFnPlugin({
334 // This is the ID that will be available to look up and import
335 // our server function manifest and resolve its module
336 manifestVirtualImportId: VIRTUAL_MODULES.serverFnManifest,
337 generateFunctionId: startPluginOpts?.serverFns?.generateFunctionId,
338 client: {
339 getRuntimeCode: () =>
340 `import { createClientRpc } from '@tanstack/${corePluginOpts.framework}-start/client-rpc'`,
341 replacer: (d) => `createClientRpc('${d.functionId}')`,
342 envName: VITE_ENVIRONMENT_NAMES.client,
343 },
344 server: {
345 getRuntimeCode: () =>
346 `import { createServerRpc } from '@tanstack/${corePluginOpts.framework}-start/server-rpc'`,
347 replacer: (d) => `createServerRpc('${d.functionId}', ${d.fn})`,
348 envName: VITE_ENVIRONMENT_NAMES.server,
349 },
350 }),
351 loadEnvPlugin(),
352 startManifestPlugin({
353 getClientBundle: () => getBundle(VITE_ENVIRONMENT_NAMES.client),
354 getConfig,
355 }),
356 devServerPlugin({ getConfig }),
357 {
358 name: 'tanstack-start:core:capture-bundle',
359 applyToEnvironment(e) {
360 return (
361 e.name === VITE_ENVIRONMENT_NAMES.client ||
362 e.name === VITE_ENVIRONMENT_NAMES.server
363 )
364 },
365 enforce: 'post',
366 generateBundle(_options, bundle) {
367 const environment = this.environment.name as ViteEnvironmentNames
368 if (!Object.values(VITE_ENVIRONMENT_NAMES).includes(environment)) {
369 throw new Error(`Unknown environment: ${environment}`)
370 }
371 capturedBundle[environment] = bundle
372 },
373 },
374 ]
375}
376β
377function defineReplaceEnv<TKey extends string, TValue extends string>(
378 key: TKey,
379 value: TValue,
380): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {
381 return {
382 [`process.env.${key}`]: JSON.stringify(value),
383 [`import.meta.env.${key}`]: JSON.stringify(value),
384 } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }
385}