diff --git a/.changeset/rsbuild-watched-directory-edits.md b/.changeset/rsbuild-watched-directory-edits.md new file mode 100644 index 0000000000..1dfe706b31 --- /dev/null +++ b/.changeset/rsbuild-watched-directory-edits.md @@ -0,0 +1,6 @@ +--- +'@tanstack/start-plugin-core': patch +'@tanstack/router-utils': patch +--- + +Rsbuild dev: a directory a plugin watches (Tailwind CSS adds the ones it scans) is no longer taken for a created file when Rspack reports it modified, and a created file asks again only the resolutions it may take. Under Yarn PnP the first route edit of such an app rebuilt a module of `@tanstack/start-client-core`, which Rspack then failed to resolve, breaking every later compile. diff --git a/packages/router-utils/src/compiler/host.ts b/packages/router-utils/src/compiler/host.ts index cf57875045..6aca7a1aac 100644 --- a/packages/router-utils/src/compiler/host.ts +++ b/packages/router-utils/src/compiler/host.ts @@ -387,10 +387,22 @@ export async function invalidate( shadowed.push(path) } } - // (a plan under many of those paths: its resolutions are asked once) + // only those resolutions are asked again, once per plan under many of + // those paths: the plan's others found files the new one can't take const seen = new Set() for (const path of shadowed) { - await revalidate(cache, path, (fp) => fp.kind === 'resolution', seen) + await revalidate( + cache, + path, + (fp) => { + if (fp.kind !== 'resolution') { + return false + } + const found = fingerprintPath(fp) + return found !== null && found !== change.path && shadows(found) + }, + seen, + ) } } } diff --git a/packages/router-utils/tests/pipeline.test.ts b/packages/router-utils/tests/pipeline.test.ts index e6c5ed5d00..970e795468 100644 --- a/packages/router-utils/tests/pipeline.test.ts +++ b/packages/router-utils/tests/pipeline.test.ts @@ -1,3 +1,4 @@ +import path from 'node:path' import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping' import { describe, expect, it } from 'vitest' import { compileModule, invalidate, revision } from '../src/compiler' @@ -404,6 +405,59 @@ describe('resolution for analysis', () => { '/app/helper.tsx', ]) }) + + // `./service` found `service/index.ts`, which `service.web.ts` may shadow; + // `./helper` found a file the new one can't take, and is not asked again: + // an answer that changed meanwhile without a file event (Rspack's + // resolver, under Yarn PnP, finds no package from a file in Yarn's global + // cache at the start of a compile) makes no plan stale. + // Source: release check, real installs F1 (an edit under a directory + // Tailwind's Rsbuild plugin watches broke Start's Rsbuild dev server). + it('a file that appears asks again only the resolutions it may take', async () => { + let helperAnswers = true + const files = { + '/app/page.tsx': dedent(` + import { createFileRoute } from 'toy-router' + import { make } from './service' + import { helper } from './helper' + export const Route = createFileRoute('/')({ + component: () => helper(make()), + }) + `), + '/app/service/index.ts': 'export const make = () => "index"\n', + '/app/helper.ts': 'export const helper = (x: unknown) => x\n', + } + const host = new MemoryHost({ + files, + resolve: (specifier, importer, all) => { + if (specifier === './helper' && !helperAnswers) { + return null + } + const joined = path.posix.join(path.posix.dirname(importer), specifier) + return ( + [`${joined}.ts`, `${joined}/index.ts`].find((c) => c in all) ?? null + ) + }, + }) + const planners: Array = [toySplitPlanner(), toySummaryPlanner()] + const first = await host.compile('/app/page.tsx', planners) + expect(first!.dependencies).toEqual([ + '/app/service/index.ts', + '/app/helper.ts', + ]) + helperAnswers = false + host.write('/app/service.web.ts', 'export const make = () => "web"\n') + host.resolveCalls.length = 0 + const added = await invalidate( + host.caches, + { path: '/app/service.web.ts', kind: 'add' }, + host, + ) + expect(added.dependents).toEqual([]) + expect(host.resolveCalls).toEqual([ + { specifier: './service', importer: '/app/page.tsx' }, + ]) + }) }) describe('slice gates: edges and policy', () => { diff --git a/packages/start-plugin-core/src/rsbuild/host-plugin.ts b/packages/start-plugin-core/src/rsbuild/host-plugin.ts index 7450b15ea7..425fe83a06 100644 --- a/packages/start-plugin-core/src/rsbuild/host-plugin.ts +++ b/packages/start-plugin-core/src/rsbuild/host-plugin.ts @@ -258,6 +258,14 @@ export function createStartHostPlugin(opts: StartHostPluginOptions): { /** The files of the last compilation (a modified file outside them is a created one: an `add`, which re-resolves * imports that failed to resolve before). */ let knownFiles: ReadonlySet | null = null + /** + * The directories the last compilation watched (`contextDependencies`: + * Tailwind CSS adds the ones it scans): Rspack reports such a directory + * as modified when anything below it changes, which creates no file of + * its name. A created file a resolution may take is reported itself (a + * missing dependency). + */ + let knownDirectories: ReadonlySet = new Set() let currentCompilation: Rspack.Compilation | null = null let reporterInstalled = false /** @@ -329,7 +337,11 @@ export function createStartHostPlugin(opts: StartHostPluginOptions): { session.forgetMisses() await session.invalidateFileEvents( [...(compiler.modifiedFiles ?? [])] - .filter((file) => !isKnown(file) || isPackageManifest(file)) + .filter( + (file) => + (!isKnown(file) && !knownDirectories.has(file)) || + isPackageManifest(file), + ) .map((file) => ({ file, kind: isPackageManifest(file) @@ -374,6 +386,9 @@ export function createStartHostPlugin(opts: StartHostPluginOptions): { session.compiledOnce = true const deps = stats.compilation.fileDependencies knownFiles = new Set(deps as Iterable) + knownDirectories = new Set( + stats.compilation.contextDependencies as Iterable, + ) if (session.start.opts.mode === 'dev') { session.retain(environment.name, knownFiles) } else if (!compiler.watchMode) { diff --git a/packages/start-plugin-core/tests/integration/rsbuild/dev-watched-directory.test.ts b/packages/start-plugin-core/tests/integration/rsbuild/dev-watched-directory.test.ts new file mode 100644 index 0000000000..a915ab1d29 --- /dev/null +++ b/packages/start-plugin-core/tests/integration/rsbuild/dev-watched-directory.test.ts @@ -0,0 +1,163 @@ +/** + * Start's Rsbuild dev server in an app whose CSS tooling watches the source + * directory as a whole: Tailwind CSS's PostCSS plugin reports the + * directories it scans (`dir-dependency`), and the CSS loader makes them + * context dependencies, so Rspack reports `src` as modified with every edit + * below it (a fresh `@tanstack/cli` Rsbuild app with Tailwind). That + * directory is no file created: an edit builds what it changes, and a file + * created below it still reaches the modules it shadows. + * Source: release check, real installs F1 (under Yarn PnP, the first route + * edit of such an app rebuilt a module of a package and broke every later + * compile). + */ +import path from 'node:path' +import { describe, expect, onTestFinished, test } from 'vitest' +import { openPage } from '@tanstack/compiler-test-utils/browser' +import { startRsbuildStartDevServer } from '../../rsbuild-dev-server' +import { rootDocument, routerFile } from '../start-compose-app' +import type { RsbuildPlugin, Rspack } from '@rsbuild/core' + +const timeout = 60_000 + +/** Has every compile watch the app's `src` directory, as Tailwind's PostCSS plugin does. */ +const watchSourceDirectory: RsbuildPlugin = { + name: 'watch-source-directory', + setup(api) { + const src = path.join(api.context.rootPath, 'src') + api.modifyRspackConfig((config) => { + config.plugins.push({ + apply(compiler: Rspack.Compiler) { + compiler.hooks.thisCompilation.tap( + 'watch-source-directory', + (compilation) => { + compilation.contextDependencies.add(src) + }, + ) + }, + }) + }) + }, +} + +const appFiles = { + 'harness/client-entry.ts': `import { createElement } from 'react' +import { hydrateRoot } from 'react-dom/client' +import { StartClient } from '@tanstack/react-start/client' +hydrateRoot(document, createElement(StartClient)) +`, + 'harness/server-entry.ts': `export { default } from '@tanstack/react-start/server-entry'\n`, + 'src/router.ts': routerFile, + 'src/routes/__root.tsx': rootDocument(), +} + +/** A server fn module whose handler returns `MARK_HANDLER_`. */ +const greetModule = (version: string) => + `import { createServerFn } from '@tanstack/react-start' +export const greet = createServerFn().handler(async () => 'MARK_HANDLER_${version}') +` + +/** The index route: a label, the last call's result and a counter (its state). */ +const indexRoute = ( + label: string, +) => `import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' +import { greet } from '../greet.functions' +export const Route = createFileRoute('/')({ component: Page }) +function Page() { + const [called, setCalled] = useState('') + const [count, setCount] = useState(0) + return ( +
+

${label}

+

called {called}

+ + +
+ ) +} +` + +describe('Rsbuild dev with HMR: an app that watches its source directory', () => { + test( + 'a route component edit applies in place and builds no module of a package, and a server fn edit reaches the next call', + async () => { + const server = await startRsbuildStartDevServer({ + hmr: true, + browser: true, + config: { + // Start serves the pages, not an HTML template + tools: { htmlPlugin: false }, + plugins: [watchSourceDirectory], + }, + files: { + ...appFiles, + 'src/greet.functions.ts': greetModule('V1'), + 'src/routes/index.tsx': indexRoute('MARK_LABEL_V1'), + }, + }) + expect(server.errors).toEqual([]) + const page = await openPage(server.url!, { + registerCleanup: onTestFinished, + }) + await page.waitForText('hydrated', { selector: '[data-testid=hydrated]' }) + await page.page.locator('[data-testid=count]').click() + await page.waitForText('count 1', { selector: '[data-testid=count]' }) + + await server.edit({ 'src/routes/index.tsx': indexRoute('MARK_LABEL_V2') }) + expect(server.errors).toEqual([]) + await page.waitForText('MARK_LABEL_V2', { + selector: '[data-testid=label]', + }) + // in place: the page kept its state + await page.waitForText('count 1', { selector: '[data-testid=count]' }) + // no module of a package is built again for it + expect(server.rebuilt.filter((file) => !file.startsWith('src/'))).toEqual( + [], + ) + + await server.edit({ 'src/greet.functions.ts': greetModule('V2') }) + expect(server.errors).toEqual([]) + await page.page.locator('[data-testid=call]').click() + await page.waitForText('called MARK_HANDLER_V2', { + selector: '[data-testid=called]', + }) + expect(page.loads()).toBe(1) + expect(page.errors).toEqual([]) + }, + timeout, + ) + + // Rspack reports the watched directory, and `src/lib.ts` itself (the + // resolution of `./lib` looked for it before `src/lib/index.ts`). + test( + 'a created file that shadows a resolution compiles the importer again', + async () => { + const server = await startRsbuildStartDevServer({ + compileTimeout: 20_000, + config: { plugins: [watchSourceDirectory] }, + files: { + 'src/lib/index.ts': `export const base = { + handler: (fn: () => Promise) => fn, +} +`, + 'src/a.ts': `import { base } from './lib' +export const a = base.handler(async () => 'MARK_A') +`, + 'src/entry.ts': `import { a } from './a'\nconsole.log(a)\n`, + }, + }) + const client = async () => + Object.values(await server.outputs('client')).join('\n') + expect(server.errors).toEqual([]) + expect(await client()).toContain('MARK_A') + await server.edit({ + 'src/lib.ts': `import { createServerFn } from '@tanstack/react-start' +export const base = createServerFn() +`, + }) + expect(server.errors).toEqual([]) + expect(await client()).not.toContain('MARK_A') + }, + timeout, + ) +})