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