diff --git a/.changeset/bundler-peer-floors.md b/.changeset/bundler-peer-floors.md new file mode 100644 index 00000000000..2d6e7028d7c --- /dev/null +++ b/.changeset/bundler-peer-floors.md @@ -0,0 +1,9 @@ +--- +'@tanstack/start-plugin-core': minor +'@tanstack/react-start': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +'@tanstack/react-start-rsc': minor +--- + +Raise Start's bundler peer ranges to the lowest versions Start's test suites pass on: `vite` `>=8.1.0` (8.0.x fails Start's dev and build suites), `@rsbuild/core` `^2.2.13`, the first Rsbuild that requires Rspack 2.2.9, and `@rspack/core` `>=2.2.9` for `@tanstack/react-start-rsc`. Earlier Rspack 2 releases leave dev builds stuck after a rebuild, fail RSC builds, and can report a stale client build after a server component's CSS edit, so the page keeps the old styles (web-infra-dev/rspack#15865). The router plugin's ranges are unchanged: it still supports Rsbuild 1. diff --git a/.changeset/chokidar-6-node-22-22.md b/.changeset/chokidar-6-node-22-22.md new file mode 100644 index 00000000000..b5041794920 --- /dev/null +++ b/.changeset/chokidar-6-node-22-22.md @@ -0,0 +1,18 @@ +--- +'@tanstack/router-cli': minor +'@tanstack/router-generator': minor +'@tanstack/router-plugin': minor +'@tanstack/router-vite-plugin': minor +'@tanstack/start-plugin-core': minor +'@tanstack/react-start': minor +'@tanstack/react-start-rsc': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +--- + +Require Node `>=22.22.0`. Before this, `@tanstack/router-cli`, `@tanstack/router-generator` and `@tanstack/router-plugin` required `^20.19.0 || >=22.12.0`, `@tanstack/router-vite-plugin` `>=20.19`, and the Start packages `>=22.12.0`. The route generator and the CLI now depend on chokidar 6, which requires Node 22.22. Node versions below 22.22.0 are no longer supported, and Yarn 1 refuses to install these packages on them. + +chokidar 6 fixes two cases where the route generator's file watcher could miss changes. That watcher runs under `tsr watch`, Rspack and webpack watch mode, Rsbuild dev and `vite build --watch`, but not Vite dev. Both were tested on Linux: + +- A route file saved again within 50 ms of the previous save, for example by a format-on-save or a script, now reaches the route tree. Before, the route could keep the first save's content. A route file that is a symlink can still miss the second save. +- A routes directory that is deleted and created again, for example by a branch switch, is watched again. Before, route changes could stop reaching the route tree until the watcher was restarted. diff --git a/.changeset/client-only-children-prop.md b/.changeset/client-only-children-prop.md new file mode 100644 index 00000000000..83ec9100b11 --- /dev/null +++ b/.changeset/client-only-children-prop.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +`` with an explicit `children` prop (``) now renders only its fallback on the server, like children written between the tags: the server no longer runs or imports the children. diff --git a/.changeset/compiler-performance.md b/.changeset/compiler-performance.md new file mode 100644 index 00000000000..a646d10607e --- /dev/null +++ b/.changeset/compiler-performance.md @@ -0,0 +1,13 @@ +--- +'@tanstack/router-plugin': patch +'@tanstack/start-plugin-core': patch +'@tanstack/router-generator': patch +'@tanstack/router-utils': patch +--- + +Faster builds and dev servers. On 333- and 1,485-route React and Solid apps, builds are 2.2–4.8× faster and dev cold start is 2.2–4.9× faster; Start builds end with 3–11× less heap. + +- Production builds release an environment's compiler state as soon as that environment is built, so a build of several environments (client, SSR, then a server or RSC environment) no longer grows its heap with each one (#8794). +- A long-running dev server or `tsr watch` keeps a digest of each route file instead of its text, and an edit that leaves the route tree unchanged no longer goes over every route file. +- On Vite, dependency modules (`node_modules`) no longer pass through the router plugin's transform: Vite and Rolldown leave them out natively, as the webpack and Rspack loader rule does. A build no longer hands every dependency's source to the plugin to leave it unchanged (LibrePhotos: 9,763 of 10,950 calls, for 107 route files), which lowers build peak memory. +- On Rsbuild, Start's client manifest (route preloads and stylesheets), computed after every client compilation, no longer reads the module graph of the entry chunk and stops reading a chunk's modules once it has found every chunk it can import: 3–4× faster per compilation. In dev, an edit shows 37–40% sooner on a 1,485-route app (215–268 ms) and 27–35% sooner on a 338-route app. diff --git a/.changeset/compiler-yuku.md b/.changeset/compiler-yuku.md new file mode 100644 index 00000000000..933c704c96c --- /dev/null +++ b/.changeset/compiler-yuku.md @@ -0,0 +1,23 @@ +--- +'@tanstack/router-utils': minor +'@tanstack/router-generator': minor +'@tanstack/router-plugin': minor +'@tanstack/router-core': minor +'@tanstack/start-plugin-core': minor +'@tanstack/react-start-rsc': minor +--- + +The build-time compilers run on one compiler core built on [Yuku](https://github.com/yuku-toolchain/yuku) instead of Babel: route code splitting and route HMR in the router plugin, Start's server functions, environment separation, ``, RSC CSS and import protection, and the route generator. Each module is compiled once per environment from its original source, with exact source maps. + +**Dependencies.** `@babel/*`, `babel-dead-code-elimination`, `ansis` and `diff` are no longer dependencies, and the router plugin no longer depends on `chokidar` directly (the route generator brings it). `@babel/core` no longer comes with the router plugin or Start: if your app runs Babel itself (for example for the React Compiler), add `@babel/core` to your own `devDependencies`. + +**New entries:** `@tanstack/router-utils/compiler` (the compiler core), `@tanstack/router-core/tooling` (the router-core helpers the plugins load instead of the router runtime) and `@tanstack/router-plugin/planners` (the route planners TanStack Start uses). + +**Removed:** + +- `@tanstack/router-utils`: the Babel helpers (`parseAst`, `generateFromAst`, `deadCodeElimination`, `findReferencedIdentifiers`, `stripTypeExports` and the binding helpers of `compiler-helpers`), `logDiff`, `createIdentifier` and `decodeIdentifier`. +- Start's experimental, Babel-typed `compilerTransforms` and `serverFnProviderModuleDirectives` options and the `StartCompilerPlugin`, `StartCompilerImportTransform`, `StartCompilerTransformContext` and `StartCompilerTransformCandidate` types. RSC integrations pass `rsc: { loadCssExpression, providerDirective }` instead. +- `@tanstack/react-start-rsc/plugin/rscCssTransform`: RSC CSS injection runs in Start's compiler. +- `ssrIsProvider` of `TanStackStartCoreOptions`: the Vite plugin derives it from `providerEnvironmentName`, the Rsbuild plugin from `rsc`. + +**Router plugin context:** a context passed to the router plugins must come from `createRouterPluginContext()` (`@tanstack/router-plugin/context`), imported in the same module format (ESM or CJS) as the plugins. A hand-built `{ routesByFile: new Map() }`, or a context from the other module format, throws when the plugin is created, with an error naming the factory. diff --git a/.changeset/dead-code-removal.md b/.changeset/dead-code-removal.md new file mode 100644 index 00000000000..e19651a47fb --- /dev/null +++ b/.changeset/dead-code-removal.md @@ -0,0 +1,13 @@ +--- +'@tanstack/router-utils': minor +'@tanstack/start-plugin-core': patch +'@tanstack/router-plugin': patch +--- + +Dead-code removal is one rule at every level of a module: what only removed code used (a server fn handler on the client, a `createServerOnlyFn` body, a split route option, a type the client erases) leaves with it, from a function's locals, a destructuring pattern, a namespace's members and the top level alike. Code that stays keeps its behaviour, but for the changes listed last. + +- **Server code no longer reaches the client through:** a parameter default only server code reads (`make(db = getServerDb())` becomes `make(db = void 0)` on the client; literal defaults stay, `length` doesn't change); a sibling of a destructuring pattern nobody reads (`const { unused, secret } = getServerObj()`); a pattern default beside a rest element; a type alias, interface, namespace of types or `declare` that only removed code names, also through `import A = N.M` (a chain of aliases of any length), `export type { X }` and a reopened namespace's other block. +- **Registrations no longer disappear:** a value and a type of one name are two uses (`const Shape = register(); type Shape = …`), so a type only removed code names doesn't take a value of its name with it; a namespace of types beside a class, `enum` or `const` doesn't take the value either. +- **Code that throws keeps throwing:** a declaration that reads itself while it is initialised (`const { a = a } = o`, `const x = (() => x)()`) stays. +- **A type never keeps a value:** a declaration only types name (an annotation or a cast in code that runs, a type alias, `typeof`, an overload signature, an abstract or `declare` member) leaves with its initializer, client and server alike, so a call that only set it up no longer runs, and a class only types name is removed with its static blocks. An import only the types of code that stays name, directly, through type aliases or through a `declare`, is the host's (`verbatimModuleSyntax` keeps it), while an exported type (`export type`, `export interface`, `export type { X }`) still takes what only it names; a factory a classic JSX pragma names (`@jsx h`, `@jsxFrag`) is a read where JSX is; a module with decorators, or with a `React` of its own, keeps what types name, as before; a `declare` or a type alias nobody names or exports keeps what it names. +- **What changes on the client, by design:** a removed definition takes its own evaluation with it (a getter of a removed name isn't read, a removed default's call doesn't run); a pattern that stays drops its dead positions, so a `null` there no longer throws on the client; a name read only through a direct `eval` can be removed. The limits and their workarounds are listed in the compiler's known bugs. diff --git a/.changeset/dev-servers.md b/.changeset/dev-servers.md new file mode 100644 index 00000000000..c6f79c908a8 --- /dev/null +++ b/.changeset/dev-servers.md @@ -0,0 +1,11 @@ +--- +'@tanstack/router-utils': patch +'@tanstack/router-plugin': patch +'@tanstack/start-plugin-core': patch +--- + +Dev servers: + +- Vite: a module that imports a file that doesn't exist yet loads it once the file is created; it kept failing until a restart. +- A Vite dev server without HMR (`server.hmr: false`, as Vitest runs one) tells Start's compiler about file changes: a module whose import became (or stopped being) a server function builder kept its old compile, with the handler's code in the client module, until a restart. +- Vite: deleting a nested `package.json` whose `imports` or `exports` a module resolved through rebuilds that module in the client and in SSR. When the parent package's mapping pointed the import at a server function builder (or away from one), the old compile stayed until a restart. diff --git a/.changeset/devtool-namespace-hash-template.md b/.changeset/devtool-namespace-hash-template.md new file mode 100644 index 00000000000..8a2bfdfe046 --- /dev/null +++ b/.changeset/devtool-namespace-hash-template.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-utils': patch +--- + +webpack and Rspack development builds whose `output.devtoolNamespace` holds a hash template (`app-[fullhash:8]`) keep the route file's text in the maps of split routes. diff --git a/.changeset/diagnostics.md b/.changeset/diagnostics.md new file mode 100644 index 00000000000..c56f27933d8 --- /dev/null +++ b/.changeset/diagnostics.md @@ -0,0 +1,28 @@ +--- +'@tanstack/router-utils': patch +'@tanstack/router-plugin': patch +'@tanstack/router-generator': patch +'@tanstack/start-plugin-core': patch +'@tanstack/react-start-rsc': patch +--- + +Compiler and route generator messages: + +- Files are named relative to the project root, with one position (line and column, from 1) and a `[tanstack-router]` or `[tanstack-start]` prefix, on every host. On Rsbuild, Rspack and webpack the position is the compilation's own location, so the terminal and the error overlay point at it (`File: ./src/fns.ts:3:28`, `WARNING in ./src/routes/index.tsx 2:22`) instead of `:1:1`. +- Invalid `codeSplitGroupings` fail the module at the value, naming the option. Invalid `codeSplittingOptions` fail with one readable error naming each option instead of a raw schema dump. +- Start's refusals say what to write instead, at the right position: a refused server function names its position, or the local it reads, with the fix (`.validator()` and `{ data }`); a builder kept in an object or assigned after its declaration gets the documented fix. Refusals in a Vue single-file component are reported at the SFC's line and column, in builds and on the dev server, on Vite and Rsbuild. +- The client stubs of the RSC helpers no longer recommend a route loader, and their explanation is development-only. +- A plugin that gives a route file different text under different module ids gets a warning. +- Internal checks: a client build fails with an internal compiler error, naming the file and the position, if a client module would hold server code (a server function's handler or validator, a middleware's or an isomorphic function's server implementation, a `createServerOnlyFn` body, a route option `deleteNodes` lists), or if an output would copy part of a module without a change the compiler planned there. These mean a compiler bug: please report them. +- A warning about how a module is written is for whoever can edit it: an installed package's module (`node_modules`) no longer gets advice for its author (a middleware factory's parameter read in `.server()`, an exported or `this`-using route option, a server compile's parse failure), and an error in one names the package to update or report. Warnings that server code reaches the client, import protection and the package warnings stay. +- Vite dev: the warning about a package that uses Start names the package and its manifest, not Vite's pre-bundle (`node_modules/.vite`), and gives a package that declares Start but that the app does not list the right remedy. In a pre-bundle holding several packages, each package a Start call is in gets its own warning (a kit that only imports the router gets none), wherever the app keeps Vite's `cacheDir`. A pre-bundle is installed code there too: no advice for its author, and its errors name the package; a workspace package the app pre-bundles keeps its author's advice. A pre-bundle another plugin edits before Start's transform names no package. +- `start-server-param` says what the browser can see and where secrets go, at the parameter: "Only server code reads `descriptor`. Arguments at calls included in client code can be visible to the browser. Public labels are fine. Read secrets inside `.server()`." +- A route option whose value the route file exports is reported at the export (the declaration of the first one listed), with how to split it: "`Page` stays in the route module because src/routes/x.tsx exports it. To split it, remove its export, or move it to another module and import it here." +- A route the compiler does not recognise (a wrapped route call, …) is reported once in a Start app, and says only what applies: a root route is not called not code-split, and a wrapped route a build does nothing to (a root or lazy route file without Start) is not reported. In a Start app, every router warning comes from the client's compile of the file. +- A spread of route options is reported as what it may hold: "If the spread holds `ssr`, `server` or `headers`, they stay in client code". +- A route option whose value is a server function written in place is no longer reported as not code-split: the client splits it (only the server's module keeps it). +- Hydrate's refusals of `this`, `super`, `new.target`, `await`, `yield` and a private name of the enclosing class point at the use, not the `. If the page loaded before the server changed, reload it." on every host (Vite dev said "Invalid server function ID"); the import-protection marker conflict names the first marker as `src/x.ts:1:8`; the generator's missing root route names the file to add. +- The RSC client's `` and `RscNodeRenderer` errors are tagged `[tanstack-start]` in development and compact in production. diff --git a/.changeset/hydrate.md b/.changeset/hydrate.md new file mode 100644 index 00000000000..dac2443ada5 --- /dev/null +++ b/.changeset/hydrate.md @@ -0,0 +1,16 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +``: + +- **Through the app's own re-exports** (`export { Hydrate } from '@tanstack/react-start'`, an imported `Hydrate` exported again, `export *`, a namespace import, chains of these), `` splits its children like a direct import, in React and Solid, on Vite and Rsbuild; its children's code loaded with the page. A re-export under another name, or one from an installed package, isn't followed. +- **Solid:** children that call `use*()` functions directly are split; the calls run under the boundary's owner, with its context. They failed the build. +- **React:** the hook refusal now covers member calls too: a child calling `React.useId()` or `Route.useLoaderData()` directly fails the build like one calling `useId()`. Move the call into a child component, or use `split={false}`. +- **React:** so does React's `use` written directly in the children, `use(Context)` and `use(promise)` alike (also renamed, or as `React.use`): moved into the split component, `use(Context)` read another context than on the server. The error points at the call, for every hook. +- **New refusals**, where the split children would run on a copy or a snapshot (the build fails at the code; `split={false}` keeps the boundary in place): + - React: a function in the children that reads a `let` the component reassigns, also through a nested ``. Keep the value in a ref (`useRef`). + - Children that assign a local of the component, or a module-level variable other code of the module also uses. The message names the variable; move it to a module of its own, with a function that assigns it. + - `new.target` in the children, and (Solid) a nested boundary assigning an outer local through `ref`. +- `await` or `yield` directly in the children, and a read of a private name of the class around the boundary (`this.#label`), fail the build with a message instead of a parse error. The deferred hydration guide lists every pattern that fails the build. +- **On the server, a hook call whose value only a `fallback` reads** is removed with the imports only it uses, in every file; outside a route's split component it was kept. A hook that needs the browser (`useState(() => window.innerWidth)`) no longer fails the server render there. A hook that takes an id (`useId`, Solid's `createUniqueId`, or a custom hook that calls one) shifts the ids after it on the server, as with `` children: call such a hook in a component inside the boundary. diff --git a/.changeset/import-protection-allow-import.md b/.changeset/import-protection-allow-import.md new file mode 100644 index 00000000000..39f1b4b8e20 --- /dev/null +++ b/.changeset/import-protection-allow-import.md @@ -0,0 +1,12 @@ +--- +'@tanstack/start-plugin-core': minor +'@tanstack/react-start': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +--- + +Import protection: new `allowImport(info)` option, and `onViolation` only reports. + +- `allowImport` runs during the build, before an import is replaced by its mock, in dev and in builds, once per import. Returning `true` gives the import the real module: it is not a violation, nothing is reported, and `onViolation` is not called. `false` or nothing is the normal outcome under `behavior`. It also sees imports that tree-shaking removes later, so use it to decide, not to report, and give stable answers. Its `info` is `onViolation`'s without `trace` and `snippet`. +- `onViolation` runs during the build, after tree-shaking of the importing environment, for imports that survive tree-shaking and were not allowed, and returns nothing. **If you returned `false` to allow an import, move that decision to `allowImport` and return `true`:** returning `false` now does nothing but print a message saying so. It used to silence the report, while a `.server` file stayed mocked and a file with a `server-only` marker shipped for real. +- With RSC, a `'use client'` file allowed from `rsc` is the real module in `ssr` too. diff --git a/.changeset/import-protection-own-client-only.md b/.changeset/import-protection-own-client-only.md new file mode 100644 index 00000000000..7e49da13351 --- /dev/null +++ b/.changeset/import-protection-own-client-only.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +An import-protection error for a client-only component rendered inside an app's own `ClientOnly` component (not the router's), or as the `fallback` of the router's ``, now names where it is rendered and suggests the router's ``, as it does for one rendered without a wrapper. diff --git a/.changeset/import-protection.md b/.changeset/import-protection.md new file mode 100644 index 00000000000..3777c6bbe82 --- /dev/null +++ b/.changeset/import-protection.md @@ -0,0 +1,16 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Import protection: + +- **Exempt importers get the real module.** A module that `exclude` or `ignoreImporters` exempts gets the real module of a denied file it imports plainly; it got the mock. An importer outside the scope (`include`, `srcDirectory`) still gets the mock, and a build now warns once about each denied file it mocks whose every importer is unchecked, naming the file, what denies it, its importers and the fix. The warning isn't a violation: `onViolation` isn't called and `'error'` doesn't fail the build. +- **Importers that disagree fail the build**, on Vite and Rsbuild, under both behaviors: one importer needs a denied file as it is (an exempt plain import, or one `allowImport` allows) while a checked module reaches the file itself (a pattern import such as `import.meta.glob`, or an import another plugin added). The error names the file, each importer and the two fixes: leave the file out of the pattern, or narrow the exemption or `allowImport`. Dev servers print it and keep serving. +- **Verdicts come after tree-shaking:** a build reports only what is in its final client bundle: a mock in one of the bundle's chunks is a violation, one the bundler dropped reports nothing. An import of a denied file that tree-shaking removes no longer fails the build, on Vite and Rsbuild, whatever the file runs at its top level (the client gets the mock, which runs nothing). A bare import (`import './x.server'`), a kept `import()` or `require()` that reads nothing, and an import of type names that `verbatimModuleSyntax` keeps are violations where the build keeps their importer, whatever the tree-shaking options; so is a client entry's own `export {} from '@tanstack/react-start/server-only'`, on Rsbuild too (it built and ran the entry). A denied file that code the compiler does not read imports (a package module, another plugin's import) is mocked as a whole under its package's own `sideEffects`: an unused import of it there is a violation, as on main. +- **Pattern imports:** on Rsbuild, a denied file reached through a template-literal `import()` or `import.meta.webpackContext` is reported (an `'error'` build fails), and the Vite dev server reports the pattern imports it mocks. Both mocked them silently. +- **React Server Components:** a `'use client'` module that a server component imports is a client reference where server components render (Vite's `rsc` environment, Rsbuild's RSC layer): a `.client.tsx` component that a server component rendered was replaced by its mock there, and the page failed to render it. The server component's import of it is how SSR, which renders the component, gets it: when a server rule denies the file, `allowImport` is asked about that import and `onViolation` reports it with `info.env === 'rsc'`, the server component as `importer`, the specifier as written and its position, on Vite and Rsbuild (Rsbuild called it `ssr`; for a marker, Vite reported the marker's import inside the component, in `ssr`). The answer decides what SSR gets: the real component, or its mock and the report (an `'error'` build fails); an exempt server component gives SSR the real one. Its report suggests renaming the file without `.client` (or removing its marker) if it can render on the server, or `` inside another `'use client'` component: a `` in the server component doesn't keep it out of SSR. +- **Rsbuild with RSC: the RSC layer is the `rsc` environment.** `onViolation` and `allowImport` get `info.env === 'rsc'` for a module of the server compiler's RSC layer (server components, server functions' handlers), as on Vite; it was `'ssr'`, the name of SSR's modules too. Match `info.envType === 'server'` for both. The rules that apply there are unchanged (the server rules). `allowImport` is asked once per import and environment, so an import that a file of both layers makes is asked about for `ssr` and for `rsc`, as on Vite. +- **Rsbuild dev and watch builds serve what a fresh build serves.** A denied file is real exactly when an exempt or allowed import arrives at it from a module the app reaches without a denied module served as its mock. The app is what the compilation holds by itself: its entries and includes, however a plugin adds them (`compilation.addInclude` with or without an entry included). So an exempt importer that an edit takes out and puts back gets the real module again (`vite build --watch` too), a denied file in a cycle with its exempt barrel (or a barrel whose import of it `allowImport` allows) no longer keeps itself real once only a checked import reaches it, one edit that flips two denied files serves both as a fresh build does, and a denied file in a layer of your own that the build only finds while building another one gets its real module. A compilation whose module imports change between two builds of the same source names the history of that module (or the server functions, with their files, of a resolver that goes back to an earlier content): a build fails instead of serving it otherwise than its source asks for, and a dev server warns (the next edit starts again). A denied file only a worker plugin's child compiler builds is reported under `behavior: 'error'` in dev too. Every compilation settles the modules it builds, including a worker plugin's child compilation and a module a plugin adds late (a Module Federation shared provide): a denied file that a child compilation only reaches through a checked import (a context) fails the build as a denied import there does, also when the child's exempt entry names it in an import the bundler drops; and a provided module's exempt import of a denied file gets the mock in a cold build as in a cached one, as `main`. +- **Asset queries:** on Vite, `?raw` of a file with a `server-only` marker gives the client the mock; its text shipped. +- **Rsbuild:** a module that a worker plugin builds in a child compiler (`worker-rspack-loader`, workbox) is checked: a denied import there fails the build at the import, whatever the `behavior` (a child compiler can't load the mock), and is reported to `onViolation`; it was mocked silently. +- **Reports:** Vite builds report every violation, not only the first. Mock mode says "Import mocked". A pattern import's report names the pattern and its position and suggests a `!` exclusion. On Rsbuild, traces start at the app's own first file instead of Start's client entry. The suggested fix fits the import: `` for a component rendered on the server (for a route option's component, a wrapper that passes the router's props on: `errorComponent: (props) => `, after `const Component = …` when the value is no component's JSX tag, such as `chart` or `Screens['chart']`), `createClientOnlyFn` for a function. A trace with no file of the app is left out. A marker violation gives the position of the marked module's marker import (`src/count.ts:3:8`). In production builds, a mocked value reports its use at runtime too. diff --git a/.changeset/kept-expression-grammar.md b/.changeset/kept-expression-grammar.md new file mode 100644 index 00000000000..22e8a610a1f --- /dev/null +++ b/.changeset/kept-expression-grammar.md @@ -0,0 +1,14 @@ +--- +'@tanstack/router-utils': patch +'@tanstack/start-plugin-core': patch +--- + +A function an env-only or isomorphic fn keeps in place of its call now behaves as the call did wherever the call stood: + +- an optional chain the call site continues still throws on a failed read (`createServerOnlyFn(cfg?.impl).name` read `undefined`), and an assignment through one builds; +- a nested call (`createServerOnlyFn(createIsomorphicFn().server({}))` as an arrow's body, `createServerOnlyFn(createServerOnlyFn(function () {}))` as a statement) builds and returns its value; +- a kept string statement (`createServerOnlyFn('use client')` after the factory's import) never becomes a directive once the import is removed, nor once a lowering erases TypeScript wrappers around it or the parentheses with them (`createServerOnlyFn('use strict' as any)` in a function with a default parameter failed the Rsbuild build; TypeScript's transpiler and esbuild made a directive of the parenthesised string); +- the kept text no longer runs into the next token (`createServerOnlyFn(impl)in o` failed the build); +- a number before `.` and JSX as a callee or member object get the parentheses they need; +- `delete` and `typeof` of a kept reference act on a value, as on the call's: `delete createServerOnlyFn(box.m)` no longer deletes `box.m`; +- in Solid's `` children, `createClientOnlyFn(cb)()` of a captured `cb` no longer calls it with the component's props as `this`. diff --git a/.changeset/moved-code-context.md b/.changeset/moved-code-context.md new file mode 100644 index 00000000000..e1736b316eb --- /dev/null +++ b/.changeset/moved-code-context.md @@ -0,0 +1,14 @@ +--- +'@tanstack/router-utils': patch +'@tanstack/router-plugin': patch +'@tanstack/start-plugin-core': patch +--- + +Code the compiler moves out of a function (`` children, a server function written inside a class or an object, a split route option) is checked against what it takes from around it by the language's own scoping, the same way in all three: + +- **``**: ``, `this` in a nested class's computed key or in a parameter decorator, and a hook call in a class's computed key now fail the build, as `this` and hooks elsewhere in the children do. `typeof this` in a type no longer does. A class field reading a variable the component assigns later (``) is refused like a function reading it. +- **``**: reading the enclosing function's `arguments` in the children now fails the build, at the `arguments`. Read it into a local before the boundary (`const args = arguments`), or use `split={false}`. +- **``, React**: a function in the children may read a `let` the component assigns, when every assignment is an ordinary statement of the component before the boundary (also in `if`/`else`, `switch` or `try` blocks) and the boundary is not in a loop or a callback: it reads the value assigned. It failed the build. +- **Solid**: `ref={el}` on a `let` counts as an assignment of `el`, unless `el` holds a callback that no code kept in that output reassigns (Solid then calls it). A split handler reading an element a ref outside the boundary sets later now sees it; children naming a module-level `let` by ref fail the build instead of setting a copy the module never reads; a split route component whose ref names a module `let` that `beforeLoad` reads stays in the route module. +- **Server functions in a class**: `this` in a nested class's computed key or as a JSX tag, and a private name an inner class does not declare, fail the build at the code; a member or key named `arguments` and `typeof this` no longer do. A function called in place in the chain that reads a declaration of its own statement fails the build instead of throwing when the module loads. +- **Route splitting**: a `function` loader whose nested class decorates a parameter with the loader's `this` stays in the route module with the `this` warning. diff --git a/.changeset/node-modules-policy.md b/.changeset/node-modules-policy.md new file mode 100644 index 00000000000..8dec00708b0 --- /dev/null +++ b/.changeset/node-modules-policy.md @@ -0,0 +1,16 @@ +--- +'@tanstack/start-plugin-core': patch +'@tanstack/react-start': patch +'@tanstack/solid-start': patch +'@tanstack/vue-start': patch +--- + +One policy for installed and workspace packages: + +- A `server-only` or `client-only` marker is honoured in every file, a package's included, whatever `excludeFiles` says (it now skips file-name rules only). It denies the file to every importer that `exclude` or `ignoreImporters` does not exempt and `allowImport` does not allow: a module outside `srcDirectory`, and a package's module the compiler does not compile (reported at its import of the file), are violations too, no longer a mock with a warning. A bare import of a marked file is a violation wherever its importer runs, even under the app's `"sideEffects": false` (in a package that declares the file free of side effects, the bundler drops it, and nothing is reported). For an importer the compiler does not compile, `allowImport` is asked about the marked file itself (`importer` and `resolved` are the file). +- `@tanstack/-start/server` is a server-only-marked module: a client use of it that the client keeps fails the build at the module that keeps it, in a package or a workspace package too, not only in the app's files. Stricter than before on Vite: a kept constant (`HEADERS`) or a dynamic `import()` behind a runtime guard Vite does not remove (`typeof window`, `isServer`) fails; guard it with `import.meta.env.SSR` or use it inside `createServerFn().handler()`, `createServerOnlyFn()`, `createIsomorphicFn().server()` or `createMiddleware().server()`. On Rsbuild, builds that failed on `node:async_hooks` for an import the client drops now build. +- A package declares Start with `@tanstack/-start`, `@tanstack/start-client-core`, `@tanstack/start-server-core`, `@tanstack/start-fn-stubs` or `@tanstack/-start-rsc` in `peerDependencies`, `dependencies` or `optionalDependencies` (`peerDependenciesMeta` alone does not count). Its modules are read like the app's: a builder one module hands to another under a new name is followed, and the app's handlers built on it leave the client. A package that uses Start without declaring it gets one warning. A builder its modules hand on is followed as in a package that declares Start: every dependency module an import reaches is read, whatever its text (`export { base } from`, the `import { base } from './chunk.js'; export { base }` entry that esbuild, tsup, Rolldown and tsdown print for a builder in a shared chunk, `export const authed = base`, `base?.handler()` on a builder made in another module), so the app's handler built on it leaves the client; on Vite's development server, which pre-bundles such a package, it is not followed. The refusals that apply to a builder from a package that declares Start now apply to one from such a package too, so two builds that used to ship server code to the client without a message now fail: passing its builder to code Start cannot follow (`wrap(pick(base))`), and calling the removed `.inputValidator()` on it. An export is read as the value it starts with: one that starts as a builder and is later replaced by an ordinary object is still a builder to the modules that import it (a `.inputValidator()` on it fails the build); use a second name or a `const`. +- On Vite, the packages Start bundles for the server and keeps out of the optimizer are found through workspace packages, packages that declare Start and installed optional dependencies, by the name the importer wrote (npm aliases work). A Start package behind an ordinary installed package warns that the parent must be bundled (`ssr.noExternal`). +- A module the user lists in `exclude` or `ignoreImporters` is compiled, a package's included, so the denied file it imports is the real one with nothing reported. A route file the generator registered from a package is compiled like the app's (split, `server` handlers off the client). +- Rsbuild with RSC: a package's `'use client'` component that only a server component renders is checked; a server-only module it uses on the client fails the build instead of shipping its mock. +- With RSC on Vite, a package whose export conditions give the browser and the server different files must re-export one module that defines its server functions: a function defined in each fails the build, naming the browser's file. diff --git a/.changeset/route-code-splitting.md b/.changeset/route-code-splitting.md new file mode 100644 index 00000000000..eadb3857d24 --- /dev/null +++ b/.changeset/route-code-splitting.md @@ -0,0 +1,28 @@ +--- +'@tanstack/router-plugin': minor +'@tanstack/router-utils': patch +--- + +Route code splitting keeps its rules: the same options split, as your groupings say; root routes aren't split; code only one split option uses moves into its chunk, and what several options read is one shared module. An option whose value the route file exports stays in the route module, and the build warns once, naming the file and the exports. Top-level statements stay in the route module, and a declaration or import leaves it only when splitting made it unused. + +**Now split:** + +- Options written as methods: `component() {…}`, `loader() {…}`, `async loader() {…}` (#8623). +- The `handler` of a loader object written in the route options (`loader: { handler, staleReloadMode }`): the handler and what only it uses load with the loader's chunk, and the object with its other keys stays in the route module, where the router reads them (#8753). A loader object held by a local `const` stays whole in the route module. An object the compiler can't read in the route file (imported, returned by a call such as `Object.freeze(…)`, chosen by a condition) isn't supported when the loader is split: write the object in the route options. +- Route options named through several `const`s or a cast (`const options = base as any`): they're split, and the options `deleteNodes` lists are removed, as when written inline. + +**Values that failed the build now stay in the route module and work:** a member access (`pages.Home`), `satisfies`, `!`, a class, a namespace member, an array-pattern binding, a sequence, a call holding JSX or TypeScript syntax (`memo(() =>

)`; `memo(Page)` still splits), and an option whose chunk would assign a variable the route module or another chunk also uses (`count++` on a module `let` the `component` reads). + +**Not split, with a warning:** + +- A function or method that uses its own `this` or `super` (#8688): splitting changes what `this` refers to. Use an arrow function, or avoid `this`. +- A route file under `node_modules` (a `physical()` mount of an installed package, a routes package resolved with `resolve.preserveSymlinks`), on Vite, webpack and Rspack: the build or dev server warns once per file. A routes package of a pnpm or Yarn workspace resolves to its real path outside `node_modules` and is split. +- Route options the compiler can't read statically: options built by a call (`createFileRoute('/x')(makeOptions())`), imported, written to after their declaration, or used by other code of the file (`const z = options; z.server = …`, `export const defaults = options`), and what a spread or a computed key holds. The options written next to a spread or computed key still split, and a `deleteNodes` option written there is still removed. Under `deleteNodes` (every Start client build), the warning says the listed options it can't see aren't removed, so the code they read ships to the client: write them as literal properties of the route options. + +**Other changes:** + +- A declaration nothing used before splitting stays in the route module only and runs once (`const unused = register('x')`); split chunks no longer run it again. An import nothing uses (`import './polyfill'`, a stylesheet) runs once, with the route file. +- `codeSplittingOptions.deleteNodes` applies with `autoCodeSplitting: false` too: the listed options are removed from route files in dev and builds. It did nothing without `autoCodeSplitting`. +- Options removed by `deleteNodes` take what only they read out of every output of the route file, split chunks included: a destructuring default only a `server` handler reads (`const { title, secret = readSecret() } = …`) no longer brings its server-only import into a client chunk. +- Under `verbatimModuleSyntax`, a value import that only split code used in types is no longer loaded. Import a module you need for its side effects with `import './x'`. +- Production source maps name a split chunk's source by the route file's path, not `route.tsx?tsr-split=…`, so devtools show one file and error trackers group by it. diff --git a/.changeset/route-delete-webpack-family.md b/.changeset/route-delete-webpack-family.md new file mode 100644 index 00000000000..e2a66fbfe2d --- /dev/null +++ b/.changeset/route-delete-webpack-family.md @@ -0,0 +1,6 @@ +--- +'@tanstack/router-plugin': patch +'@tanstack/router-generator': patch +--- + +Deleting or renaming a route file while webpack or Rspack/Rsbuild watches no longer fails a build with `Can't resolve` from the route tree (also with `bail`, and with the route tree generated into a linked directory), and on webpack a route file re-created right after its deletion is served again: the compilation of the change now builds the route tree (and the route files the generator rewrote) from what the generator wrote. The generator's `Generator` takes an `onWrite` option, told of each file it replaced. diff --git a/.changeset/route-generator.md b/.changeset/route-generator.md new file mode 100644 index 00000000000..d45a0b72985 --- /dev/null +++ b/.changeset/route-generator.md @@ -0,0 +1,24 @@ +--- +'@tanstack/router-generator': minor +'@tanstack/router-cli': patch +'@tanstack/router-plugin': patch +'@tanstack/start-plugin-core': patch +--- + +The route generator is rebuilt without Babel. + +**`routeTree.gen.ts` formatting changes.** The route tree is printed directly in your `quoteStyle` and `semicolons`, and `enableRouteTreeFormatting` now defaults to `false`: Prettier is loaded only when you set it to `true`. If your formatter ignores the file, as the installation guides recommend, commit the one-time diff. If a formatter runs over it, ignore the file or set `enableRouteTreeFormatting: true`: otherwise the generator and the formatter rewrite each other's output on every run. Custom scaffolding templates are inserted as written, and Start's route tree footer follows `quoteStyle` and `semicolons` too. + +- Route files are recognised by binding: an aliased `createFileRoute` import gets its id fixed; a `createFileRoute` the app declares itself is left alone; a plain template literal path (``createFileRoute(`/posts`)``) that doesn't match the file is rewritten to a string literal in your `quoteStyle`; a computed path (`${…}`, a variable) is reported, not rewritten (#7216). +- The tree is rebuilt from the files on every change: deleting a layout keeps its children, a deleted `routeTree.gen.ts` is written again, and edits of a TypeScript virtual route config and of `__virtual.ts` files are picked up (a JavaScript config, `.js`, `.mjs` or `.cjs`, still needs a restart). +- Empty `.ts` route files get a scaffold without JSX (#8480); `.lazy.vue` files (the route's component; next to a `.component.vue` piece, the route's lazy route as before) and `route.component.vue` pieces belong to their route; `importRoutesUsingAbsolutePaths` applies to lazy imports; unusual file names give valid trees. +- A route file named `root` with child routes no longer breaks the types of the root route's children: its names in `routeTree.gen.ts` took the tree's own `RootRouteChildren`, which was then declared twice. A route named `root` is now `Root2Route` in the tree (`routeTree.children.Root2Route`). +- Router-only builds fail on a route tree error (two files for one route, two routes with one id, conflicting paths, a missing root route) or a route file that doesn't parse, naming the files; they built with the route tree on disk, without the route. `tsr generate` also fails on a root route file that doesn't parse. A dev server or watch session prints the error and keeps the last good tree. +- A route file the generator adds the router import to keeps a leading `// @ts-nocheck`, `// @ts-check` (in any case, as TypeScript reads them) or `/// ` above it; the import went above the directive, which TypeScript then ignored. +- Writes work when `tmpDir` is on another filesystem than the project; they failed with `EXDEV`. A dev server or `tsr watch` keeps writing the route tree after its temporary directory (`.tanstack/tmp` by default) is deleted under it (`git stash -u`, `git clean -fd`); every later route change failed until a restart. +- `tsr watch` and the Rspack and webpack plugins watch every route root, including `physical()` mounts, and every route file a virtual route config names outside them. `vite build --watch` picks up route files created while it watches. +- The Rspack and webpack plugins apply a route config edit after a watching was closed and another opened on the same compiler (a tool that pauses and resumes a compiler): the route tree and the route modules' splitting followed it only after a restart. +- The esbuild plugin (`@tanstack/router-plugin/esbuild`) generates the route tree at the start of every build and rebuild; an app without a committed route tree failed to build. esbuild watches only the files of the bundle, so a route file created in watch mode joins the tree at the next rebuild (or run `tsr watch` beside it). +- A Vite build whose environments share the plugins from a config file (`builder.sharedPlugins`, as TanStack Start sets it) runs the generator once instead of once per config resolution, so a generator plugin's `onRouteTreeChanged` runs once. + +**API:** removed `format`, `inferFullPath`, `checkRouteFullPathUniqueness`, `writeIfDifferent` and the `ImportDeclaration`, `ImportSpecifier`, `HandleNodeAccumulator`, `TransformContext` and `TransformOptions` types. A generator plugin's `onRouteTreeChanged` receives `{ model, generator }`, and `afterTransform` is gone. The `Generator` no longer takes an `fs` option (an undocumented file-system override): it reads and writes route files directly. It takes an optional `logger`. The `Generator`'s `buildRouteTree()`, `getCrawlingResult()` and `targetTemplate` are removed, and so is `RouteNode.createFileRouteProps`; `getRoutesByFileMap()` returns a `ReadonlyMap` (`GetRoutesByFileMapResult`), and `GetRouteNodesResult` has a required `subtreeDirectories`. diff --git a/.changeset/route-hmr.md b/.changeset/route-hmr.md new file mode 100644 index 00000000000..a07e713c487 --- /dev/null +++ b/.changeset/route-hmr.md @@ -0,0 +1,18 @@ +--- +'@tanstack/router-core': minor +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +'@tanstack/router-plugin': patch +--- + +Route HMR (development only) runs on a new runtime that the router plugin's dev output imports from new `/hmr` subpaths (`@tanstack/router-core/hmr`, `@tanstack/{react,solid,vue}-router/hmr`). It updates the live route in place and keeps each split component's lazy wrapper across updates. Nothing of it reaches production bundles, and production and server code never load it. + +- **React: an edit always shows.** The router takes the new component once React Refresh ran its refresh pass (or after 200 ms when no pass comes), and React Refresh alone decides whether the component keeps its state. An update that gives the route no component React Refresh may patch (each one split, as `autoCodeSplitting` does by default, absent or unchanged) applies as soon as the module evaluates. A component React Refresh can't patch (`const Page = flag ? Wide : Narrow`, a factory's result, an unexported class, a layout import switched to another module) kept showing the old code until a reload. +- **Solid: an edit always shows.** The router keeps the component it holds only when solid-refresh patched it in place (both are solid-refresh proxies of the same component name and file). Before, a component chosen by a condition (`flag ? Wide : Narrow`), a swap through a barrel or a rename in an unsplit route could stay stale. Split chunks carry the route file's `@refresh` comments (`// @refresh granular`, a copy of the comment alone, read where the refresh plugin reads it in the file; the statement it is on still runs once), so a split component keeps its state where an unsplit one does; on React, a split component resets on every edit under `/* @refresh reset */` as an unsplit one does. After a rename or a removed component in a split route, later edits show only after a reload (solidjs/solid-refresh#88). A `codeSplitGroupings` edit that moves a component to another chunk (or in or out of the split), or removes a component from a chunk another component stays in, reloads the page; before, the edits after it stayed stale until a reload. Adding or removing another component (an `errorComponent`) updates in place. Restoring a deleted file a split component reads reloads the page once, on every host, also with Rsbuild's `dev.liveReload: false` (solid-refresh patches a module only in its own update on Vite); before, the page showed the old file until the next edit on Vite. +- Lazy route files (`createLazyFileRoute`, `*.lazy.tsx`) update in place instead of reloading the page, on Vite and Rsbuild, for React, Solid and Vue; a React component keeps its state when React Refresh can patch it. The page still reloads when the edit removes an option the route had loaded from the lazy file (the route file's value shows again). +- On Rspack, an edit of a split loader refreshes the route; the page kept the old loader's data. +- An edit of a Vue route file keeps the component of its `*.component.vue` file; the page went blank until a reload. +- An update reaches every router of the page that holds a route the edited file evaluated to (or that loaded its lazy route file's options), whichever router was created last: two routers of one route tree (React StrictMode's state initializer) both show it. Another router's route of the same id from another file (a widget's code router, a second route tree compiled by its own plugin instance, module federation) is left alone (#7921). Before, an edit could reach only the router created last, or the other router's route. +- One save that changes a loader's data shape and the component reading it shows in place, React, Solid and Vue; before, the page could end on the error screen until the next save. In a Start app whose root route renders the document and has no route `errorComponent` (or router `defaultErrorComponent`), React reloads the page once in that save; Solid and Vue can leave the page blank or on the error until the next route save, which reloads. +- After a render error, the edit that fixes it shows in place in a client-only app and wherever a route error component caught it (in a Solid Start app whose root route renders the document in its component, the root's own error component replaces the document, and the fixing edit reloads the page); before, a route edit after any caught render error reloaded the page, also after the page had recovered. diff --git a/.changeset/route-recognition.md b/.changeset/route-recognition.md new file mode 100644 index 00000000000..93677074a39 --- /dev/null +++ b/.changeset/route-recognition.md @@ -0,0 +1,11 @@ +--- +'@tanstack/router-generator': patch +'@tanstack/router-plugin': patch +--- + +The route generator and the code splitter recognise route files the same way: a file is split only when the generator lists it and its `Route` is the router's own `createFileRoute`, `createLazyFileRoute`, `createRootRoute` or `createRootRouteWithContext` call for that kind of file, imported from the configured framework's router package (an aliased import counts). A file the generator doesn't list, or a `Route` made by a helper the app imports, is served as written. + +- The generator repairs a root constructor in a route file to `createFileRoute(path)`, and `createFileRoute` or `createLazyFileRoute` in `__root` to `createRootRoute`, as it repairs `createLazyFileRoute` in a route file. +- A route id that isn't a string literal builds with a warning; it failed route generation and the build. A route id with a type assertion (`'/x' as const`) is a literal the generator keeps in sync; it failed route generation too. +- A route file whose `Route` the code splitter can't read builds unsplit with a warning that names the cause and the call to write: the options call missing, a constructor imported as a type only, a root constructor called the wrong way (`createRootRouteWithContext()({ … })` for the context form), a call wrapped, made inside a function of the file or stored in another `const`, a route made with `createRoute`, a `Route` declared by a destructuring (`export const { Route } = …`, left out of the route tree before) or declared twice (a build error before). A route made inside a function of the file (an app's route factory) was split and threw at runtime. Under TanStack Start the warning says that the route's `server`, `ssr` and `headers` options ship to the client. +- Under TanStack Start, while route generation has never succeeded (a dev server started with a route file that doesn't parse), a module that exports `Route` fails with the generator's error, instead of being served as written with its `server` code. Once generation succeeds, it is compiled as a route again. diff --git a/.changeset/route-set-publication.md b/.changeset/route-set-publication.md new file mode 100644 index 00000000000..47a4a5c3125 --- /dev/null +++ b/.changeset/route-set-publication.md @@ -0,0 +1,13 @@ +--- +'@tanstack/router-generator': minor +'@tanstack/router-plugin': patch +'@tanstack/start-plugin-core': patch +--- + +Route-set changes reach every dev server. + +- Start on Rsbuild reloads the open tab when the client's route tree changes (a route added, deleted or renamed, a page turned into a server handler or back, a lazy file added), once the client and the server both serve the change. In an app that installed Start, this replaces the reload Rsbuild's client made at the client's compile, with an `HMR update failed` line in the console. With RSC the reload goes over the RSC client's channel. An app that sets `dev.liveReload: false`, for all environments or for the client, is not reloaded; with `dev.hmr: false`, without RSC and with live reload on, Rsbuild's own reload at every client compile stays the only one. +- On Vite dev, the modules of the files a generator run replaced are invalidated when the run is published, so a route tree whose watcher event Vite dropped or another plugin held is not served stale. +- The client's route tree orders each sibling list after leaving out server-only routes: a pathless layout whose only route below it is server-only no longer takes `/` from the index route. The client's tree is also found when `generatedRouteTree` is in a linked directory, one the generator creates included. +- A generator replaced by a `tsr.config.json` change no longer writes, publishes or reports anything for its last run. A cold generation failure followed by another reports the second. A generator session closed before its watcher is ready ends its `watch()`, and a Start `vite build --watch` whose client watcher closes during its first build ends. +- The generator exports `contentDigest` and `ownersLast`, and answers `sourceDigest`, `treeDigest` and `retire()`. diff --git a/.changeset/route-watcher-errors-and-config-replace.md b/.changeset/route-watcher-errors-and-config-replace.md new file mode 100644 index 00000000000..b3acc6160fe --- /dev/null +++ b/.changeset/route-watcher-errors-and-config-replace.md @@ -0,0 +1,8 @@ +--- +'@tanstack/router-cli': patch +'@tanstack/router-generator': patch +--- + +The route generator's file watcher and the `tsr watch` config watcher report their errors instead of ending the process. An example is a path the watcher cannot watch, such as a route file linked to a file in a directory that can be searched but not read. The watcher keeps watching the other paths. + +`tsr watch` now starts again with the new config when `tsr.config.json` is replaced by a save that removes the file and writes it again, and when the file is created after `tsr watch` started. Before, it could keep the previous config until it was restarted. A config saved while `tsr watch` is starting again makes one more start after it, so starts no longer overlap. diff --git a/.changeset/router-generator-router-utils.md b/.changeset/router-generator-router-utils.md new file mode 100644 index 00000000000..92daa3e8d8b --- /dev/null +++ b/.changeset/router-generator-router-utils.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-generator': patch +--- + +The route generator now depends on `@tanstack/router-utils`, for the syntax helpers it shares with the compiler. diff --git a/.changeset/router-generator-sysreview-fixes.md b/.changeset/router-generator-sysreview-fixes.md new file mode 100644 index 00000000000..09a5a2d47c8 --- /dev/null +++ b/.changeset/router-generator-sysreview-fixes.md @@ -0,0 +1,10 @@ +--- +'@tanstack/router-generator': patch +'@tanstack/start-plugin-core': patch +--- + +- The root route of a `physical()` mount with a path prefix stays a root route: its `createRootRouteWithContext` declaration is no longer rewritten. +- A Vue component and a TypeScript route file sharing a name can be used for two routes. +- Route constructor repair keeps an import that a type still references (`typeof createRootRoute`). +- An import added to a route file whose `'use client'` directive has a trailing comment goes below that line instead of breaking the file. +- Prerender discovery includes a static route whose component is in its lazy file or a component piece (`about.lazy.tsx`, `about.component.vue`). diff --git a/.changeset/router-plugin-esbuild-abs-working-dir.md b/.changeset/router-plugin-esbuild-abs-working-dir.md new file mode 100644 index 00000000000..9d2599082c9 --- /dev/null +++ b/.changeset/router-plugin-esbuild-abs-working-dir.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-plugin': patch +--- + +esbuild: `tanstackRouter()` reads `tsr.config.json` and resolves relative route paths from esbuild's `absWorkingDir`, as the other bundlers do from their root; `autoCodeSplitting` there is refused when the build starts. diff --git a/.changeset/router-plugin-next-to-start.md b/.changeset/router-plugin-next-to-start.md new file mode 100644 index 00000000000..95b1b0319ec --- /dev/null +++ b/.changeset/router-plugin-next-to-start.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-plugin': patch +--- + +A Vite app that registers `tanstackRouter()` next to `tanstackStart()` fails with an error saying to remove `tanstackRouter()` (Start already includes it), instead of a `MISSING_EXPORT` build error. diff --git a/.changeset/router-plugin-options-callback.md b/.changeset/router-plugin-options-callback.md new file mode 100644 index 00000000000..7b5e2f7caa7 --- /dev/null +++ b/.changeset/router-plugin-options-callback.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-plugin': patch +--- + +An options callback (`tanstackRouter(() => ({ ... }))`) takes the defaults and `tsr.config.json` on Vite and esbuild too, as on webpack and Rspack: Vite splits routes again, and esbuild refuses `autoCodeSplitting` set in `tsr.config.json`. diff --git a/.changeset/router-plugin-sysreview-fixes.md b/.changeset/router-plugin-sysreview-fixes.md new file mode 100644 index 00000000000..8a6a3f9c2ba --- /dev/null +++ b/.changeset/router-plugin-sysreview-fixes.md @@ -0,0 +1,11 @@ +--- +'@tanstack/router-plugin': patch +--- + +- Rspack's options callbacks (`TanStackRouterGeneratorRspack(() => ({ … }))`, `TanStackRouterCodeSplitterRspack(() => ({ … }))`): the options the callback leaves out take their defaults, as with an options object. +- `codeSplitGroupings` accepts a parenthesized group (`[(['loader']), ['component']]`). +- A route option already wrapped in `lazyRouteComponent` or `lazyFn` is no longer wrapped again, so its `preload()` loads its module. +- A reassigned handler named under a computed key of a route's `server` option (`{ ['GET']: get }`) fails the build like one under a plain key. +- webpack and Rspack resolve the router config and relative route paths against the compiler's `context`, not the working directory, and a `mode: 'none'` build no longer includes route HMR code. +- webpack and Rspack persistent caches: a module the cache restores that has become a route (listed in `virtualRouteConfig` since) is built again, and split. +- A route option written as a method that stays in the route module no longer moves a value it shares with a split option into a shared module that runs before the route module's earlier statements. diff --git a/.changeset/rsbuild-dev-manifest-after-edits.md b/.changeset/rsbuild-dev-manifest-after-edits.md new file mode 100644 index 00000000000..8dbb134326c --- /dev/null +++ b/.changeset/rsbuild-dev-manifest-after-edits.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild dev: pages link the preloads and stylesheets of the current client build after an edit. After an edit that added an import of a module in a chunk of its own, a CSS import or a new route, server-rendered pages kept linking what the dev server's first client build emitted until a restart (missing preloads and styles). diff --git a/.changeset/rsbuild-host-records.md b/.changeset/rsbuild-host-records.md new file mode 100644 index 00000000000..75aa1003678 --- /dev/null +++ b/.changeset/rsbuild-host-records.md @@ -0,0 +1,14 @@ +--- +'@tanstack/start-plugin-core': patch +'@tanstack/router-utils': patch +--- + +Start on Rsbuild: what a compile leaves besides the module (its record, the server-function registry, the modules Start generates, the warnings) now follows four rules, each with one writer. + +- A build or a dev server on a primed persistent cache no longer builds the client route tree, the server-function resolver or the Start manifest again when they were built from the current content: on an app of about 450 modules, a warm build is 3% faster and a warm dev start 2% faster. An app's own transform on `routeTree.gen.ts` runs when the tree is built, so not on an unchanged restore. +- A second `createDevServer()` on one Rsbuild instance serves its own Start manifest and server-function resolver. +- A second `build()` on one Rsbuild instance with the persistent cache serves its own client files: the page no longer links the JS files of the first build. +- A dev server drops a server function, and its file, from the server compilation once the last import of it is removed, as on Vite: a later save of the file no longer builds it on the server. With RSC, `build --watch` drops a server function whose only caller an edit removed, as a new build does. +- A module the client gets as its import-protection mock no longer registers its server functions. +- In `build --watch`, an installed package's server-only module edited to drop its marker no longer reports a violation. +- Warnings are on a compilation when it seals, and each report (a build's, each `build --watch` rebuild's, a dev server's until it printed them once) has each warning once. A `build --watch` rebuild prints a warning of a module it kept, also when only the server compiled again, and so does the error of an invalid custom server function id. An app plugin that reads a compilation's warnings once it sealed (a "no warnings" policy) sees Start's. When the client and server compilations overlap in a dev server, a package's "does not declare Start" warning is in the first report that can show it. A warning about a module a worker built by a child compiler imports is printed once, at its file, whatever the worker plugin does with the child's warnings, also from the persistent cache. diff --git a/.changeset/rsbuild-hydrate-css-other-routes.md b/.changeset/rsbuild-hydrate-css-other-routes.md new file mode 100644 index 00000000000..ea0917631ff --- /dev/null +++ b/.changeset/rsbuild-hydrate-css-other-routes.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: a page no longer links the stylesheets of another route's `` boundaries. When two or more lazy routes used ``, the chunk they share (with ``'s own code) was read as dynamically importing every boundary of every one of those routes, so each route's page linked the CSS of all the others' boundaries. diff --git a/.changeset/rsbuild-query-chunk-names.md b/.changeset/rsbuild-query-chunk-names.md new file mode 100644 index 00000000000..c452204fd6f --- /dev/null +++ b/.changeset/rsbuild-query-chunk-names.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: client chunks named with a query (`[name].js?v=[contenthash]`) keep their server functions callable over HTTP and their route stylesheets linked. diff --git a/.changeset/rsc-css-conditionals.md b/.changeset/rsc-css-conditionals.md new file mode 100644 index 00000000000..29bf4157449 --- /dev/null +++ b/.changeset/rsc-css-conditionals.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': minor +--- + +RSC CSS: a server component passed to `renderServerComponent`, `createCompositeComponent` or `renderToReadableStream` through `?:`, `&&`, `||` or `??` carries its CSS on each operand that can be the JSX rendered; only a JSX argument written directly carried it. diff --git a/.changeset/rsc-data-slot.md b/.changeset/rsc-data-slot.md new file mode 100644 index 00000000000..8cc1ec5603a --- /dev/null +++ b/.changeset/rsc-data-slot.md @@ -0,0 +1,5 @@ +--- +'@tanstack/react-start-rsc': patch +--- + +A renderable server component payload with a slot named `data` (`renderServerComponent({ data:

})`) renders that slot; `{payload.data}` threw "Objects are not valid as a React child". diff --git a/.changeset/rspack-webpack-rsbuild.md b/.changeset/rspack-webpack-rsbuild.md new file mode 100644 index 00000000000..125358b0699 --- /dev/null +++ b/.changeset/rspack-webpack-rsbuild.md @@ -0,0 +1,13 @@ +--- +'@tanstack/router-plugin': patch +'@tanstack/start-plugin-core': patch +--- + +Rspack, webpack and Rsbuild: + +- The router plugin uses its own loader, so project paths with `'` or `#` build (#7754). Paths with `'` or `#` build on Vite too. +- The router plugin's loader rule matches every JavaScript module outside `node_modules` (it leaves modules that aren't routes unchanged), so a file stays one module when it becomes a route or stops being one. Because the loader is now part of every app module's request, the deterministic module ids of those modules change with this release, and under pnpm (or any install whose paths hold the package version, such as Yarn Plug'n'Play) with each later update of the plugin too; with npm's `node_modules` layout they change once. The code doesn't change. +- Start's Rsbuild loader passes a dependency's module it doesn't compile on as the bytes it came as: a package's binary file with a JavaScript extension imported as an asset (an MPEG transport stream segment named `.ts`, with `type: 'asset/resource'`) is emitted unchanged instead of corrupted, and a byte order mark is kept. +- Rsbuild and Rspack dev: a hot update holds only the outputs an edit changes. In a live session, browser DevTools keep a file's previous text after an edit that changes no output's code (a comment, a type) until a reload; a reload or a new tab shows the current text. Start's server environment puts the files' text into its maps only when Rsbuild writes them to disk (`dev.writeToDisk`): Rsbuild runs the server bundles from memory, and Node never reads those maps. +- Start on Rsbuild with `performance.buildCache`: a build after a source edit no longer serves pages that link the previous build's client entry. Rspack's persistent cache restored the server's Start manifest, so every page loaded a missing script and never hydrated. +- webpack and Rspack with a persistent cache: a build after a code-splitting configuration change the bundler's cache doesn't see (`tsr.config.json`, options computed from the environment, a bundler config outside `cache.buildDependencies`) splits routes as a build with a fresh cache does. The cache used to restore route modules split under the earlier groupings. diff --git a/.changeset/server-only-route-becomes-page-watch.md b/.changeset/server-only-route-becomes-page-watch.md new file mode 100644 index 00000000000..864d457b618 --- /dev/null +++ b/.changeset/server-only-route-becomes-page-watch.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild dev, `rsbuild build --watch` and `vite build --watch`: a server-only route that gains a component (or a loader, `head` or another client option) reaches the client. The client route tree leaves server-only routes out, so only the server compiled again and the page showed Not Found until another client edit or a restart. The client route tree module now depends on the route files it left out. diff --git a/.changeset/solid-start-default-entry-no-jsx.md b/.changeset/solid-start-default-entry-no-jsx.md new file mode 100644 index 00000000000..70d2aeca9b8 --- /dev/null +++ b/.changeset/solid-start-default-entry-no-jsx.md @@ -0,0 +1,5 @@ +--- +'@tanstack/solid-start': patch +--- + +Vite dev pre-bundles the dependencies of an app that uses Solid Start's default client entry when the package resolves outside the app's root (a monorepo, a pnpm store at the workspace root). The default entry no longer contains JSX, which Vite's dependency scan read as React JSX there, failing on `react/jsx-dev-runtime` and skipping pre-bundling. diff --git a/.changeset/start-builders-and-erasure.md b/.changeset/start-builders-and-erasure.md new file mode 100644 index 00000000000..9d12eccd2cb --- /dev/null +++ b/.changeset/start-builders-and-erasure.md @@ -0,0 +1,19 @@ +--- +'@tanstack/start-plugin-core': minor +'@tanstack/start-client-core': patch +--- + +Start never ships server code to the client through a builder it can't follow: each use of a Start builder or factory (`createServerFn`, `createMiddleware`, `createIsomorphicFn`, `createServerOnlyFn`, `createClientOnlyFn`, `createStart` and what they return) is either compiled or fails the client build at that use, with the fix. In development the module fails (the overlay shows it). + +- **Now compiled** (their handlers shipped to the client): a factory destructured from a Start namespace (`const { createServerFn } = Start`), `(0, createServerFn)()`, a builder chosen by `?:`, `??`, `||` or `&&` between two builders of the same kind, a factory with statements before its single `return`, a project namespace re-exported (`export * as ns`) and read by member, a factory that two `export *` branches reach under two names of one binding (`export { api as a, api as b }`, or an imported binding exported beside a re-export of it), and a factory exported as `'*'`. +- **Now a client build error, at the use:** a builder or factory passed to a function, stored in an object, an array or a class field, awaited or rendered as a JSX prop; a method read off a builder (`const h = createServerFn().handler`, `.call`, `.bind`) or an unknown method; a builder returned from a function with control flow, from an async function, a method or a getter; a `let` builder reassigned with anything else; a builder destructured; a builder in a TS `namespace`; a project namespace object passed around when its module exports a builder; a choice between two isomorphic functions of which only one's call returns a builder; a server function built on a `var` that redeclares a function or a parameter. +- **A client-only `createIsomorphicFn().client(fn)` or `createMiddleware().client(fn)` passed to other code** fails the client build too, as a precaution: pass the middleware to `.middleware([…])` or `createStart`'s lists directly, or end its chain with `.server(({ next }) => next())`; give the isomorphic function `.server(() => undefined)`, or use `createClientOnlyFn(fn)`. +- **A function parameter that reaches server code:** passed directly as the server code (`(fn) => createServerOnlyFn(fn)`, `({ handler }) => createMiddleware().server(handler)`), it fails the client build, since every call keeps its argument on the client. Only read inside the server code (`(role) => createMiddleware().server(() => check(role))`), it gets one warning at its definition: what callers pass for it ships to the client, so don't pass secrets or server code through it. +- **Builder options:** passing a builder's options object on, writing to it or reading its `middleware` list fails the client build; read the options you need by name (`base.options.method`, `const { method } = base.options`). A builder's `.options` is typed read-only. +- **`.inputValidator()`** (renamed to `.validator()` in #7566 and removed in #8694) fails the client build at the call, saying to call `.validator()` or to update the dependency that calls it. +- **Not followed, no error:** `import()`, `require()` and `import.meta.glob` of Start objects, and modules other plugins generate or rewrite. Keep builders statically analyzable. +- **Called at once with a method:** an env-only or isomorphic function whose implementation is a method and that is called where it is created (`createClientOnlyFn(obj.method)()`, `createIsomorphicFn().client(obj.method)()`) calls the method detached (`(0, obj.method)()`), as the function the factory returns does. It was called with `obj` as `this`. +- **Erasure:** a class, `enum` or `namespace` that only code removed for the other environment uses (a handler on the client, an isomorphic function's `.server()`, a `createServerOnlyFn` body) is removed with the imports only it uses; it stayed in the client bundle with its imports. +- **TypeScript from another Vite plugin:** a file that is no JavaScript, which a plugin hands to the bundler as TypeScript (`moduleType: 'ts'` or `'tsx'`), is compiled as TypeScript; its handlers shipped to the client. + +**Vue single-file components:** the script blocks are compiled on Vite and on Rsbuild with `@rsbuild/plugin-vue`. On Rsbuild, an SFC that imports Start failed the build. On the dev servers and in builds with Vue's devtools (Vite: `features.prodDevtools`, a true `__VUE_PROD_DEVTOOLS__` define or `NODE_ENV=development`; Rsbuild: `NODE_ENV=development`), Vue hands a ` + + +` + +// The configs import the harness plugin through a relative path so the app +// stays free of extra dependencies. The plugin is inert unless the harness +// sets COMPILER_PERF_HOOKS_OUT. +const startViteConfig = `import path from 'node:path' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { hookTimingPlugin } from '../../scripts/hook-timing.mjs' + +export default defineConfig({ + cacheDir: path.resolve(import.meta.dirname, '.vite-cache'), + logLevel: 'warn', + clearScreen: false, + build: { outDir: process.env.COMPILER_PERF_OUT_DIR ?? 'dist' }, + plugins: [tanstackStart(), viteReact(), hookTimingPlugin()], +}) +` + +// tanstack.com's vite.config: a Rollup-style `manualChunks` function grouping +// Start's client runtime, which Rolldown merges into the entry +const startDepsViteConfig = startViteConfig.replace( + " build: { outDir: process.env.COMPILER_PERF_OUT_DIR ?? 'dist' },", + ` build: { + outDir: process.env.COMPILER_PERF_OUT_DIR ?? 'dist', + rollupOptions: { + output: { + manualChunks: (id: string) => + id.includes('/node_modules/@tanstack/react-start') || + id.includes('/node_modules/@tanstack/start-') + ? 'tanstack-start' + : undefined, + }, + }, + },`, +) + +/** + * The generated dependency graph of `react-start-deps`, written under the + * app's own node_modules: `@bench/icons` (a barrel of DEP_ICONS components, + * side-effect free, like an icon package), `@bench/utils` (a chain of + * DEP_UTILS modules each importing the next two) and `@bench/start-lib` (a + * Start library: a server function, a `` wrapper, a 2 MB `?url` + * asset, the utils chain). + */ +function dependencyFiles(rng) { + const files = new Map() + const pkg = (name, extra = {}) => + JSON.stringify( + { + name, + version: '1.0.0', + type: 'module', + exports: { '.': './index.js' }, + ...extra, + }, + null, + 2, + ) + '\n' + files.set( + 'node_modules/@bench/icons/package.json', + pkg('@bench/icons', { sideEffects: false }), + ) + const barrel = [] + for (let n = 0; n < DEP_ICONS; n++) { + const id = pad4(n) + barrel.push(`export { Icon${id} } from './icons/Icon${id}.js'`) + files.set( + `node_modules/@bench/icons/icons/Icon${id}.js`, + `import { jsx } from 'react/jsx-runtime' +export function Icon${id}(props) { + return jsx('svg', { 'data-icon': '${id}', viewBox: '0 0 ${rng.int(8, 64)} 16', ...props }) +} +`, + ) + } + files.set('node_modules/@bench/icons/index.js', barrel.join('\n') + '\n') + files.set('node_modules/@bench/utils/package.json', pkg('@bench/utils')) + files.set( + 'node_modules/@bench/utils/index.js', + `export { u0000 as util } from './u0000.js'\n`, + ) + for (let n = 0; n < DEP_UTILS; n++) { + const id = pad4(n) + const next = [(n + 1) % DEP_UTILS, (n + 2) % DEP_UTILS].map(pad4) + files.set( + `node_modules/@bench/utils/u${id}.js`, + `import { u${next[0]} } from './u${next[0]}.js' +import { u${next[1]} } from './u${next[1]}.js' +export function u${id}(depth) { + return depth <= 0 ? ${rng.int(1, 999)} : u${next[0]}(depth - 1) + u${next[1]}(depth - 2) +} +`, + ) + } + files.set( + 'node_modules/@bench/start-lib/package.json', + pkg('@bench/start-lib'), + ) + // a binary asset a bundler serves by URL: never code, never read as text + let blob = '' + for (let i = 0; i < 2 * 1024 * 1024; i++) { + blob += String.fromCharCode(rng.int(1, 255)) + } + files.set('node_modules/@bench/start-lib/engine.wasm', blob) + files.set( + 'node_modules/@bench/start-lib/index.js', + `import { jsx } from 'react/jsx-runtime' +import { createServerFn } from '@tanstack/react-start' +import { ClientOnly } from '@tanstack/react-router' +import { util } from '@bench/utils' +import engineUrl from './engine.wasm?url' + +export const libStats = createServerFn({ method: 'GET' }).handler(async () => { + return { engine: engineUrl.length, depth: util(6) } +}) + +export function LibBadge({ label }) { + return jsx(ClientOnly, { + fallback: null, + children: jsx('span', { 'data-lib': engineUrl, children: label + util(3) }), + }) +} +`, + ) + return files +} + +const routerViteConfig = `import path from 'node:path' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { hookTimingPlugin } from '../../scripts/hook-timing.mjs' + +export default defineConfig({ + cacheDir: path.resolve(import.meta.dirname, '.vite-cache'), + logLevel: 'warn', + clearScreen: false, + build: { outDir: process.env.COMPILER_PERF_OUT_DIR ?? 'dist' }, + plugins: [ + tanstackRouter({ target: 'react', autoCodeSplitting: true }), + viteReact(), + hookTimingPlugin(), + ], +}) +` + +const startRsbuildConfig = `import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' + +export default defineConfig({ + logLevel: 'warn', + plugins: [pluginReact(), tanstackStart()], + output: { + distPath: { root: process.env.COMPILER_PERF_OUT_DIR ?? 'dist-rsbuild' }, + cleanDistPath: true, + }, + performance: { printFileSize: false }, +}) +` + +const solidHydratedMarker = ` onMount(() => { + ;(window as any).__PERF_HYDRATED__ = performance.timeOrigin + performance.now() + })` + +const solidStartRootSource = `import { onMount } from 'solid-js' +import type { JSX } from 'solid-js' +import { HydrationScript } from 'solid-js/web' +import { HeadContent, Outlet, Scripts, createRootRoute } from '@tanstack/solid-router' +import { Nav } from '../components/Nav' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }, { title: 'Compiler perf app' }], + }), + component: RootComponent, + notFoundComponent: () =>

Not found

, +}) + +function RootComponent() { + return ( + + + + ) +} + +function RootDocument(props: { children: JSX.Element }) { +${solidHydratedMarker} + return ( + + + + + + +