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

plugin.ts

853 lines33.5 KB

1import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs'
2import { dirname, join, resolve } from 'node:path'
3import { fileURLToPath } from 'node:url'
4import { joinURL } from 'ufo'
5import {
6 applyResolvedBaseAndOutput,
7 applyResolvedRouterBasepath,
8 createStartConfigContext,
9} from '../config-context'
10import { normalizePath } from '../utils'
11import { createServerFnBasePath, normalizePublicBase } from '../planning'
12import { addWorkspaceWatchIgnored } from './watch-ignored'
13import { parseStartConfig, rsbuildClientOutputSchema } from './schema'
14import {
15 RSBUILD_CLIENT_ASSETS_DIR,
16 RSBUILD_ENVIRONMENT_NAMES,
17 RSBUILD_RSC_LAYERS,
18 createRsbuildEnvironmentPlan,
19 createRsbuildResolvedEntryAliases,
20 resolveRsbuildOutputDirectory,
21} from './planning'
22import { registerStartCompilerTransforms } from './start-compiler-host'
23import { registerImportProtection } from './import-protection'
24import {
25 START_MANIFEST_PLACEHOLDER,
26 registerVirtualModules,
27} from './virtual-modules'
28import { createServerSetup } from './server-middleware'
29import { registerClientBuildCapture } from './normalized-client-build'
30import { registerRouterPlugins } from './start-router-plugin'
31import { postBuildWithRsbuild } from './post-build'
32import { enableSwcReactServerComponents } from './swc-rsc'
33import type { ServerFn } from '../start-compiler/types'
34import type { TanStackStartRsbuildPluginCoreOptions } from './types'
35import type {
36 ModifyRspackConfigFn,
37 RsbuildDevServer,
38 RsbuildPlugin,
39 RsbuildPluginAPI,
40 Rspack,
41 rspack as rspackNamespaceType,
42} from '@rsbuild/core'
43import type { TanStackStartRsbuildInputConfig } from './schema'
44import type { ScriptFormat } from '@tanstack/router-core'
45​
46// Detect whether this plugin source is running from inside the TanStack
47// Router monorepo (packages/start-plugin-core/src/rsbuild/plugin.ts). When
48// installed from npm in a user app, the path structure is different and
49// this evaluates to false. Used to gate dev-only workarounds that only
50// matter when workspace package dists are symlinked into node_modules.
51const currentDir = dirname(fileURLToPath(import.meta.url))
52const isInsideRouterMonoRepo = (() => {
53 // src layout: <repo>/packages/start-plugin-core/src/rsbuild → 4 levels up
54 // dist layout (CJS/ESM): <repo>/packages/start-plugin-core/dist/<fmt>/rsbuild
55 // → also 4 levels up
56 const candidate = resolve(currentDir, '../../../../')
57 return candidate.endsWith('/packages') || candidate.endsWith('\\packages')
58})()
59​
60type RspackNamespace = typeof rspackNamespaceType
61type RscPluginPair = ReturnType<
62 NonNullable<RspackNamespace['experiments']['rsc']>['createPlugins']
64type RspackConfig = Parameters<ModifyRspackConfigFn>[0]
65type RspackCompiler = Rspack.Compiler
66type RspackCompilationExtended = Rspack.Compilation
67type RspackAsset = ReturnType<RspackCompilationExtended['getAssets']>[number]
68​
69export function tanStackStartRsbuild(
70 corePluginOpts: TanStackStartRsbuildPluginCoreOptions,
71 startPluginOpts: TanStackStartRsbuildInputConfig = {},
72): RsbuildPlugin {
73 const rscOpts = corePluginOpts.rsc
74 const rscEnabled = Boolean(rscOpts)
75​
76 const configContext = createStartConfigContext({
77 corePluginOpts,
78 startPluginOpts,
79 parseConfig: parseStartConfig,
80 })
81 const { getConfig, resolvedStartConfig } = configContext
82 const serverFnProviderEnv = corePluginOpts.providerEnvironmentName
83 const ssrIsProvider = corePluginOpts.ssrIsProvider
84 const scriptFormat = rsbuildClientOutputSchema.parse(
85 startPluginOpts.rsbuild?.client?.output ?? 'module',
86 ) satisfies ScriptFormat
87​
88 // RSC plugin instances — created lazily when rspack namespace is available
89 let rscPlugins: RscPluginPair | undefined
90​
91 // Reference to the dev server for RSC HMR socket writes
92 let devServerRef: Pick<RsbuildDevServer, 'sockWrite'> | null = null
93 const serverFnsById: Record<string, ServerFn> = {}
94 let updateServerFnResolver: (() => void) | undefined
95​
96 return {
97 name: 'tanstack-start-rsbuild',
98 setup(api: RsbuildPluginAPI) {
99 const startCompilerEnvironments = [
100 { name: RSBUILD_ENVIRONMENT_NAMES.client, type: 'client' as const },
101 { name: RSBUILD_ENVIRONMENT_NAMES.server, type: 'server' as const },
102 ...(serverFnProviderEnv !== RSBUILD_ENVIRONMENT_NAMES.server &&
103 !rscEnabled
104 ? [{ name: serverFnProviderEnv, type: 'server' as const }]
105 : []),
106 ]
107 const startCompilerServerEnvironmentNames = startCompilerEnvironments
108 .filter((env) => env.type === 'server')
109 .map((env) => env.name)
110​
111 // ---------------------------------------------------------------
112 // 1. modifyRsbuildConfig — resolve config, set up environments
113 // ---------------------------------------------------------------
114 api.modifyRsbuildConfig((rsbuildConfig, { mergeRsbuildConfig }) => {
115 const root =
116 typeof rsbuildConfig.root === 'string'
117 ? rsbuildConfig.root
118 : process.cwd()
119​
120 const serverBase = rsbuildConfig.server?.base
121 const assetPrefix = rsbuildConfig.output?.assetPrefix
122 const publicBase = normalizePublicBase(
123 typeof serverBase === 'string'
124 ? serverBase
125 : typeof assetPrefix === 'string' && assetPrefix !== 'auto'
126 ? assetPrefix
127 : undefined,
128 )
129 const rootDistPath = rsbuildConfig.output?.distPath
130 const clientDistPath =
131 rsbuildConfig.environments?.[RSBUILD_ENVIRONMENT_NAMES.client]?.output
132 ?.distPath
133 const serverDistPath =
134 rsbuildConfig.environments?.[RSBUILD_ENVIRONMENT_NAMES.server]?.output
135 ?.distPath
136​
137 applyResolvedBaseAndOutput({
138 resolvedStartConfig,
139 root,
140 publicBase,
141 clientOutputDirectory: resolveRsbuildOutputDirectory({
142 distPath: clientDistPath,
143 rootDistPath,
144 fallback: 'dist/client',
145 subdirectory: 'client',
146 }),
147 serverOutputDirectory: resolveRsbuildOutputDirectory({
148 distPath: serverDistPath,
149 rootDistPath,
150 fallback: 'dist/server',
151 subdirectory: 'server',
152 }),
153 })
154​
155 const { startConfig } = getConfig()
156 const routerBasepath = applyResolvedRouterBasepath({
157 resolvedStartConfig,
158 startConfig,
159 })
160​
161 const resolvedEntryPlan = configContext.resolveEntries()
162 const isDev = api.context.action === 'dev'
163 const isPreview = api.context.action === 'preview'
164​
165 const entryAliases = createRsbuildResolvedEntryAliases({
166 entryPaths: resolvedEntryPlan.entryPaths,
167 })
168​
169 const environmentPlan = createRsbuildEnvironmentPlan({
170 root,
171 entryAliases,
172 clientOutputDirectory: resolvedStartConfig.outputDirectories.client,
173 serverOutputDirectory: resolvedStartConfig.outputDirectories.server,
174 publicBase: resolvedStartConfig.basePaths.publicBase,
175 serverFnProviderEnv,
176 environmentOverrides: corePluginOpts.rsbuild?.environments,
177 scriptFormat,
178 rsc: rscOpts,
179 dev: isDev,
180 })
181 const serverFnBase = createServerFnBasePath({
182 routerBasepath,
183 serverFnBase: startConfig.serverFns.base,
184 })
185 const inlineCssEnabled =
186 !isDev && startConfig.server.build.inlineCss.enabled
187​
188 return mergeRsbuildConfig(rsbuildConfig, {
189 source: {
190 ...(rscEnabled
191 ? {
192 include: [
193 // RSC needs SWC to inspect package code in node_modules so directives such as "use client" can be discovered.
194 // This follows Rsbuild's documented broad include form for compiling node_modules, with core-js excluded:
195 // https://rsbuild.rs/config/source/include#compile-node_modules
196 //
197 // TODO: Once the Rspack rule matching needed here is ready, narrow this to React-aware packages, for example via
198 // descriptionData: { "peerDependencies.react": /./ }, so unrelated dependencies are not sent through swc-loader.
199 {
200 not: /[\\/]core-js[\\/]/,
201 },
202 ],
203 }
204 : {}),
205 define: {
206 'process.env.TSS_SERVER_FN_BASE': JSON.stringify(serverFnBase),
207 'import.meta.env.TSS_SERVER_FN_BASE':
208 JSON.stringify(serverFnBase),
209 'process.env.TSS_ROUTER_BASEPATH': JSON.stringify(routerBasepath),
210 'import.meta.env.TSS_ROUTER_BASEPATH':
211 JSON.stringify(routerBasepath),
212 'process.env.TSS_DEV_SERVER': JSON.stringify(
213 isDev ? 'true' : 'false',
214 ),
215 'import.meta.env.TSS_DEV_SERVER': JSON.stringify(
216 isDev ? 'true' : 'false',
217 ),
218 // Rsbuild dev already injects emitted CSS asset hrefs, so keep
219 // Start's synthetic `/@tanstack-start/styles.css` path disabled.
220 'process.env.TSS_DEV_SSR_STYLES_ENABLED': JSON.stringify('false'),
221 'import.meta.env.TSS_DEV_SSR_STYLES_ENABLED':
222 JSON.stringify('false'),
223 'process.env.TSS_DEV_SSR_STYLES_BASEPATH': JSON.stringify(
224 resolvedStartConfig.basePaths.publicBase,
225 ),
226 'import.meta.env.TSS_DEV_SSR_STYLES_BASEPATH': JSON.stringify(
227 resolvedStartConfig.basePaths.publicBase,
228 ),
229 'process.env.TSS_INLINE_CSS_ENABLED': JSON.stringify(
230 inlineCssEnabled ? 'true' : 'false',
231 ),
232 'import.meta.env.TSS_INLINE_CSS_ENABLED': JSON.stringify(
233 inlineCssEnabled ? 'true' : 'false',
234 ),
235 'process.env.TSS_DISABLE_CSRF_MIDDLEWARE_WARNING': JSON.stringify(
236 startConfig.serverFns.disableCsrfMiddlewareWarning
237 ? 'true'
238 : 'false',
239 ),
240 'import.meta.env.TSS_DISABLE_CSRF_MIDDLEWARE_WARNING':
241 JSON.stringify(
242 startConfig.serverFns.disableCsrfMiddlewareWarning
243 ? 'true'
244 : 'false',
245 ),
246 },
247 },
248 server: {
249 ...(rsbuildConfig.server?.printUrls === undefined ||
250 rsbuildConfig.server.printUrls === true
251 ? { printUrls: ({ urls }: { urls: Array<string> }) => urls }
252 : {}),
253 // Rsbuild compression currently treats Node's raw header array
254 // writeHead form as an object, which corrupts SSR response headers.
255 compress: false,
256 // SSR apps render every route on the server — disable HTML
257 // fallback so rsbuild doesn't intercept /_serverFn/ URLs.
258 htmlFallback: false,
259 // server.setup returned callback runs after built-in middleware
260 // but BEFORE fallback middleware — the ideal slot for SSR.
261 // Preview always installs the middleware since it is the only SSR
262 // handler; dev can opt out when a custom server hosts SSR.
263 ...(isPreview ||
264 (isDev &&
265 startPluginOpts.rsbuild?.installDevServerMiddleware !== false)
266 ? {
267 setup: createServerSetup({
268 serverFnBasePath: serverFnBase,
269 serverOutputDirectory:
270 resolvedStartConfig.outputDirectories.server,
271 publicBase: resolvedStartConfig.basePaths.publicBase,
272 }),
273 }
274 : {}),
275 },
276 ...(isDev
277 ? {
278 dev: {
279 lazyCompilation: false,
280 ...(rscEnabled ? { liveReload: false } : {}),
281 },
282 }
283 : {}),
284 environments: environmentPlan.environments,
285 resolve: {
286 alias: environmentPlan.alias,
287 },
288 })
289 })
290​
291 // ---------------------------------------------------------------
292 // 2. StartCompiler transforms — server fns, isomorphic fns, etc.
293 // ---------------------------------------------------------------
294 registerStartCompilerTransforms(api, {
295 framework: corePluginOpts.framework,
296 // modifyRsbuildConfig copies rsbuildConfig.root into resolvedStartConfig.root,
297 // so defer this read until transform time instead of falling back to
298 // process.cwd() during plugin setup.
299 root: () => resolvedStartConfig.root || process.cwd(),
300 environments: startCompilerEnvironments,
301 providerEnvName: serverFnProviderEnv,
302 generateFunctionId: startPluginOpts.serverFns?.generateFunctionId,
303 compilerTransforms: corePluginOpts.compilerTransforms,
304 serverFnProviderModuleDirectives:
305 corePluginOpts.serverFnProviderModuleDirectives,
306 serverFnsById,
307 onServerFnsByIdChange: () => {
308 updateServerFnResolver?.()
309 },
310 })
311​
312 registerImportProtection(api, {
313 getConfig,
314 framework: corePluginOpts.framework,
315 environments: startCompilerEnvironments,
316 })
317​
318 // ---------------------------------------------------------------
319 // 3. Virtual modules — manifest, server fn resolver, adapters,
320 // RSC runtime, RSC HMR
321 // ---------------------------------------------------------------
322 const virtualModuleState = registerVirtualModules(api, {
323 root: resolvedStartConfig.root || process.cwd(),
324 getConfig,
325 serverFnsById,
326 providerEnvName: serverFnProviderEnv,
327 ssrIsProvider,
328 serializationAdapters: corePluginOpts.serializationAdapters,
329 getDevClientEntryUrl: (publicBase: string) =>
330 joinURL(publicBase, RSBUILD_CLIENT_ASSETS_DIR, 'js/index.js'),
331 rscEnabled,
332 scriptFormat,
333 })
334 updateServerFnResolver = virtualModuleState.updateServerFnResolver
335​
336 if (!rscEnabled) {
337 api.modifyRspackConfig((config, utils) => {
338 if (
339 !startCompilerServerEnvironmentNames.includes(
340 utils.environment.name,
341 )
342 ) {
343 return
344 }
345​
346 config.plugins.push({
347 apply(compiler: RspackCompiler) {
348 compiler.hooks.finishMake.tapPromise(
349 {
350 name: 'TanStackStartServerFnResolverRebuild',
351 stage: -10,
352 },
353 async (compilation: RspackCompilationExtended) => {
354 virtualModuleState.updateServerFnResolver()
355​
356 await rebuildModulesContaining(
357 compilation,
358 virtualModuleState.serverFnResolverPath,
359 )
360 },
361 )
362 },
363 })
364 })
365 }
366​
367 // ---------------------------------------------------------------
368 // 4. Client build stats capture via processAssets
369 // ---------------------------------------------------------------
370 const { getClientBuild } = registerClientBuildCapture(api, getConfig)
371​
372 // ---------------------------------------------------------------
373 // 4b. Server manifest module generation (build only)
374 // For ordinary multi-environment builds, Rsbuild can compile the
375 // server environment after the client environment finishes. Generate
376 // the final manifest as module source in that phase instead of
377 // patching emitted server assets afterwards.
378 // ---------------------------------------------------------------
379 if (api.context.action !== 'dev') {
380 const normalizedManifestPath = normalizePath(
381 virtualModuleState.manifestPath,
382 )
383 const matchesManifestPath = (id: string) =>
384 normalizePath(id) === normalizedManifestPath
385​
386 api.transform(
387 {
388 test: (id: string) => matchesManifestPath(id),
389 environments: [RSBUILD_ENVIRONMENT_NAMES.server],
390 },
391 ({ code }) => {
392 const clientBuild = getClientBuild()
393​
394 if (clientBuild) {
395 return virtualModuleState.generateManifestContent(clientBuild)
396 }
397​
398 if (!rscEnabled) {
399 throw new Error(
400 'TanStack Start could not generate the rsbuild server manifest before the client build completed',
401 )
402 }
403​
404 // RSC builds cannot express the required client -> server ordering
405 // through MultiCompiler dependencies, so keep the placeholder for
406 // the RSC-only asset-patching fallback below.
407 return code
408 },
409 )
410 }
411​
412 // ---------------------------------------------------------------
413 // 5. Router plugin wiring (generator + code splitter)
414 // ---------------------------------------------------------------
415 registerRouterPlugins(api, {
416 getConfig,
417 corePluginOpts,
418 startPluginOpts,
419 })
420​
421 // ---------------------------------------------------------------
422 // 6. Dev SSR middleware — registered via server.setup in
423 // modifyRsbuildConfig above (returned callback runs after
424 // built-ins but before fallback middleware)
425 // ---------------------------------------------------------------
426​
427 // ---------------------------------------------------------------
428 // 6b. Dev watcher: ignore workspace package `dist/**` directories.
429 //
430 // In a real user app, `@tanstack/react-router` and friends live
431 // inside `node_modules/` and are ignored by Rspack's default
432 // watcher. In this monorepo, pnpm symlinks them to
433 // `packages/*/dist` (realpath outside node_modules), so the
434 // watcher follows them and treats their dist files as live
435 // sources. If anything rewrites those files during dev, Rspack
436 // sees transient half-written modules and fails to resolve
437 // relative imports between them.
438 //
439 // Only apply this in monorepo development. In user apps this
440 // is a no-op — their `node_modules/@tanstack/*/dist/**` is
441 // already ignored by Rspack's default watchOptions.
442 // ---------------------------------------------------------------
443 if (isInsideRouterMonoRepo && api.context.action === 'dev') {
444 api.modifyRspackConfig((config) => {
445 const workspaceDistRealpaths = resolveWorkspacePackageDistRealpaths()
446 if (workspaceDistRealpaths.length === 0) return
447​
448 config.watchOptions = {
449 ...(config.watchOptions ?? {}),
450 ignored: addWorkspaceWatchIgnored(
451 config.watchOptions?.ignored,
452 workspaceDistRealpaths,
453 ),
454 }
455 })
456 }
457​
458 // ---------------------------------------------------------------
459 // 7. RSC: rspack layer rules + native RSC plugins
460 // When RSC is enabled, we add:
461 // - issuerLayer rule for react-server condition propagation
462 // - SWC reactServerComponents: true
463 // - rspack ServerPlugin (server env) / ClientPlugin (client env)
464 // The Coordinator inside createPlugins() handles compilation
465 // ordering (server→client→server-actions) automatically.
466 // ---------------------------------------------------------------
467 if (rscEnabled) {
468 api.modifyRspackConfig((config, utils) => {
469 const envName = utils.environment.name
470 const isServerEnv = envName === RSBUILD_ENVIRONMENT_NAMES.server
471 const isClientEnv = envName === RSBUILD_ENVIRONMENT_NAMES.client
472​
473 // Create RSC plugin pair lazily (once per build)
474 if (!rscPlugins) {
475 rscPlugins = utils.rspack.experiments.rsc.createPlugins()
476 }
477​
478 if (isServerEnv) {
479 // --- issuerLayer rule: modules imported from RSC layer
480 // get react-server resolve condition ---
481 const moduleRules = (config.module.rules ??= [])
482 const root = resolvedStartConfig.root || process.cwd()
483​
484 // Split server-fn provider modules are the actual RSC execution
485 // boundary in Start's layered model. They must compile in the
486 // RSC layer so React and react-server-dom-rspack resolve their
487 // react-server exports without forcing the whole SSR graph into
488 // react-server conditions.
489 moduleRules.push({
490 resourceQuery: /(?:^|[?&])tss-serverfn-split(?:&|$)/,
491 layer: RSBUILD_RSC_LAYERS.rsc,
492 resolve: {
493 conditionNames: ['react-server', '...'],
494 },
495 })
496​
497 // All modules imported from the RSC layer inherit
498 // the react-server condition (transitive propagation), except
499 // route split virtual modules. Those remain ordinary SSR/client
500 // route code; only `?tsr-shared=1` modules may be shared with the
501 // provider subtree.
502 moduleRules.push({
503 issuerLayer: RSBUILD_RSC_LAYERS.rsc,
504 resourceQuery: {
505 not: [/(?:^|[?&])tsr-split(?:=|&|$)/],
506 },
507 resolve: {
508 conditionNames: ['react-server', '...'],
509 },
510 })
511​
512 // The RSC ServerPlugin injects imports like
513 // `react-server-dom-rspack/server` into transformed modules.
514 // Some modules in the server graph resolve from real package paths
515 // outside the app root, so relying on the default relative
516 // `node_modules` lookup is not enough. Seed resolve.modules with the
517 // app root explicitly, without package-manager-specific heuristics.
518 seedResolveModules(config, [`${root}/node_modules`, 'node_modules'])
519​
520 // Add ServerPlugin with HMR callback
521 config.plugins.push(
522 new rscPlugins.ServerPlugin({
523 cssLink: {
524 precedence: false,
525 props: {
526 'data-rsc-css-href': '',
527 },
528 },
529 onServerComponentChanges: () => {
530 // Send rsc:update to connected clients for HMR
531 devServerRef?.sockWrite('custom', {
532 event: 'rsc:update',
533 })
534 },
535 }),
536 )
537​
538 config.plugins.push({
539 apply(compiler: RspackCompiler) {
540 compiler.hooks.finishMake.tapPromise(
541 {
542 name: 'TanStackStartRscServerFnResolverRebuild',
543 stage: -10,
544 },
545 async (compilation: RspackCompilationExtended) => {
546 const resolverContent =
547 virtualModuleState.generateCurrentResolverContent(true)
548 virtualModuleState.tryUpdateServerFnResolver(
549 resolverContent,
550 )
551​
552 await rebuildModulesContaining(
553 compilation,
554 virtualModuleState.serverFnResolverPath,
555 )
556 },
557 )
558 },
559 })
560​
561 if (api.context.action !== 'dev') {
562 config.plugins.push({
563 apply(compiler: RspackCompiler) {
564 compiler.hooks.finishMake.tapPromise(
565 {
566 name: 'TanStackStartRscManifestRebuild',
567 // The native RSC ServerPlugin completes the client-entry
568 // handoff during its finishMake hook. Rebuild the manifest
569 // after that point so the transform hook can emit the final
570 // manifest source instead of the placeholder.
571 stage: 10,
572 },
573 async (compilation: RspackCompilationExtended) => {
574 const clientBuild = getClientBuild()
575​
576 if (!clientBuild) {
577 return
578 }
579​
580 virtualModuleState.updateManifest(clientBuild)
581​
582 await rebuildModulesContaining(
583 compilation,
584 virtualModuleState.manifestPath,
585 )
586 },
587 )
588 },
589 })
590 }
591 }
592​
593 if (isClientEnv) {
594 // Add ClientPlugin — the Coordinator links it to the
595 // ServerPlugin's compilation state
596 config.plugins.push(new rscPlugins.ClientPlugin())
597 }
598​
599 // --- SWC reactServerComponents ---
600 // Enable RSC directive detection where the native RSC plugins need it.
601 // In the server build, scope it to the actual RSC provider subtree so
602 // ordinary route-split modules (e.g. ?tsr-split=component) stay out of
603 // RSC validation unless they are really imported by a provider module.
604 if (isServerEnv) {
605 enableSwcReactServerComponents(config, 'rsc-subtree')
606 } else if (isClientEnv) {
607 enableSwcReactServerComponents(config, 'all')
608 }
609 })
610​
611 // Capture dev server reference for RSC HMR socket writes
612 if (api.context.action === 'dev') {
613 api.onBeforeStartDevServer(({ server }) => {
614 devServerRef = server
615 })
616 }
617 }
618​
619 // ---------------------------------------------------------------
620 // 8. Build ordering — client must complete before server starts
621 // so that the manifest virtual module has real client build stats.
622 // Uses rspack MultiCompiler.setDependencies() under the hood.
623 //
624 // IMPORTANT: When RSC is enabled we must NOT set dependencies.
625 // The RSC Coordinator already orchestrates server↔client
626 // compilation ordering by interleaving phases within compiler
627 // hooks. Adding setDependencies(server, [client]) on top of
628 // the Coordinator creates a deadlock: MultiCompiler blocks
629 // the server compiler until client is `done`, but the
630 // Coordinator blocks the client's `make` hook until the
631 // server's entries phase completes — neither can start.
632 // ---------------------------------------------------------------
633 if (!rscEnabled) {
634 api.onAfterCreateCompiler(({ compiler }) => {
635 // MultiCompiler has a `compilers` array; single compiler does not
636 if ('compilers' in compiler) {
637 for (const environmentName of startCompilerServerEnvironmentNames) {
638 const serverCompiler = compiler.compilers.find(
639 (c) => c.name === environmentName,
640 )
641 if (serverCompiler) {
642 const dependencies: Array<string> = [
643 RSBUILD_ENVIRONMENT_NAMES.client,
644 ]
645 if (
646 environmentName === RSBUILD_ENVIRONMENT_NAMES.server &&
647 serverFnProviderEnv !== RSBUILD_ENVIRONMENT_NAMES.server
648 ) {
649 dependencies.push(serverFnProviderEnv)
650 }
651​
652 compiler.setDependencies(serverCompiler, dependencies)
653 }
654 }
655 }
656 })
657 }
658​
659 // ---------------------------------------------------------------
660 // 8b. Manifest asset replacement fallback (RSC build only)
661 // Rsbuild's native RSC coordinator interleaves server and client
662 // compilers, so the server manifest module can compile before Start's
663 // normalized client build stats exist. Keep final replacement in the
664 // server asset pipeline, after the client processAssets capture has a
665 // chance to run.
666 // ---------------------------------------------------------------
667 if (api.context.action !== 'dev' && rscEnabled) {
668 const manifestPlaceholderLiteral = JSON.stringify(
669 START_MANIFEST_PLACEHOLDER,
670 )
671 api.modifyRspackConfig((config, utils) => {
672 if (utils.environment.name !== RSBUILD_ENVIRONMENT_NAMES.server)
673 return
674​
675 config.plugins.push({
676 apply(compiler: RspackCompiler) {
677 compiler.hooks.compilation.tap(
678 'TanStackStartManifestReplace',
679 (compilation: RspackCompilationExtended) => {
680 compilation.hooks.processAssets.tap(
681 {
682 name: 'TanStackStartManifestReplace',
683 stage:
684 utils.rspack.Compilation
685 .PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
686 },
687 () => {
688 let assetsWithPlaceholder:
689 | Array<{ asset: RspackAsset; sourceStr: string }>
690 | undefined
691​
692 for (const asset of compilation.getAssets()) {
693 if (!asset.name.endsWith('.js')) {
694 continue
695 }
696​
697 const sourceStr = String(asset.source.source())
698 if (!sourceStr.includes(manifestPlaceholderLiteral)) {
699 continue
700 }
701​
702 if (!assetsWithPlaceholder) {
703 assetsWithPlaceholder = []
704 }
705 assetsWithPlaceholder.push({
706 asset,
707 sourceStr,
708 })
709 }
710​
711 if (!assetsWithPlaceholder) {
712 return
713 }
714​
715 const clientBuild = getClientBuild()
716 if (!clientBuild) {
717 throw new Error(
718 'TanStack Start could not replace the rsbuild RSC server manifest placeholder because the client build was unavailable',
719 )
720 }
721​
722 const manifestValueLiteral =
723 virtualModuleState.generateManifestValueLiteral(
724 clientBuild,
725 )
726​
727 for (const {
728 asset,
729 sourceStr,
730 } of assetsWithPlaceholder) {
731 compilation.updateAsset(
732 asset.name,
733 new utils.rspack.sources.RawSource(
734 sourceStr.replace(
735 manifestPlaceholderLiteral,
736 manifestValueLiteral,
737 ),
738 ),
739 )
740 }
741 },
742 )
743 },
744 )
745 },
746 })
747 })
748 }
749​
750 // ---------------------------------------------------------------
751 // 9. After client env compiles — refresh resolver + manifest
752 // ---------------------------------------------------------------
753 api.onAfterEnvironmentCompile(({ environment }) => {
754 if (environment.name !== RSBUILD_ENVIRONMENT_NAMES.client) return
755​
756 virtualModuleState.updateServerFnResolver()
757​
758 const clientBuild = getClientBuild()
759 if (clientBuild) {
760 virtualModuleState.updateManifest(clientBuild)
761 }
762 })
763​
764 if (api.context.action === 'build') {
765 api.onAfterBuild(async () => {
766 const { startConfig } = getConfig()
767​
768 await postBuildWithRsbuild({
769 startConfig,
770 clientOutputDirectory: resolvedStartConfig.outputDirectories.client,
771 serverOutputDirectory: resolvedStartConfig.outputDirectories.server,
772 })
773 })
774 }
775 },
776 }
778​
779function seedResolveModules(
780 config: RspackConfig,
781 entries: Array<string>,
782): void {
783 const resolveModules = (config.resolve.modules ??= [])
784​
785 for (const entry of entries) {
786 if (!resolveModules.includes(entry)) {
787 resolveModules.push(entry)
788 }
789 }
791​
792function rebuildModulesContaining(
793 compilation: RspackCompilationExtended,
794 identifierFragment: string,
795): Promise<void> {
796 const rebuilds: Array<Promise<void>> = []
797 for (const mod of compilation.modules) {
798 if (!mod.identifier().includes(identifierFragment)) {
799 continue
800 }
801​
802 rebuilds.push(
803 new Promise<void>((resolve, reject) => {
804 compilation.rebuildModule(mod, (err: Error | null) => {
805 if (err) reject(err)
806 else resolve()
807 })
808 }),
809 )
810 }
811​
812 return rebuilds.length === 0
813 ? Promise.resolve()
814 : Promise.all(rebuilds).then(() => undefined)
816​
817/**
818 * Return the realpath of every packages/<name>/dist directory in the
819 * TanStack Router monorepo. Only meaningful when called from inside the
820 * monorepo — in user apps, callers should guard with
821 * `isInsideRouterMonoRepo` before invoking this.
822 */
823function resolveWorkspacePackageDistRealpaths(): Array<string> {
824 // currentDir points at either <repo>/packages/start-plugin-core/src/rsbuild
825 // or <repo>/packages/start-plugin-core/dist/<fmt>/rsbuild. Four levels up
826 // lands on <repo>/packages in both layouts.
827 const packagesDir = resolve(currentDir, '../../../../')
828 if (!existsSync(packagesDir)) return []
829​
830 let entries: Array<string>
831 try {
832 entries = readdirSync(packagesDir)
833 } catch {
834 return []
835 }
836​
837 const dists: Array<string> = []
838 for (const entry of entries) {
839 const distPath = join(packagesDir, entry, 'dist')
840 try {
841 if (!statSync(distPath).isDirectory()) continue
842 } catch {
843 continue
844 }
845 try {
846 dists.push(realpathSync(distPath))
847 } catch {
848 dists.push(distPath)
849 }
850 }
851​
852 return dists