Open History to see the last commit
1import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules'
2import { resolve as resolvePath } from 'pathe'
3import {
4 SERVER_FN_LOOKUP,
5 TRANSFORM_ID_REGEX,
6 VITE_ENVIRONMENT_NAMES,
7} from '../../constants'
8import { detectKindsInCode } from '../../start-compiler/compiler'
9import { getTransformCodeFilterForEnv } from '../../start-compiler/config'
10import {
11 createCompilerVirtualModuleIdPattern,
12 createStartCompiler,
13 loadCompilerVirtualModule,
14 mergeServerFnsById,
15} from '../../start-compiler/host'
16import { generateServerFnResolverModule } from '../../start-compiler/server-fn-resolver-module'
17import { cleanId } from '../../start-compiler/utils'
18import { createVirtualModule } from '../createVirtualModule'
19import {
20 MissingHydrateSourceError,
21 createHydrateCompilerPlugin,
22} from '../../hydrate-when-transform'
23import { resolveViteId } from '../../utils'
24import { appendIdQueryFlag, removeIdQueryFlag } from '../module-id'
25import {
26 createViteDevServerFnModuleSpecifierEncoder,
27 decodeViteDevServerModuleSpecifier,
28} from './module-specifier'
29import { mergeHotUpdateModules } from './hot-update'
30import type {
31 CompileStartFrameworkOptions,
32 StartCompilerImportTransform,
33 StartCompilerPlugin,
34} from '../../types'
35import type {
36 GenerateFunctionIdFnOptional,
37 ServerFn,
38} from '../../start-compiler/types'
39import type { Environment, EnvironmentModuleNode, PluginOption } from 'vite'
40β
41// Re-export from shared constants for backwards compatibility
42export { SERVER_FN_LOOKUP }
43β
44const validateServerFnIdVirtualModule = `virtual:tanstack-start-validate-server-fn-id`
45const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split'
46β
47type ModuleInvalidationEnvironment = {
48 moduleGraph: {
49 getModulesByFile: (file: string) => Set<EnvironmentModuleNode> | undefined
50 invalidateModule: (
51 mod: EnvironmentModuleNode,
52 seen?: Set<EnvironmentModuleNode>,
53 ) => void
54 }
55}
56β
57type ViteModuleLoadOptions = {
58 devId?: string
59 load: (options: { id: string }) => Promise<{ code?: string | null } | null>
60 error: (message: string) => never
61}
62β
63async function loadViteModuleFromEnvironment(
64 environment: Environment,
65 id: string,
66 opts: ViteModuleLoadOptions,
67): Promise<string | undefined> {
68 if (environment.mode === 'build') {
69 const loaded = await opts.load({ id })
70 return loaded?.code ?? ''
71 }
72β
73 if (environment.mode === 'dev') {
74 await environment.transformRequest(opts.devId ?? id)
75 return undefined
76 }
77β
78 opts.error(
79 `could not load module ${id}: unknown environment mode ${environment.mode}`,
80 )
81}
82β
83function invalidateMatchingFileModules(
84 environment: ModuleInvalidationEnvironment,
85 ids: Iterable<string>,
86 shouldInvalidate: (mod: EnvironmentModuleNode) => boolean,
87) {
88 const seen = new Set<EnvironmentModuleNode>()
89 const invalidatedModules: Array<EnvironmentModuleNode> = []
90β
91 for (const id of ids) {
92 const fileModules = environment.moduleGraph.getModulesByFile(cleanId(id))
93β
94 if (!fileModules) {
95 continue
96 }
97β
98 for (const fileModule of fileModules) {
99 if (!shouldInvalidate(fileModule)) {
100 continue
101 }
102β
103 environment.moduleGraph.invalidateModule(fileModule, seen)
104 invalidatedModules.push(fileModule)
105 }
106 }
107β
108 return invalidatedModules
109}
110β
111function invalidateServerFnProviderModules(
112 environment: {
113 moduleGraph: {
114 getModulesByFile: (file: string) => Set<EnvironmentModuleNode> | undefined
115 invalidateModule: (
116 mod: EnvironmentModuleNode,
117 seen?: Set<EnvironmentModuleNode>,
118 ) => void
119 }
120 },
121 ids: Iterable<string>,
122) {
123 return invalidateMatchingFileModules(
124 environment,
125 ids,
126 (fileModule) => fileModule.id?.includes(TSS_SERVERFN_SPLIT_PARAM) ?? false,
127 )
128}
129β
130function invalidateServerFnLookupModules(
131 environment: ModuleInvalidationEnvironment,
132 ids: Iterable<string>,
133) {
134 invalidateMatchingFileModules(
135 environment,
136 ids,
137 (fileModule) => fileModule.id?.includes(SERVER_FN_LOOKUP) ?? false,
138 )
139}
140β
141function invalidateCompilerVirtualModules(
142 environment: ModuleInvalidationEnvironment,
143 ids: Iterable<string>,
144 pattern: RegExp | undefined,
145) {
146 if (!pattern) {
147 return []
148 }
149β
150 return invalidateMatchingFileModules(environment, ids, (fileModule) => {
151 if (!fileModule.id) {
152 return false
153 }
154β
155 pattern.lastIndex = 0
156 return pattern.test(fileModule.id)
157 })
158}
159β
160function getServerFnProviderIds(ids: Iterable<string>) {
161 const providerIds = new Set<string>()
162β
163 for (const id of ids) {
164 const cleanedId = cleanId(id)
165 providerIds.add(`${cleanedId}?${TSS_SERVERFN_SPLIT_PARAM}`)
166 }
167β
168 return providerIds
169}
170β
171function invalidateModuleNodes(
172 environment: {
173 moduleGraph: {
174 invalidateModule: (
175 mod: EnvironmentModuleNode,
176 seen?: Set<EnvironmentModuleNode>,
177 ) => void
178 }
179 },
180 modules: Iterable<EnvironmentModuleNode>,
181) {
182 const seen = new Set<EnvironmentModuleNode>()
183β
184 for (const mod of modules) {
185 environment.moduleGraph.invalidateModule(mod, seen)
186 }
187}
188β
189function getDevServerFnValidatorModule(): string {
190 return `
191export async function getServerFnById(id, _access) {
192 const validateIdImport = ${JSON.stringify(validateServerFnIdVirtualModule)} + '?id=' + id
193 await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport)
194 const decoded = Buffer.from(id, 'base64url').toString('utf8')
195 const devServerFn = JSON.parse(decoded)
196 const mod = await import(/* @vite-ignore */ devServerFn.file)
197 return mod[devServerFn.export]
198}
199`
200}
201β
202function parseIdQuery(id: string): {
203 filename: string
204 query: {
205 [k: string]: string
206 }
207} {
208 if (!id.includes('?')) return { filename: id, query: {} }
209 const [filename, rawQuery] = id.split(`?`, 2) as [string, string]
210 const query = Object.fromEntries(new URLSearchParams(rawQuery))
211 return { filename, query }
212}
213β
214export interface StartCompilerPluginOptions {
215 framework: CompileStartFrameworkOptions
216 environments: Array<{
217 name: string
218 type: 'client' | 'server'
219 getServerFnById?: string
220 }>
221 /**
222 * Custom function ID generator (optional).
223 */
224 generateFunctionId?: GenerateFunctionIdFnOptional
225 compilerTransforms?: Array<StartCompilerImportTransform> | undefined
226 compilerPlugins?: Array<StartCompilerPlugin> | undefined
227 serverFnProviderModuleDirectives?: ReadonlyArray<string> | undefined
228 /**
229 * The Vite environment name for the server function provider.
230 */
231 providerEnvName: string
232}
233β
234export function startCompilerPlugin(
235 opts: StartCompilerPluginOptions,
236): PluginOption {
237 const compilers = new Map<string, ReturnType<typeof createStartCompiler>>()
238 const compilerPlugins = [
239 createHydrateCompilerPlugin(),
240 ...(opts.compilerPlugins ?? []),
241 ]
242 const compilerVirtualModuleIdPattern =
243 createCompilerVirtualModuleIdPattern(compilerPlugins)
244 const environmentByName = new Map(
245 opts.environments.map((environment) => [environment.name, environment]),
246 )
247β
248 // Shared registry of server functions across all environments
249 const serverFnsById: Record<string, ServerFn> = {}
250β
251 const onServerFnsById = (d: Record<string, ServerFn>) => {
252 mergeServerFnsById(serverFnsById, d)
253 }
254β
255 let root = process.cwd()
256 let bundledDev = false
257 // Determine which environments need the resolver (getServerFnById)
258 // SSR environment always needs the resolver for server-side calls
259 // Provider environment needs it for the actual implementation
260 const ssrEnvName = VITE_ENVIRONMENT_NAMES.server
261β
262 // SSR is the provider when the provider environment is the default server environment
263 const ssrIsProvider = opts.providerEnvName === ssrEnvName
264β
265 // Environments that need the resolver: SSR (for server calls) and provider (for implementation)
266 const appliedResolverEnvironments = new Set(
267 ssrIsProvider ? [opts.providerEnvName] : [ssrEnvName, opts.providerEnvName],
268 )
269β
270 function perEnvServerFnPlugin(environment: {
271 name: string
272 type: 'client' | 'server'
273 }): PluginOption {
274 const compilerTransforms =
275 environment.name === opts.providerEnvName
276 ? opts.compilerTransforms
277 : undefined
278 const serverFnProviderModuleDirectives =
279 environment.name === opts.providerEnvName
280 ? opts.serverFnProviderModuleDirectives
281 : undefined
282 // Derive transform code filter from KindDetectionPatterns (single source of truth)
283 const transformCodeFilter = getTransformCodeFilterForEnv(environment.type, {
284 compilerTransforms,
285 compilerPlugins,
286 })
287 return {
288 name: `tanstack-start-core::server-fn:${environment.name}`,
289 enforce: 'pre',
290 applyToEnvironment(env) {
291 return env.name === environment.name
292 },
293 configResolved(config) {
294 root = config.root
295 bundledDev = !!config.experimental.bundledDev
296 },
297 buildStart() {
298 if (
299 this.environment.mode === 'build' ||
300 (bundledDev &&
301 this.environment.name === VITE_ENVIRONMENT_NAMES.client)
302 ) {
303 // Vite app builds can run multiple Rolldown build phases with fresh
304 // plugin drivers. The compiler host closes over this hook context for
305 // load/resolve, so do not reuse it after a previous driver was closed.
306 compilers.delete(this.environment.name)
307 }
308 },
309 watchChange(id) {
310 if (bundledDev && this.environment.mode === 'dev') {
311 compilers.get(this.environment.name)?.invalidateModule(id)
312 }
313 },
314 transform: {
315 filter: {
316 id: {
317 exclude: new RegExp(`${SERVER_FN_LOOKUP}$`),
318 include: TRANSFORM_ID_REGEX,
319 },
320 code: {
321 include: transformCodeFilter,
322 },
323 },
324 async handler(code, id) {
325 let compiler = compilers.get(this.environment.name)
326β
327 if (!compiler) {
328 // Default to 'dev' mode for unknown environments (conservative: no caching)
329 const mode = this.environment.mode === 'build' ? 'build' : 'dev'
330β
331 compiler = createStartCompiler({
332 env: environment.type,
333 envName: environment.name,
334 root,
335 mode,
336 framework: opts.framework,
337 providerEnvName: opts.providerEnvName,
338 generateFunctionId: opts.generateFunctionId,
339 compilerTransforms,
340 compilerPlugins,
341 serverFnProviderModuleDirectives,
342 onServerFnsById,
343 getKnownServerFns: () => serverFnsById,
344 encodeModuleSpecifierInDev:
345 mode === 'dev'
346 ? createViteDevServerFnModuleSpecifierEncoder(root)
347 : undefined,
348 loadModule: async (id: string) => {
349 const code = await loadViteModuleFromEnvironment(
350 this.environment,
351 id,
352 {
353 load: (options) => this.load(options),
354 error: (message) => this.error(message),
355 devId: appendIdQueryFlag(id, SERVER_FN_LOOKUP),
356 },
357 )
358 if (code !== undefined) {
359 compiler!.ingestModule({ code, id })
360 }
361 },
362β
363 resolveId: async (source: string, importer?: string) => {
364 const r = await this.resolve(source, importer)
365β
366 if (r) {
367 if (!r.external) {
368 // Keep the resolved ID intact because it is passed back to
369 // Vite's load hook. Virtual-module prefixes and queries are
370 // part of that load identity, not compiler-only metadata.
371 return r.id
372 }
373 }
374β
375 return null
376 },
377 })
378β
379 compilers.set(this.environment.name, compiler)
380 }
381β
382 // Detect which kinds are present in this file before parsing
383 const detectedKinds = detectKindsInCode(code, environment.type, {
384 compilerTransforms,
385 })
386β
387 const result = await compiler.compile({
388 id,
389 code,
390 detectedKinds,
391 warn: (message) => this.warn(message),
392 })
393β
394 return result
395 },
396 },
397β
398 hotUpdate(ctx) {
399 const compiler = compilers.get(this.environment.name)
400 const idsToInvalidate = new Set<string>()
401 const transitiveCompilerImportersToInvalidate = new Set<string>()
402 const importerModulesToInvalidate = new Set<EnvironmentModuleNode>()
403 const changedIds: Array<string> = []
404β
405 ctx.modules.forEach((m) => {
406 if (m.id) {
407 idsToInvalidate.add(m.id)
408 changedIds.push(m.id)
409 }
410 })
411β
412 const deletedIds = compiler?.invalidateModules(changedIds) ?? new Set()
413β
414 ctx.modules.forEach((m) => {
415 if (m.id) {
416 if (deletedIds.has(cleanId(m.id))) {
417 transitiveCompilerImportersToInvalidate.add(cleanId(m.id))
418β
419 m.importers.forEach((importer) => {
420 if (importer.id) {
421 idsToInvalidate.add(importer.id)
422 importerModulesToInvalidate.add(importer)
423 transitiveCompilerImportersToInvalidate.add(
424 cleanId(importer.id),
425 )
426 }
427 })
428 }
429 }
430 })
431β
432 const finishHotUpdate = async () => {
433 if (
434 environment.type === 'server' &&
435 compiler &&
436 transitiveCompilerImportersToInvalidate.size > 0
437 ) {
438 const seenImporters = new Set(
439 transitiveCompilerImportersToInvalidate,
440 )
441 const nestedImporters =
442 await compiler.getTransitiveImporters(seenImporters)
443β
444 for (const nestedImporterId of nestedImporters) {
445 seenImporters.add(nestedImporterId)
446 }
447β
448 for (const importerId of seenImporters) {
449 idsToInvalidate.add(importerId)
450 }
451 compiler.invalidateModules(seenImporters)
452 }
453β
454 invalidateModuleNodes(this.environment, importerModulesToInvalidate)
455 invalidateServerFnLookupModules(this.environment, idsToInvalidate)
456 const compilerVirtualModules = invalidateCompilerVirtualModules(
457 this.environment,
458 idsToInvalidate,
459 compilerVirtualModuleIdPattern,
460 )
461β
462 if (environment.type !== 'server') {
463 return mergeHotUpdateModules(ctx.modules, compilerVirtualModules)
464 }
465β
466 invalidateModuleNodes(this.environment, ctx.modules)
467β
468 const providerIdsToInvalidate =
469 getServerFnProviderIds(idsToInvalidate)
470 compiler?.invalidateModules(providerIdsToInvalidate)
471β
472 const providerModules = invalidateServerFnProviderModules(
473 this.environment,
474 [...idsToInvalidate, ...providerIdsToInvalidate],
475 )
476β
477 return mergeHotUpdateModules(ctx.modules, [
478 ...compilerVirtualModules,
479 ...providerModules,
480 ])
481 }
482β
483 return finishHotUpdate()
484 },
485 }
486 }
487β
488 return [
489 ...opts.environments.map(perEnvServerFnPlugin),
490 {
491 name: 'tanstack-start-core:capture-server-fn-module-lookup',
492 // we only need this plugin in dev mode
493 apply: 'serve',
494 applyToEnvironment(env) {
495 return !!opts.environments.find((e) => e.name === env.name)
496 },
497 transform: {
498 filter: {
499 id: new RegExp(`${SERVER_FN_LOOKUP}$`),
500 },
501 handler(code, id) {
502 const compiler = compilers.get(this.environment.name)
503 compiler?.ingestModule({
504 code,
505 id: removeIdQueryFlag(id, SERVER_FN_LOOKUP),
506 })
507 },
508 },
509 },
510 {
511 name: 'tanstack-start-core:compiler-virtual-module',
512 enforce: 'pre',
513 load: {
514 filter: {
515 id: compilerVirtualModuleIdPattern ?? /$^/,
516 },
517 async handler(id) {
518 const environment = environmentByName.get(this.environment.name)
519 if (!environment || !compilerVirtualModuleIdPattern) {
520 return null
521 }
522β
523 const loadVirtualModule = () =>
524 loadCompilerVirtualModule(compilerPlugins, {
525 id,
526 root,
527 env: environment.type,
528 envName: this.environment.name,
529 })
530β
531 try {
532 return loadVirtualModule()
533 } catch (error) {
534 if (!(error instanceof MissingHydrateSourceError)) {
535 throw error
536 }
537 }
538β
539 const sourceId = cleanId(id)
540 await loadViteModuleFromEnvironment(this.environment, sourceId, {
541 load: (options) => this.load(options),
542 error: (message) => this.error(message),
543 })
544β
545 return loadVirtualModule()
546 },
547 },
548 },
549 // Validate server function ID in dev mode
550 {
551 name: 'tanstack-start-core:validate-server-fn-id',
552 apply: 'serve',
553 load: {
554 filter: {
555 id: new RegExp(resolveViteId(validateServerFnIdVirtualModule)),
556 },
557 async handler(id) {
558 const parsed = parseIdQuery(id)
559 const fnId = parsed.query.id
560 if (fnId && serverFnsById[fnId]) {
561 return `export {}`
562 }
563β
564 // ID not yet registered β the source file may not have been
565 // transformed in this dev session yet (e.g. cold restart with
566 // cached client). Try to decode the ID, discover the source
567 // file, trigger its compilation, and re-check.
568 if (fnId) {
569 try {
570 const decoded = JSON.parse(
571 Buffer.from(fnId, 'base64url').toString('utf8'),
572 )
573 if (
574 typeof decoded.file === 'string' &&
575 typeof decoded.export === 'string'
576 ) {
577 // Use the Vite when to decode the module specifier
578 // back to the original source file path.
579 const sourceFile = decodeViteDevServerModuleSpecifier(
580 decoded.file,
581 )
582β
583 if (sourceFile) {
584 // Resolve to absolute path
585 const absPath = resolvePath(root, sourceFile)
586β
587 // Trigger transform of the source file in this environment,
588 // which will compile createServerFn calls and populate
589 // serverFnsById as a side effect.
590 if (this.environment.mode !== 'dev') {
591 this.error(
592 `could not validate server function ID ${fnId}: unknown environment mode ${this.environment.mode}`,
593 )
594 }
595β
596 await this.environment.transformRequest(
597 `${absPath}?${SERVER_FN_LOOKUP}`,
598 )
599β
600 // Re-check after lazy compilation
601 if (serverFnsById[fnId]) {
602 return `export {}`
603 }
604 }
605 }
606 } catch {
607 // Decoding or fetching failed β fall through to error
608 }
609 }
610β
611 this.error(`Invalid server function ID: ${fnId}`)
612 },
613 },
614 },
615 // Manifest plugin for server environments
616 createVirtualModule({
617 name: 'tanstack-start-core:server-fn-resolver',
618 moduleId: VIRTUAL_MODULES.serverFnResolver,
619 enforce: 'pre',
620 applyToEnvironment: (env) => {
621 return appliedResolverEnvironments.has(env.name)
622 },
623 load() {
624 if (this.environment.name !== opts.providerEnvName) {
625 const mod = opts.environments.find(
626 (e) => e.name === this.environment.name,
627 )?.getServerFnById
628 if (mod) {
629 return mod
630 }
631β
632 this.error(
633 `No getServerFnById implementation found for caller environment: ${this.environment.name}`,
634 )
635 }
636β
637 if (this.environment.mode !== 'build') {
638 return getDevServerFnValidatorModule()
639 }
640β
641 // When SSR is the provider, server-only-referenced functions aren't in the manifest,
642 // so no isClientReferenced check is needed.
643 // When SSR is NOT the provider (custom provider env), server-only-referenced
644 // functions ARE in the manifest and need the isClientReferenced check to
645 // block direct client HTTP requests to server-only-referenced functions.
646 return generateServerFnResolverModule({
647 serverFnsById,
648 includeClientReferencedCheck: !ssrIsProvider,
649 // Only production builds reach this branch.
650 memoizeModules: true,
651 })
652 },
653 }),
654 ]
655}