diff --git a/.changeset/solid-split-chunk-newest-import.md b/.changeset/solid-split-chunk-newest-import.md new file mode 100644 index 0000000000..66b64517d3 --- /dev/null +++ b/.changeset/solid-split-chunk-newest-import.md @@ -0,0 +1,7 @@ +--- +'@tanstack/router-core': patch +'@tanstack/solid-router': patch +'@tanstack/router-plugin': patch +--- + +Solid route HMR on Rsbuild, Rspack and webpack (development only): a split chunk imported again answers its newest evaluation. An edit of a loader grouped with the route component (`codeSplittingOptions.defaultBehavior: [['component', 'loader']]`) now shows, as does a route module edit after a conditional component switched (`const Page = flag ? Wide : Narrow`, then `staleTime`). This is a temporary workaround of Rspack's lazy compilation (web-infra-dev/rspack#16594): a later `import()` of a module that accepts its own updates, as solid-refresh makes every Solid chunk, answers its first namespace. A component the chunk handed over is kept when solid-refresh patched it, so such edits remount nothing more. diff --git a/packages/compiler-test-utils/oracle/KNOWN-BUGS.md b/packages/compiler-test-utils/oracle/KNOWN-BUGS.md index 7f674672b9..09f4ef9453 100644 --- a/packages/compiler-test-utils/oracle/KNOWN-BUGS.md +++ b/packages/compiler-test-utils/oracle/KNOWN-BUGS.md @@ -55,13 +55,6 @@ code.test.ts`: "a root route's %s loads lazily". kept. SPEC J3.2. `router-plugin/tests/integration/route-hmr-browser-solid-identity.test.ts`: "a split component mounts once per save", "@refresh granular: a split component keeps its state when solid-refresh keeps it" (autoCodeSplitting: true). Fix: one mount per save; the Rsbuild rows of the same file stay green. -- **Rsbuild: an edit of a Solid split loader that shares its chunk with a component never shows** - (`codeSplittingOptions` grouping `loader` with a component): solid-refresh makes the chunk accept its own updates, - so Rspack's lazy-compilation proxy keeps answering the chunk's first module, and the route's refresh re-runs that - module's loader. The chunk hands its components to the route's lazy wrappers, not its loader. Found by design 7's - matrix (2026-11-12); main not measured. SPEC J3.3. - `router-plugin/tests/integration/route-hmr-browser-solid-identity-rsbuild.test.ts`: "a loader sharing the route - component chunk: every edit" (autoCodeSplitting: true). Fix: the edit shows. - **Rsbuild, split: after a rename or a removed component in a Solid route file, no later hot update reaches the page** until a reload. Upstream, solid-refresh (see "Upstream issues"); a plain Solid app with a `lazy()` import fails the same way, Vite does not. SPEC J3.3. @@ -600,6 +593,17 @@ Paths under `router-plugin/tests/` unless given. Solid chunk now hands its exports to the route's lazy wrappers. SPEC J3.3. `integration/route-hmr-browser-solid-identity-rsbuild.test.ts`: "a conditional behind a const" (autoCodeSplitting: true). +- **Rsbuild: a Solid split chunk imported again answered its first evaluation**: solid-refresh makes the chunk accept + its own updates, and Rspack's lazy-compilation proxy answers every later `import()` of such a module with its first + namespace (upstream, see "Upstream issues"). An edit of a loader grouped with a component never showed (main showed + an inline arrow loader only by accident: solid-refresh wrapped its capitalised `SplitLoader`; a loader function of + the file or a loader object was stale on main too), and a route module edit after a conditional component switched + (`const Page = flag ? Wide : Narrow`) brought the old component back (main: stale from the switch). A temporary + workaround makes the importer of a Solid split chunk answer the chunk's newest evaluation. SPEC J3.3. + `integration/route-hmr-browser-solid-identity-rsbuild.test.ts`: "a loader sharing the route component chunk", "a + loader function of the file sharing the route component chunk", "a loader in an object sharing the route component + chunk", "a conditional, then an option the route module keeps", "a grouped loader edited, then an option the route + module keeps" (autoCodeSplitting: true). - **A split chunk lost the route file's `@refresh` pragma**: solid-refresh never kept a split component's state under `@refresh granular` (`@refresh skip` and `reload` were lost the same way). SPEC J2.16. `integration/route-hmr-browser-solid-identity-rsbuild.test.ts`: "@refresh granular, an edit of the loader and of a @@ -928,29 +932,30 @@ Paths under `react-start-rsc/tests/integration/`. "Remove when" says when a harness change can go. -| Tool | Symptom | What the suite does | -| --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Rspack 2.2 (vendored watchpack 2.5.2) | a file removal that lands while a compile runs is lost (fixed in watchpack 2.6.0, webpack/watchpack#345) | Rsbuild tests delete or recreate one file per edit and settle before the next write (`start-plugin-core/tests/integration/importProtection/v2-edits*.test.ts`, `v2-hosts.ts`, `integration/rsbuild/dev-server.test.ts`). Remove when Rspack bundles watchpack ≥ 2.6. | -| Rspack 2.2.7–2.2.9 HMR runtime (webpack 5.110 has the same gap) | a hot update whose module gained imports that `splitChunks` moved to a new async chunk re-executes it before that chunk loads: `Cannot read properties of undefined (reading 'call')` | pinned (J3): `start-plugin-core/tests/integration/rsbuild/first-server-fn-import.test.ts`; rspack#11324/#11922 call it expected (a React Refresh reload the bare `TypeError` never triggers; still failing on 2.2.9, rspack#16288). Remove when Rspack loads an updated chunk's new siblings first. | -| Vite 8.3.4–8.3.7 module runner | a `full-reload` clears `evaluatedModules` while an import is evaluating; the import goes on in the new generation, sharing route modules with the requests after the reload | pinned (J3.3): `start-plugin-core/tests/integration/start-dev-ssr-reload-in-flight.test.ts`; vitejs/vite#24046. Remove when the runner's reload waits for the evaluations in flight (or keeps them in their generation). | -| Rspack 2.2 (vendored watchpack 2.5.2) | a file deleted during the watcher's first scan is never reported | the Rsbuild dev harness resolves once every compiler's watcher has scanned the app, and writes the initial files with past modification times (`compiler-test-utils/src/rsbuild-dev-server.ts`). This is what "the server is up" means; it may stay. | -| Vite 8 `experimental.bundledDev` | closing the server during its initial build leaves a rejection unhandled ("Failed to get bundle state"); no public API to await it (vitejs/vite#22991) | before `close()` the harness waits for the initial build, reading one Vite internal (`compiler-test-utils/src/dev-server.ts`). Remove when Vite handles the rejection. | -| Vite 8.3.4 dependency optimizer | keeps writing `node_modules/.vite/deps_temp_*` after `close()` resolved: removing the app fails with `ENOTEMPTY`, or a write into the removed app is an unhandled rejection | before `close()` the Vite dev harnesses wait until each environment's optimizer has scanned and no `deps*_temp_*` directory is left (`closeViteServer` in `compiler-test-utils/src/dev-server.ts`). Remove when Vite awaits its optimizer on close. | -| Vite 8.3.4 dependency optimizer | a late-discovered dependency changes a pre-bundled chunk's exports without changing its hash; the page fails with "does not provide an export named ''" | not seen since the harness apps use `tanstackStart()` (whose framework plugins pre-bundle React at start). No workaround. If seen, re-run the file alone. | -| solid-refresh 0.6.3 (Rspack HMR) | after a rename or a removed component, every later evaluation of the module finds the removed name in the registry it keeps in `hot.data` and calls `hot.invalidate()`; outside an update (an `import()`), Rspack's status stays `ready` and no later update applies | pinned (J3.3): `router-plugin/tests/integration/route-hmr-browser-solid-identity-rsbuild.test.ts`. Remove when solid-refresh forgets a removed name once it invalidated the module (or Rspack applies an update invalidated while idle). | -| Rolldown 1.2.13 | `var x = 1; for (var x of [2]) {}; export { x }` (also a for-in head or `var { x } = o`): an importer of `x` gets the constant `1` | pinned above (`.fails`) | -| webpack 5.110 | `export { K as "" } from './x'` (an empty export name) is read as `export *`: importers get `K`, not `""` | not pinned (the compiler's output is valid). Rows in `router-plugin/tests/integration/extracted-export-string-names.test.ts` skip webpack for that name. | -| Rollup 4.63.1 (Vite 7) | a `for (var x of …)` or `for (var x in …)` whose `x` another chunk imports renders `for (var x; of …)`: the build fails | not pinned (the compiler's output is valid). Same for a `var` declared once. | -| `@vitejs/plugin-react` 6.0.1 (Rolldown's Refresh wrapper) | the Refresh footer is appended without a line break: a module whose code ends in a line comment loses the footer's first line, and the next hot update throws `RefreshRuntime is not defined` | not pinned (the compiler's output is valid). Avoid ending emitted modules with a line comment. | -| `@vitejs/plugin-react` 6.0.1 (oxc Refresh) | a higher-order call with a cast around its argument (`memo(Page as any)`) gets no family (so in react-refresh/babel 0.18; SWC registers it): a hoisted route component remounts on edits | pinned (J3.2): `router-plugin/tests/integration/route-hmr-browser-identity.test.ts` "memo(Page as any)" (autoCodeSplitting: false). Remove when the transform sees through TypeScript wrappers, as SWC does (oxc-project/oxc#29281). | -| Vite resolver | `#` in a file path outside `node_modules` is read as a fragment; a query import of such a file does not resolve | not pinned (a plain Vite app fails the same way). | -| Vite `vite:oxc` | `.cts` with TypeScript syntax is not transformed (also with a query) | not pinned. | -| es-module-lexer 2.3.2 (Vite 8) | fails on `import def, { "kebab-name" as kebab } from "x"` | `importProtection/mock-shapes.test.ts` writes the two imports as separate declarations. | -| Node `autoSelectFamily` | a worker blocked for over 500 ms abandons the `::1` attempt to a `localhost` server and is refused at `127.0.0.1` | every harness server listens on `127.0.0.1` and its URL names that address. | -| Node 24/26 `fs.rmSync` | returns without an error and leaves files behind when another process removes part of the tree meanwhile | only the run's teardown removes the run's temp directory (`compiler-test-utils/src/run-directory.ts`). | -| Rspack 2.2, webpack 5 | unminified production output keeps reads of dropped bindings in dead code of modules no compiler touched | the dangling-name check covers only modules the compilers produced or changed (SPEC G8; `checkDanglingNames` in `compiler-test-utils/src/build-harness.ts`). | -| Chromium (Playwright, `--disable-dev-shm-usage`) | shared memory lives in files in `TMPDIR`; a full router-plugin `test:integration` holds up to about 2.2 GB; with little room, module requests fail (`net::ERR_INSUFFICIENT_RESOURCES`) | the browser helpers bound open pages (`runPageLimit`, `openPageLimit` in `compiler-test-utils/src/browser.ts`). Use a `TMPDIR` with room, or re-run the file alone. | -| unplugin 3.3 | webpack and Rspack loaders drop the plugin's source map | fixed (S4): unplugin was the former integration layer. | -| `@babel/generator` 7.29 | drops required parentheses | fixed (S3): Babel was the former printer. | -| babel-dead-code-elimination 1.0.12 | counts `typeof` type queries as references (pcattori/babel-dead-code-elimination#50) | fixed (S2): the former dead-code elimination. | -| babel-dead-code-elimination 1.0.12 | removes the const of a class and const cycle and keeps the class, whose static field then reads a deleted name (no class visitor) | fixed (S7): the former dead-code elimination. | +| Tool | Symptom | What the suite does | +| --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Rspack 2.2 (vendored watchpack 2.5.2) | a file removal that lands while a compile runs is lost (fixed in watchpack 2.6.0, webpack/watchpack#345) | Rsbuild tests delete or recreate one file per edit and settle before the next write (`start-plugin-core/tests/integration/importProtection/v2-edits*.test.ts`, `v2-hosts.ts`, `integration/rsbuild/dev-server.test.ts`). Remove when Rspack bundles watchpack ≥ 2.6. | +| Rspack 2.2.7–2.2.9 HMR runtime (webpack 5.110 has the same gap) | a hot update whose module gained imports that `splitChunks` moved to a new async chunk re-executes it before that chunk loads: `Cannot read properties of undefined (reading 'call')` | pinned (J3): `start-plugin-core/tests/integration/rsbuild/first-server-fn-import.test.ts`; rspack#11324/#11922 call it expected (a React Refresh reload the bare `TypeError` never triggers; still failing on 2.2.9, rspack#16288). Remove when Rspack loads an updated chunk's new siblings first. | +| Vite 8.3.4–8.3.7 module runner | a `full-reload` clears `evaluatedModules` while an import is evaluating; the import goes on in the new generation, sharing route modules with the requests after the reload | pinned (J3.3): `start-plugin-core/tests/integration/start-dev-ssr-reload-in-flight.test.ts`; vitejs/vite#24046. Remove when the runner's reload waits for the evaluations in flight (or keeps them in their generation). | +| Rspack 2.2 (vendored watchpack 2.5.2) | a file deleted during the watcher's first scan is never reported | the Rsbuild dev harness resolves once every compiler's watcher has scanned the app, and writes the initial files with past modification times (`compiler-test-utils/src/rsbuild-dev-server.ts`). This is what "the server is up" means; it may stay. | +| Vite 8 `experimental.bundledDev` | closing the server during its initial build leaves a rejection unhandled ("Failed to get bundle state"); no public API to await it (vitejs/vite#22991) | before `close()` the harness waits for the initial build, reading one Vite internal (`compiler-test-utils/src/dev-server.ts`). Remove when Vite handles the rejection. | +| Vite 8.3.4 dependency optimizer | keeps writing `node_modules/.vite/deps_temp_*` after `close()` resolved: removing the app fails with `ENOTEMPTY`, or a write into the removed app is an unhandled rejection | before `close()` the Vite dev harnesses wait until each environment's optimizer has scanned and no `deps*_temp_*` directory is left (`closeViteServer` in `compiler-test-utils/src/dev-server.ts`). Remove when Vite awaits its optimizer on close. | +| Vite 8.3.4 dependency optimizer | a late-discovered dependency changes a pre-bundled chunk's exports without changing its hash; the page fails with "does not provide an export named ''" | not seen since the harness apps use `tanstackStart()` (whose framework plugins pre-bundle React at start). No workaround. If seen, re-run the file alone. | +| solid-refresh 0.6.3 (Rspack HMR) | after a rename or a removed component, every later evaluation of the module finds the removed name in the registry it keeps in `hot.data` and calls `hot.invalidate()`; outside an update (an `import()`), Rspack's status stays `ready` and no later update applies | pinned (J3.3): `router-plugin/tests/integration/route-hmr-browser-solid-identity-rsbuild.test.ts`. Remove when solid-refresh forgets a removed name once it invalidated the module (or Rspack applies an update invalidated while idle). | +| Rolldown 1.2.13 | `var x = 1; for (var x of [2]) {}; export { x }` (also a for-in head or `var { x } = o`): an importer of `x` gets the constant `1` | pinned above (`.fails`) | +| Rspack 2.3.1 lazy compilation (Rsbuild's dev default) | a module that accepts its own updates and is loaded with `import()` evaluates again on each edit, but every later `import()` of it answers its first namespace (web-infra-dev/rspack#16594) | worked around, temporarily (J3.3): `solid-router/src/hmr-chunk-importer.ts` and the router plugin's `chunkImporterCall` (`router-plugin/src/planners/split.ts`) make a Solid split chunk's importer answer its newest evaluation. Remove when the issue is fixed: delete the module, the planner branch and their tests (`solid-router/tests/hmr-chunk-importer.test.ts`); the browser rows of `route-hmr-browser-solid-identity-rsbuild.test.ts` stay. | +| webpack 5.110 | `export { K as "" } from './x'` (an empty export name) is read as `export *`: importers get `K`, not `""` | not pinned (the compiler's output is valid). Rows in `router-plugin/tests/integration/extracted-export-string-names.test.ts` skip webpack for that name. | +| Rollup 4.63.1 (Vite 7) | a `for (var x of …)` or `for (var x in …)` whose `x` another chunk imports renders `for (var x; of …)`: the build fails | not pinned (the compiler's output is valid). Same for a `var` declared once. | +| `@vitejs/plugin-react` 6.0.1 (Rolldown's Refresh wrapper) | the Refresh footer is appended without a line break: a module whose code ends in a line comment loses the footer's first line, and the next hot update throws `RefreshRuntime is not defined` | not pinned (the compiler's output is valid). Avoid ending emitted modules with a line comment. | +| `@vitejs/plugin-react` 6.0.1 (oxc Refresh) | a higher-order call with a cast around its argument (`memo(Page as any)`) gets no family (so in react-refresh/babel 0.18; SWC registers it): a hoisted route component remounts on edits | pinned (J3.2): `router-plugin/tests/integration/route-hmr-browser-identity.test.ts` "memo(Page as any)" (autoCodeSplitting: false). Remove when the transform sees through TypeScript wrappers, as SWC does (oxc-project/oxc#29281). | +| Vite resolver | `#` in a file path outside `node_modules` is read as a fragment; a query import of such a file does not resolve | not pinned (a plain Vite app fails the same way). | +| Vite `vite:oxc` | `.cts` with TypeScript syntax is not transformed (also with a query) | not pinned. | +| es-module-lexer 2.3.2 (Vite 8) | fails on `import def, { "kebab-name" as kebab } from "x"` | `importProtection/mock-shapes.test.ts` writes the two imports as separate declarations. | +| Node `autoSelectFamily` | a worker blocked for over 500 ms abandons the `::1` attempt to a `localhost` server and is refused at `127.0.0.1` | every harness server listens on `127.0.0.1` and its URL names that address. | +| Node 24/26 `fs.rmSync` | returns without an error and leaves files behind when another process removes part of the tree meanwhile | only the run's teardown removes the run's temp directory (`compiler-test-utils/src/run-directory.ts`). | +| Rspack 2.2, webpack 5 | unminified production output keeps reads of dropped bindings in dead code of modules no compiler touched | the dangling-name check covers only modules the compilers produced or changed (SPEC G8; `checkDanglingNames` in `compiler-test-utils/src/build-harness.ts`). | +| Chromium (Playwright, `--disable-dev-shm-usage`) | shared memory lives in files in `TMPDIR`; a full router-plugin `test:integration` holds up to about 2.2 GB; with little room, module requests fail (`net::ERR_INSUFFICIENT_RESOURCES`) | the browser helpers bound open pages (`runPageLimit`, `openPageLimit` in `compiler-test-utils/src/browser.ts`). Use a `TMPDIR` with room, or re-run the file alone. | +| unplugin 3.3 | webpack and Rspack loaders drop the plugin's source map | fixed (S4): unplugin was the former integration layer. | +| `@babel/generator` 7.29 | drops required parentheses | fixed (S3): Babel was the former printer. | +| babel-dead-code-elimination 1.0.12 | counts `typeof` type queries as references (pcattori/babel-dead-code-elimination#50) | fixed (S2): the former dead-code elimination. | +| babel-dead-code-elimination 1.0.12 | removes the const of a class and const cycle and keeps the class, whose static field then reads a deleted name (no class visitor) | fixed (S7): the former dead-code elimination. | diff --git a/packages/router-core/src/hmr.ts b/packages/router-core/src/hmr.ts index b4c27f8558..76cf590f54 100644 --- a/packages/router-core/src/hmr.ts +++ b/packages/router-core/src/hmr.ts @@ -21,7 +21,11 @@ export interface RouteHmrMeta { * the new one is taken), or when the new one can be taken. Not a public API. */ export interface RouteHmrAdapter { - /** Split component: decided when the chunk re-imported after a route update resolves, from the loaded export. */ + /** + * Split component: decided when the chunk re-imported after a route update + * resolves, from the loaded export (a module the chunk handed over: + * `keepPatched`). + */ keep?: (next: any, held: any) => boolean /** * `held` and `next` are the same option of two evaluations of one module @@ -96,15 +100,16 @@ export interface LazyRouteComponentPort { * has loaded (or is loading), then, once the adapter's refresh settled * (`settled`), keeps the held component if `keep(loaded, held)` says so (the * framework's refresh runtime patches it in place) or swaps to the loaded - * one, and re-renders the wrapper either way (a failure it held is over). + * one, and re-renders the wrapper either way (a failure it held is over). A + * module its chunk handed over (`applyRouteChunkHmr`) evaluated again on its + * own: its framework's refresh patched it as it patches a route module, so + * `keepPatched` decides instead. * The newest import is the only one whose completion counts: an older one * that completes while a newer one is pending settles with the newer one. A * wrapper that never loaded only takes the new importer for its first load. - * `take` settles the same way with a module its chunk handed over (the chunk - * evaluated again on its own: its framework's refresh patched it as it - * patches a route module, so `keepPatched` decides), keeping the importer; - * a wrapper that holds nothing, or a module without its export, is left - * alone. + * `take` settles the same way with a module its chunk handed over, keeping + * the importer; a wrapper that holds nothing, or a module without its + * export, is left alone. * * Dev-only, called by the framework packages' `lazyRouteComponent` on the * client; not a public API. @@ -119,7 +124,6 @@ export function lazyRouteComponentHot( const settleWith = ( loading: Promise, name: string, - keep: RouteHmrAdapter['keep'], adapter: RouteHmrAdapter, ) => { const promise: Promise = loading.then( @@ -128,6 +132,7 @@ export function lazyRouteComponentHot( return port.pending() } const next = res[name] + const keep = handedOver.has(res) ? adapter.keepPatched : adapter.keep const take = () => { if (port.pending() !== promise) { return port.pending() @@ -171,18 +176,13 @@ export function lazyRouteComponentHot( if (!port.retarget(nextImporter, nextExportName)) { return } - settleWith(nextImporter(), currentExport, adapter.keep, adapter) + settleWith(nextImporter(), currentExport, adapter) }, take: (module, adapter) => { if (port.held() == null || !(currentExport in module)) { return } - settleWith( - Promise.resolve(module), - currentExport, - adapter.keepPatched, - adapter, - ) + settleWith(Promise.resolve(module), currentExport, adapter) }, } } @@ -221,6 +221,10 @@ const hotRoutes = new Map< // did (`applyRouteChunkHmr`). Bounded by the number of split chunks. const hotChunks = new Map>() +// The exports of every evaluation a split chunk handed over +// (`applyRouteChunkHmr`): the framework's refresh patched each of them. +const handedOver = new WeakSet() + /** * What the route HMR runtime uses of a webpack-style module's hot handle * (`import.meta.webpackHot`). Not a public API. @@ -671,6 +675,9 @@ export function applyRouteChunkHmr( if (isServer ?? typeof window === 'undefined') { return } + if (handOver) { + handedOver.add(handOver.exports) + } let chunks = hotChunks.get(routeId) if (!chunks) { chunks = new Set() diff --git a/packages/router-core/tests/lazy-route-component-hot.test.ts b/packages/router-core/tests/lazy-route-component-hot.test.ts index 0294d67587..484f97cd60 100644 --- a/packages/router-core/tests/lazy-route-component-hot.test.ts +++ b/packages/router-core/tests/lazy-route-component-hot.test.ts @@ -7,7 +7,7 @@ */ import { describe, expect, test, vi } from 'vitest' import { createControlledPromise } from '../src/utils' -import { lazyRouteComponentHot } from '../src/hmr' +import { applyRouteChunkHmr, lazyRouteComponentHot } from '../src/hmr' import type { RouteHmrAdapter } from '../src/hmr' type Module = Record @@ -55,6 +55,16 @@ function wrapper(held?: unknown, error?: unknown) { const swap: RouteHmrAdapter = {} const v = (label: string) => ({ label }) +/** `module`, handed over by an evaluation of its split chunk (`applyRouteChunkHmr`). */ +function handOver(module: T): T { + applyRouteChunkHmr('/handed', 'component', { + exports: module, + refresh: false, + adapter: swap, + }) + return module +} + describe('lazyRouteComponentHot', () => { test('a wrapper that never loaded only takes the new importer for its first load', () => { const { state, hot } = wrapper() @@ -299,17 +309,43 @@ describe('lazyRouteComponentHot', () => { const keepPatched = vi.fn(() => true) const keep = vi.fn(() => false) const handed = v('v2') - hot.take({ component: handed }, { keep, keepPatched }) + const module = handOver({ component: handed }) + hot.take(module, { keep, keepPatched }) expect(await state.pending).toBe(held) expect(keepPatched).toHaveBeenCalledWith(handed, held) expect(keep).not.toHaveBeenCalled() expect(state).toMatchObject({ comp: held, renders: 1, importer }) - hot.take({ component: handed }, swap) + hot.take(module, swap) expect(await state.pending).toBe(handed) expect(state).toMatchObject({ comp: handed, renders: 2, importer }) }) + test('an import answering a module its chunk handed over is kept or taken by keepPatched, any other by keep', async () => { + const held = v('v1') + const { state, hot } = wrapper(held) + const keepPatched = vi.fn(() => true) + const keep = vi.fn(() => false) + const handed = v('v2') + const module = handOver({ component: handed }) + hot.update(() => Promise.resolve(module), 'component', { + keep, + keepPatched, + }) + expect(await state.pending).toBe(held) + expect(keepPatched).toHaveBeenCalledWith(handed, held) + expect(keep).not.toHaveBeenCalled() + + const imported = v('v3') + hot.update(() => Promise.resolve({ component: imported }), 'component', { + keep, + keepPatched, + }) + expect(await state.pending).toBe(imported) + expect(keep).toHaveBeenCalledWith(imported, held) + expect(keepPatched).toHaveBeenCalledOnce() + }) + test('take: a wrapper that holds nothing, or a module without its export, is left alone', async () => { const { state, hot } = wrapper() hot.take({ component: v('v2') }, swap) diff --git a/packages/router-plugin/src/planners/split.ts b/packages/router-plugin/src/planners/split.ts index c21483b626..2705f7355a 100644 --- a/packages/router-plugin/src/planners/split.ts +++ b/packages/router-plugin/src/planners/split.ts @@ -16,7 +16,7 @@ import { sameFileSpecifier, stringLiteral, } from '@tanstack/router-utils/compiler' -import { identifierSymbol, pascal } from './route' +import { identifierSymbol, pascal, routerRouteId } from './route' import { COMPONENT_KEYS } from './decisions' import { ROUTER_PLANNER } from './config' import type { SplitDecision } from './decisions' @@ -110,6 +110,9 @@ export function planSplit(ctx: PlanContext, round: RouterRound): void { return sym } + // TEMPORARY WORKAROUND of web-infra-dev/rspack#16594: `chunkImporterCall` + const importerCall = chunkImporterCall(ctx, round, helperImports) + // each importer right before the statement holding its group's first // placeholder (the options object, or an option's object declared by // itself): no effects between them, so a minifier inlines it there @@ -150,9 +153,13 @@ export function planSplit(ctx: PlanContext, round: RouterRound): void { `tsrImport${d.groupKey.split('~').map(pascal).join('')}`, ) const spec = sameFileSpecifier(derivedId) + const [open, close] = importerCall(d.groupKey) ctx.rewrites.addGenerated({ body: [ - { k: 'text', parts: [`const ${importer.name} = () => import(`] }, + { + k: 'text', + parts: [`const ${importer.name} = `, ...open, '() => import('], + }, { k: 'spec', specifier: spec, @@ -160,7 +167,7 @@ export function planSplit(ctx: PlanContext, round: RouterRound): void { provenance: { origin: 'runtime' }, form: 'dynamic', }, - { k: 'text', parts: [')\n'] }, + { k: 'text', parts: [`)${close}\n`] }, ], declares: [importer.sym], effectful: false, @@ -323,3 +330,47 @@ export function planSplit(ctx: PlanContext, round: RouterRound): void { }) } } + +/** + * TEMPORARY WORKAROUND of Rspack's lazy compilation, + * https://github.com/web-infra-dev/rspack/issues/16594 (the reason and the + * scope: `@tanstack/solid-router`'s `src/hmr-chunk-importer.ts`; remove with + * it once the issue is fixed). Solid, development on the + * client, webpack-style hosts: each group's importer is wrapped, + * `__tsrChunkImporter(, , () => import(…))`, to answer the + * chunk's newest evaluation. Otherwise the importer stays as it is. + * Returns what opens and closes the wrap around a group's importer. + */ +function chunkImporterCall( + ctx: PlanContext, + round: RouterRound, + helperImports: Array, +): (groupKey: string) => [open: Array, close: string] { + const { cfg, route } = round + if (!cfg.hmr || cfg.hmr.style === 'vite' || cfg.framework !== 'solid') { + return () => [[], ''] + } + let sym: SymbolId | null = null + return (groupKey) => { + if (sym === null) { + sym = ctx.names.alloc('tsrChunkImporter').sym + const specifier = `${route.routerPackage}/hmr` + helperImports.push({ + names: [{ imported: '__tsrChunkImporter', local: sym }], + spec: { + k: 'spec', + specifier, + edgeKey: ctx.edgeKey(specifier, 'static', 'runtime'), + provenance: { origin: 'runtime' }, + }, + }) + } + return [ + [ + { sym, ctx: 'callee' }, + `(${stringLiteral(routerRouteId(route.routeId), '"')}, ${stringLiteral(groupKey, '"')}, `, + ], + ')', + ] + } +} diff --git a/packages/router-plugin/tests/integration/route-hmr-browser-solid-identity-cases.ts b/packages/router-plugin/tests/integration/route-hmr-browser-solid-identity-cases.ts index f2039e2dd8..e44ea4f1d9 100644 --- a/packages/router-plugin/tests/integration/route-hmr-browser-solid-identity-cases.ts +++ b/packages/router-plugin/tests/integration/route-hmr-browser-solid-identity-cases.ts @@ -200,6 +200,135 @@ const granularChunkRow: Row = { })), } +/** A route like `pureRoute` with a loader grouped with the component, `staleTime: `. */ +const groupedRoute = ( + loader: (text: string) => { decls: string; option: string }, + v: number, + staleTime: number, + pragma = '', +) => { + const { decls, option } = loader(JSON.stringify(dataText(v))) + return `${pragma}${head}${signal}import { Data } from '../layouts/data' +${decls}function Page() ${body('')} +export const Route = createFileRoute('/')({ component: Page, ${option}, staleTime: ${staleTime} }) +` +} + +/** `const Page = flag ? Wide : Narrow`, the route with `staleTime: `. */ +const conditionalRoute = (flag: boolean, staleTime: number) => + route( + `const flag = ${flag} +function Wide() { + return

wide layout

+} +function Narrow() { + return

narrow layout

+} +const Page = flag ? Wide : Narrow`, + `component: Page, staleTime: ${staleTime}`, + ) + +const grouped: Partial = { + codeSplittingOptions: { defaultBehavior: [['component', 'loader']] }, +} + +// Bug: solid-refresh makes a chunk holding components accept its own +// updates, and Rspack's lazy-compilation proxy then answers every later +// `import()` of the chunk with its first module: the route's refresh re-ran +// the loader of that module (main showed the inline arrow only by accident: +// solid-refresh wrapped its capitalised `SplitLoader` in a proxy). +// Impact: an edit of a loader grouped with a component never showed on +// Rsbuild (the component's own edits did: the chunk hands them over). +const groupedLoaderRows: Array = ( + [ + ['', (text: string) => ({ decls: '', option: `loader: () => ${text}` })], + [ + ' function of the file', + (text: string) => ({ + decls: `function loadData() {\n return ${text}\n}\n`, + option: 'loader: loadData', + }), + ], + [ + ' in an object', + (text: string) => ({ + decls: '', + option: `loader: { handler: () => ${text}, staleReloadMode: 'blocking' }`, + }), + ], + ] as const +).map(([shape, loader]) => ({ + name: `a loader${shape} sharing the route component chunk`, + counter: true, + pluginOptions: grouped, + files: { + 'layouts/data.tsx': dataModule, + 'routes/index.tsx': groupedRoute(loader, 1, 1), + }, + ready: dataText(1), + edits: [2, 3].map((v) => ({ + files: { 'routes/index.tsx': groupedRoute(loader, v, 1) }, + shows: dataText(v), + mounts: mounts(1, twice, 1), + })), +})) + +/** An inline arrow loader, as in `groupedLoaderRows`. */ +const arrowLoader = (text: string) => ({ + decls: '', + option: `loader: () => ${text}`, +}) + +/** + * The route module evaluates again with its split chunk unchanged: the + * route's lazy wrappers import the chunk again (Rspack's lazy-compilation + * proxy answers its first module; see `groupedLoaderRows`). + */ +const keptOptionRows: Array = [ + { + name: 'a conditional, then an option the route module keeps', + counter: false, + files: { 'routes/index.tsx': conditionalRoute(true, 1) }, + ready: 'wide layout', + edits: [ + { + files: { 'routes/index.tsx': conditionalRoute(false, 1) }, + shows: 'narrow layout', + }, + { + files: { 'routes/index.tsx': conditionalRoute(false, 2) }, + shows: 'narrow layout', + }, + { + files: { 'routes/index.tsx': conditionalRoute(false, 3) }, + shows: 'narrow layout', + }, + ], + }, + { + name: 'a grouped loader edited, then an option the route module keeps', + counter: true, + pluginOptions: grouped, + files: { + 'layouts/data.tsx': dataModule, + 'routes/index.tsx': groupedRoute(arrowLoader, 1, 1), + }, + ready: dataText(1), + edits: [ + { + files: { 'routes/index.tsx': groupedRoute(arrowLoader, 2, 1) }, + shows: dataText(2), + mounts: mounts(1, twice, 1), + }, + ...[2, 3].map((staleTime) => ({ + files: { 'routes/index.tsx': groupedRoute(arrowLoader, 2, staleTime) }, + shows: dataText(2), + mounts: mounts(1, twice, 0), + })), + ], + }, +] + export const rows: Array = [ versions( 'a function declaration', @@ -246,29 +375,7 @@ export const rows: Array = [ })), }, granularChunkRow, - // Bug: solid-refresh makes a chunk holding components accept its own - // updates, so Rspack's lazy-compilation proxy keeps answering the chunk's - // first module: the route's refresh re-runs the loader of that module. - // Impact: an edit of a loader grouped with a component never shows on - // Rsbuild (the component's own edits do: the chunk hands them over). - { - name: 'a loader sharing the route component chunk', - counter: true, - pluginOptions: { - codeSplittingOptions: { defaultBehavior: [['component', 'loader']] }, - }, - files: { - 'layouts/data.tsx': dataModule, - 'routes/index.tsx': pureRoute('')(1), - }, - ready: dataText(1), - edits: [2, 3].map((v) => ({ - files: { 'routes/index.tsx': pureRoute('')(v) }, - shows: dataText(v), - })), - pinnedFrom: ({ bundler, split }) => - bundler === 'rsbuild' && split ? 0 : undefined, - }, + ...groupedLoaderRows, versions( '@refresh granular, a body edit', (v) => @@ -303,6 +410,7 @@ const Page = flag ? Wide : Narrow`, {}, false, ), + ...keptOptionRows, versions( "a factory's result", (v) => diff --git a/packages/solid-router/src/hmr-chunk-importer.ts b/packages/solid-router/src/hmr-chunk-importer.ts new file mode 100644 index 0000000000..6feba8fed7 --- /dev/null +++ b/packages/solid-router/src/hmr-chunk-importer.ts @@ -0,0 +1,67 @@ +/** + * TEMPORARY WORKAROUND of Rspack's lazy compilation, upstream: + * https://github.com/web-infra-dev/rspack/issues/16594 (repro: + * https://github.com/Sheraff/rspack-lazy-self-accept-import). Remove this + * module, its uses in `hmr.ts`, the router plugin's `chunkImporterCall` + * (planners/split.ts) and their tests once the issue is fixed. + * + * Reason: with lazy compilation on (Rsbuild's dev default), a module that + * accepts its own updates and is loaded with `import()` evaluates again on + * each edit, but every later `import()` of it keeps resolving to its first + * namespace. solid-refresh makes every Solid split chunk accept its own + * updates, so a split chunk imported again (a loader the route's refresh + * re-runs, a lazy wrapper re-importing after a route update) would serve its + * first evaluation's code. + * + * Scope: Solid, webpack-style hosts (Rsbuild, Rspack, webpack), development + * on the client. Each evaluation of a split chunk hands its exports over + * (`__tsrRouteChunkHmr`); the importer of the chunk's group, wrapped by the + * compiler (`__tsrChunkImporter`), answers the newest of them once its + * import settled. + */ +import { isServer } from '@tanstack/router-core/isServer' + +// Per route id and split chunk, the exports of the chunk's newest +// evaluation. Bounded by the number of split chunks; a route id the router +// no longer holds is forgotten (`forgetChunkExports`). +const newest = new Map>>() + +/** Records one evaluation of a split chunk (its exports). */ +export function recordChunkExports( + routeId: string, + chunk: string, + exports: Record, +): void { + if (process.env.NODE_ENV !== 'production') { + if (isServer ?? typeof window === 'undefined') { + return + } + let chunks = newest.get(routeId) + if (!chunks) { + chunks = new Map() + newest.set(routeId, chunks) + } + chunks.set(chunk, exports) + } +} + +/** Forgets the chunks of a route id the router no longer holds. */ +export function forgetChunkExports(routeId: string): void { + newest.delete(routeId) +} + +/** + * The importer of a split chunk's group: runs `importer`, then answers the + * exports of the chunk's newest evaluation (none recorded: what the import + * answered). + * + * Called only by compiler output; not a public API. + */ +export function __tsrChunkImporter( + routeId: string, + chunk: string, + importer: () => Promise, +): () => Promise { + return () => + importer().then((module) => newest.get(routeId)?.get(chunk) ?? module) +} diff --git a/packages/solid-router/src/hmr.ts b/packages/solid-router/src/hmr.ts index d1da591d61..37203fc086 100644 --- a/packages/solid-router/src/hmr.ts +++ b/packages/solid-router/src/hmr.ts @@ -3,6 +3,8 @@ import { applyRouteChunkHmr, applyRouteHmr, } from '@tanstack/router-core/hmr' +// TEMPORARY WORKAROUND of web-infra-dev/rspack#16594: see the module +import { forgetChunkExports, recordChunkExports } from './hmr-chunk-importer' import type { AnyRoute } from '@tanstack/router-core' import type { KeptReaderHot, @@ -37,6 +39,7 @@ const adapter: RouteHmrAdapter = { keepPatched: (next, held) => refreshSource(held) !== undefined && refreshSource(held) === refreshSource(next), + retire: forgetChunkExports, } /** @@ -72,6 +75,7 @@ export function __tsrRouteChunkHmr( refresh: boolean, ): void { if (process.env.NODE_ENV !== 'production') { + recordChunkExports(routeId, chunk, exports) applyRouteChunkHmr(routeId, chunk, { exports, refresh, adapter }) } } @@ -88,3 +92,5 @@ export function __tsrKeptReaderHmr(routeId: string, hot: KeptReaderHot): void { applyKeptReaderHmr(routeId, hot) } } + +export { __tsrChunkImporter } from './hmr-chunk-importer' diff --git a/packages/solid-router/tests/hmr-chunk-importer.test.ts b/packages/solid-router/tests/hmr-chunk-importer.test.ts new file mode 100644 index 0000000000..8e25eb6196 --- /dev/null +++ b/packages/solid-router/tests/hmr-chunk-importer.test.ts @@ -0,0 +1,45 @@ +/** + * The temporary workaround of Rspack's lazy compilation (`hmr-chunk-importer.ts`): + * the importer of a split chunk answers the chunk's newest evaluation. That + * an edit reaches a real page through it: router-plugin + * `integration/route-hmr-browser-solid-identity-rsbuild.test.ts`. + */ +import { describe, expect, test } from 'vitest' +import { __tsrChunkImporter, __tsrRouteChunkHmr } from '../src/hmr' + +describe('__tsrChunkImporter (dev-only, webpack-style split chunks)', () => { + test('answers the exports of the newest evaluation the chunk handed over', async () => { + const first = { component: 'v1' } + let evaluated = false + // the chunk evaluates on its first import; every import answers that + // first evaluation (Rspack's lazy compilation) + const importer = __tsrChunkImporter('/newest', 'component~loader', () => { + if (!evaluated) { + evaluated = true + __tsrRouteChunkHmr('/newest', 'component~loader', first, true) + } + return Promise.resolve(first) + }) + expect(await importer()).toBe(first) + const second = { component: 'v2' } + __tsrRouteChunkHmr('/newest', 'component~loader', second, true) + expect(await importer()).toBe(second) + // another chunk of the route, another route's chunk of the same group + __tsrRouteChunkHmr('/newest', 'component', { component: 'other' }, false) + __tsrRouteChunkHmr('/other', 'component~loader', { component: 'x' }, true) + expect(await importer()).toBe(second) + }) + + test("a chunk that handed nothing over: the import's own answer; a failed import fails", async () => { + const module = { component: 'v1' } + expect( + await __tsrChunkImporter('/none', 'component', () => + Promise.resolve(module), + )(), + ).toBe(module) + const error = new Error('boom') + await expect( + __tsrChunkImporter('/none', 'component', () => Promise.reject(error))(), + ).rejects.toBe(error) + }) +})