Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/virtual-route-external-physical.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/router-generator': minor
'@tanstack/router-plugin': minor
---

feat: external directories in `physical()` virtual route mounts
4 changes: 4 additions & 0 deletions packages/router-generator/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,10 @@ export class Generator {
)
}

public getPhysicalDirectories(): Array<string> {
return [...this.physicalDirectories]
}

public async run(event?: GeneratorEvent): Promise<void> {
if (
event &&
Expand Down
33 changes: 33 additions & 0 deletions packages/router-generator/tests/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,39 @@ describe('generator works', async () => {
})
})

it('physical() accepts a path outside routesDirectory', async () => {
const folderName = 'virtual-physical-external-abs'
const dir = makeFolderDir(folderName)
const externalDir = path.join(dir, 'external-target')
const config = await setupConfig(folderName, {
virtualRouteConfig: rootRoute('__root.tsx', [
index('index.tsx'),
physical('/external', externalDir),
]),
})

const { routeNodes, physicalDirectories } = await virtualGetRouteNodes(
config,
dir,
{
indexTokenSegmentRegex: /^(?:index)$/,
routeTokenSegmentRegex: /^(?:route)$/,
},
)

expect(physicalDirectories).toContain(externalDir)
expect(routeNodes.map((n) => n.routePath).sort()).toEqual([
'/',
'/external/bar',
'/external/foo',
])

const externalFoo = routeNodes.find((n) => n.routePath === '/external/foo')!
expect(path.resolve(config.routesDirectory, externalFoo.filePath)).toBe(
path.join(externalDir, 'foo.tsx'),
)
})

it.each(folderNames)(
'should create directory for routeTree if it does not exist',
async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/external/bar')({
component: () => 'bar',
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/external/foo')({
component: () => 'foo',
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* eslint-disable */

// @ts-nocheck

// noinspection JSUnusedGlobalSymbols

// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.

import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'

const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)

export interface FileRoutesByFullPath {
'/': typeof IndexRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/'
fileRoutesByTo: FileRoutesByTo
to: '/'
id: '__root__' | '/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
}

declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
}
}

const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createRootRoute, Outlet } from '@tanstack/react-router'

export const Route = createRootRoute({
component: () => <Outlet />,
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/')({ component: () => 'home' })
61 changes: 55 additions & 6 deletions packages/router-plugin/src/core/router-generator-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ import type { Config } from './config'

const PLUGIN_NAME = 'unplugin:router-generator'

// Physical mounts that point outside `routesDirectory` — their files aren't
// covered by the bundler's own watcher.
function getExternalPhysicalDirs(
generator: Generator,
routesDirectoryPath: string,
): Array<string> {
return generator
.getPhysicalDirectories()
.filter((dir) => !dir.startsWith(routesDirectoryPath))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
}

export const unpluginRouterGeneratorFactory: UnpluginFactory<
Partial<Config | (() => Config)> | undefined
> = (options = {}) => {
Expand Down Expand Up @@ -78,11 +89,30 @@ export const unpluginRouterGeneratorFactory: UnpluginFactory<
initConfigAndGenerator({ root: config.root })
await generate()
},
configureServer(server) {
const external = getExternalPhysicalDirs(
generator,
getRoutesDirectoryPath(),
)
if (external.length === 0) return
for (const dir of external) {
server.watcher.add(dir)
}
const onEvent =
(event: 'create' | 'update' | 'delete') => (file: string) => {
if (!external.some((dir) => file.startsWith(dir))) return
void generate({ file, event })
}
server.watcher.on('add', onEvent('create'))
server.watcher.on('change', onEvent('update'))
server.watcher.on('unlink', onEvent('delete'))
},
},
rspack(compiler) {
initConfigAndGenerator()

let handle: FSWatcher | null = null
let externalHandle: FSWatcher | null = null

compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, () => generate())

Expand All @@ -98,19 +128,29 @@ export const unpluginRouterGeneratorFactory: UnpluginFactory<
.watch(routesDirectoryPath, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))

// External physical() mounts are outside rspack's file graph.
const external = getExternalPhysicalDirs(generator, routesDirectoryPath)
if (external.length > 0) {
externalHandle = chokidar
.watch(external, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))
.on('change', (file) => generate({ file, event: 'update' }))
.on('unlink', (file) => generate({ file, event: 'delete' }))
}

await generate()
})

compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
Comment on lines 148 to 151
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

async callback in synchronous tap hook won't await cleanup.

The watchClose hook uses .tap() which is synchronous and won't wait for the async callback's promises. The async keyword here is misleading—handle.close() returns a Promise that won't be awaited.

This could cause watchers to not be fully closed during rapid dev server restarts.

Proposed fix: use fire-and-forget or void the promises explicitly
       compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
-        if (handle) await handle.close()
-        if (externalHandle) await externalHandle.close()
+        if (handle) void handle.close()
+        if (externalHandle) void externalHandle.close()
       })

Or alternatively, if cleanup needs to be awaited, investigate if rspack supports an async shutdown hook.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) void handle.close()
if (externalHandle) void externalHandle.close()
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-plugin/src/core/router-generator-plugin.ts` around lines 148
- 151, The callback passed to compiler.hooks.watchClose.tap (where PLUGIN_NAME
is used) is currently declared async so handle.close() and
externalHandle.close() return promises that won't be awaited by the synchronous
tap; change the callback to a synchronous function and either fire-and-forget
the promises or explicitly void them and handle errors: inside the
compiler.hooks.watchClose.tap(PLUGIN_NAME, ...) callback call void
handle?.close()?.catch(err => /* log or ignore */) and void
externalHandle?.close()?.catch(err => /* log or ignore */) (or otherwise call
handle.close() and externalHandle.close() and attach .catch handlers) so cleanup
is not misrepresented as awaited.

},
webpack(compiler) {
initConfigAndGenerator()

let handle: FSWatcher | null = null
let externalHandle: FSWatcher | null = null

compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, () => generate())

Expand All @@ -126,13 +166,22 @@ export const unpluginRouterGeneratorFactory: UnpluginFactory<
.watch(routesDirectoryPath, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))

// External physical() mounts are outside webpack's file graph.
const external = getExternalPhysicalDirs(generator, routesDirectoryPath)
if (external.length > 0) {
externalHandle = chokidar
.watch(external, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))
.on('change', (file) => generate({ file, event: 'update' }))
.on('unlink', (file) => generate({ file, event: 'delete' }))
}

await generate()
})

compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
Comment on lines 186 to 189
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Same async/tap mismatch as rspack.

Identical issue: the synchronous tap hook won't await the async callback's promises.

Proposed fix
       compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
-        if (handle) await handle.close()
-        if (externalHandle) await externalHandle.close()
+        if (handle) void handle.close()
+        if (externalHandle) void externalHandle.close()
       })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) void handle.close()
if (externalHandle) void externalHandle.close()
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-plugin/src/core/router-generator-plugin.ts` around lines 186
- 189, The watchClose hook is registered with compiler.hooks.watchClose.tap
using an async callback (referenced symbols: compiler.hooks.watchClose.tap,
PLUGIN_NAME, handle, externalHandle), which means the hook won't wait for the
async work; change the registration to use tapPromise so the returned Promise is
awaited: replace compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => { if
(handle) await handle.close(); if (externalHandle) await externalHandle.close();
}) with compiler.hooks.watchClose.tapPromise(PLUGIN_NAME, async () => { ... })
so handle.close() and externalHandle.close() are properly awaited.


compiler.hooks.done.tap(PLUGIN_NAME, () => {
Expand Down
106 changes: 106 additions & 0 deletions packages/router-plugin/tests/router-generator-plugin-watcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import chokidar from 'chokidar'
import { afterEach, beforeEach, describe, it } from 'vitest'

import { physical, rootRoute } from '@tanstack/virtual-file-routes'
import { unpluginRouterGeneratorFactory } from '../src/core/router-generator-plugin'

const ROOT_ROUTE = `import { createRootRoute, Outlet } from '@tanstack/react-router'
export const Route = createRootRoute({ component: () => null })
`

const makeRouteFile = (routePath: string) =>
`import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('${routePath}')({ component: () => null })
`

async function waitUntil(
condition: () => boolean | Promise<boolean>,
{ timeoutMs = 2000, intervalMs = 25 } = {},
) {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (await condition()) return
await new Promise((r) => setTimeout(r, intervalMs))
}
throw new Error(`Timed out after ${timeoutMs}ms`)
}

async function routeTreeIncludes(generatedRouteTree: string, match: string) {
try {
const text = await readFile(generatedRouteTree, 'utf-8')
return text.includes(match)
} catch {
return false
}
}

describe('router-generator-plugin vite watcher', () => {
let fixtureDir = ''
let externalDir = ''
let routesDir = ''
let generatedRouteTree = ''
let watcher: chokidar.FSWatcher | undefined

beforeEach(async () => {
fixtureDir = await mkdtemp(path.join(tmpdir(), 'tsr-plugin-watcher-'))
routesDir = path.join(fixtureDir, 'routes')
externalDir = path.join(fixtureDir, 'external')
generatedRouteTree = path.join(fixtureDir, 'routeTree.gen.ts')

await mkdir(routesDir, { recursive: true })
await mkdir(externalDir, { recursive: true })
await writeFile(path.join(routesDir, '__root.tsx'), ROOT_ROUTE)
await writeFile(
path.join(externalDir, 'alpha.tsx'),
makeRouteFile('/ext/alpha'),
)
})

afterEach(async () => {
if (watcher) {
await watcher.close()
watcher = undefined
}
await rm(fixtureDir, { recursive: true, force: true })
})

it('regenerates routeTree when a file is added to an external physical mount', async () => {
const plugin = unpluginRouterGeneratorFactory({
routesDirectory: routesDir,
generatedRouteTree,
virtualRouteConfig: rootRoute('__root.tsx', [
physical('/ext', externalDir),
]),
disableLogging: true,
})

const viteHooks = plugin.vite as {
configResolved: (config: { root: string }) => Promise<void>
configureServer: (server: {
watcher: chokidar.FSWatcher
}) => void | Promise<void>
}

await viteHooks.configResolved({ root: fixtureDir })
await waitUntil(() => routeTreeIncludes(generatedRouteTree, "'/ext/alpha'"))

watcher = chokidar.watch(routesDir, { ignoreInitial: true })
await new Promise((resolve) => watcher!.once('ready', resolve))
await viteHooks.configureServer({ watcher })

// Add a new route file in the external mount.
const betaPath = path.join(externalDir, 'beta.tsx')
await writeFile(betaPath, makeRouteFile('/ext/beta'))

await waitUntil(() => routeTreeIncludes(generatedRouteTree, "'/ext/beta'"))

// Removing the file should likewise trigger regeneration.
await rm(betaPath)
await waitUntil(
async () => !(await routeTreeIncludes(generatedRouteTree, "'/ext/beta'")),
)
})
})
Loading