diff --git a/.changeset/react-start-prebundle-store-path.md b/.changeset/react-start-prebundle-store-path.md new file mode 100644 index 0000000000..5c5b78c8da --- /dev/null +++ b/.changeset/react-start-prebundle-store-path.md @@ -0,0 +1,5 @@ +--- +'@tanstack/react-start': patch +--- + +fix: Vite pre-bundles `@tanstack/react-store` for a project that depends on `@tanstack/react-start` but not on `@tanstack/react-router` itself. Start named the dependency by a path through `@tanstack/react-router`, which only resolves from a project that depends on the router. In such a project Vite warned "Failed to resolve dependency: @tanstack/react-router > @tanstack/react-store", and a browser failed to load the store's CommonJS dependency (`use-sync-external-store`). diff --git a/.changeset/start-mock-server-fn.md b/.changeset/start-mock-server-fn.md new file mode 100644 index 0000000000..6dbd9b72e3 --- /dev/null +++ b/.changeset/start-mock-server-fn.md @@ -0,0 +1,24 @@ +--- +'@tanstack/start-client-core': minor +'@tanstack/react-start': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +'@tanstack/start-plugin-core': minor +--- + +Add `mockServerFn` and `resetServerFnMocks` for client tests, exported from `@tanstack/react-start/testing`, `@tanstack/solid-start/testing` and `@tanstack/vue-start/testing`. Experimental. + +A client test has no server. When Vitest compiles a project with Start's plugin, a server function call in client code no longer sends a request. It goes to the mock a test registered for that function, and fails with an error that names the function when there is none. + +```ts +import { mockServerFn } from '@tanstack/react-start/testing' + +test('greets', async () => { + mockServerFn(greet, ({ data }) => `Hello ${data}`) + // ... +}) +``` + +A mock that a test registers ends with that test. Start's plugin adds a setup file to every Vitest project for this. `resetServerFnMocks` removes mocks earlier. + +The mock is typed from the server function: it gets the `data` the function is called with, and has to return what the function's handler returns. It stands for the server side of the function (its server middleware, validator and handler); the function's client middleware runs as in the app. Unlike a module mock, it also answers a call made in the file that defines the server function. diff --git a/.changeset/start-server-test-harness.md b/.changeset/start-server-test-harness.md new file mode 100644 index 0000000000..a1226bd5c8 --- /dev/null +++ b/.changeset/start-server-test-harness.md @@ -0,0 +1,37 @@ +--- +'@tanstack/start-server-core': minor +'@tanstack/start-client-core': minor +'@tanstack/start-plugin-core': minor +'@tanstack/start-storage-context': patch +'@tanstack/react-start': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +--- + +Add `runInRequest`, `mockMiddleware` and `runMiddleware` for server tests, exported from `@tanstack/react-start/testing/server`, `@tanstack/solid-start/testing/server` and `@tanstack/vue-start/testing/server`. Experimental. + +```ts +import { + mockMiddleware, + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' + +test('likePost counts a like', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + expect(await likePost({ data: '1' })).toBe(1) + expect(getResponseHeader('cache-control')).toBe('no-store') + }) +}) +``` + +- `runInRequest` runs a callback as the code that handles one request. The request middleware of `src/start.ts` runs first. A server function call inside the callback runs as a loader's call does during server rendering: its middleware, its validator and its handler. Start's request and response helpers work inside the callback. `globalMiddleware: 'skip'` leaves the middleware of `src/start.ts` out and takes a `context` that is typed from the start instance. +- `mockMiddleware` replaces a middleware with a function that is typed from it. A mock ends with the test that registered it, or with the request when it was registered inside `runInRequest`. +- `runMiddleware` calls the server function of one middleware, for a function middleware and for a request middleware. + +A server function that a test calls outside of `runInRequest` fails with an error that names `runInRequest`. + +Fixes for test runs: + +- A server test could not call a server function when Vitest served the calling module from its module cache, which is the default from the second run on. The call failed with "Invalid server function ID". In a test run the server now finds a function by its id alone. +- A project without a router entry could not load `@tanstack/react-start/server` in a server test (`Missing "#tanstack-router-entry" specifier`). diff --git a/.changeset/start-vitest-test-runs.md b/.changeset/start-vitest-test-runs.md new file mode 100644 index 0000000000..16da837679 --- /dev/null +++ b/.changeset/start-vitest-test-runs.md @@ -0,0 +1,15 @@ +--- +'@tanstack/start-plugin-core': minor +'@tanstack/router-plugin': minor +'@tanstack/router-generator': minor +--- + +Start's Vite plugin can be used in a Vitest config. When Vitest resolves the config to run tests, the plugin compiles the code as it does in the app (`createServerFn`, `createIsomorphicFn`, `createServerOnlyFn`, `createClientOnlyFn`, the server-only route options), for the client in browser mode and in jsdom or happy-dom, and for the server in the Node environment. It does not set up the app's dev server, preview server or build. + +- A project needs no router entry and no routes. A package that only uses Start's compile-time APIs used to fail with "Could not resolve entry for router entry". +- The route tree is generated once, when Vitest starts, and only for a project with a router entry and a root route. It is not regenerated while Vitest watches. +- A test run never writes route files: a route file with an outdated route path and an empty route file are left as they are, with a warning. +- A module that calls `createFileRoute`, `createRootRoute` or `createRootRouteWithContext` loses its `server`, `ssr` and `headers` options in client code even when the route generator does not know the module. +- Start's own packages go through the Start compiler in jsdom, happy-dom and Node tests of a project that installs them from the registry. Vitest's translation of the wildcards in `resolve.noExternal` misses a package name with a dash, so `@tanstack/start-client-core` ran uncompiled and a server function call in a client test failed with "No Start context found in AsyncLocalStorage". In a test run Start now names its packages with regular expressions. + +For this, `Generator` of `@tanstack/router-generator` takes `writeRouteFiles: false`, and `tanstackRouterGenerator` and `tanStackRouterCodeSplitter` of `@tanstack/router-plugin/vite` take options for the plugin that embeds them. diff --git a/docs/start/config.json b/docs/start/config.json index 36af0e6e0d..0e8946253e 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -129,6 +129,10 @@ { "label": "Server Routes", "to": "framework/react/guide/server-routes" + }, + { + "label": "Testing", + "to": "framework/react/guide/testing" } ] }, diff --git a/docs/start/framework/react/guide/testing.md b/docs/start/framework/react/guide/testing.md new file mode 100644 index 0000000000..5323575dc4 --- /dev/null +++ b/docs/start/framework/react/guide/testing.md @@ -0,0 +1,554 @@ +--- +id: testing +title: Testing +--- + +> **Experimental:** Start's support for test runners is experimental and subject to change. It works with Vitest. + +Start's Vite plugin compiles your code for the environment it runs in. In client code a server function becomes a request to the server, and an isomorphic function keeps its client implementation. Code that only the server uses is removed, together with its imports. Tests need the same compilation: without it, a client test imports your database client and every other module that only the server can load. + +When Vitest loads a config that contains `tanstackStart()`, the plugin compiles your code as it does in the app. It leaves out the parts that serve or build the app, so a test run starts no dev server and needs no built output. + +The examples on this page use React. `@tanstack/solid-start` and `@tanstack/vue-start` export the same functions from the same subpaths. + +## Setup + +Add `tanstackStart()` to the config your tests use. An app can use one `vite.config.ts` for the app and for its tests: + +```ts title="vite.config.ts" +import { defineConfig } from 'vitest/config' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { playwright } from '@vitest/browser-playwright' + +export default defineConfig({ + plugins: [tanstackStart(), react()], + test: { + projects: [ + { + extends: true, + test: { + name: 'client', + include: ['tests/**/*.client.test.{ts,tsx}'], + browser: { + enabled: true, + provider: playwright(), + instances: [{ browser: 'chromium' }], + }, + }, + }, + { + extends: true, + test: { + name: 'server', + environment: 'node', + include: ['tests/**/*.server.test.ts'], + }, + }, + ], + }, +}) +``` + +The two projects and the file names are a convention of this example. A test file is compiled for the environment its project runs in. + +A package that only uses Start's APIs, such as a shared library of server functions, uses the same config. In a test run the plugin does not ask for a router entry or for routes. + +Start treats a run as a test run when Vitest resolves the config in its default mode, `test`. With another mode (`vitest --mode staging`) the plugin sets up the app's dev server as usual. + +## Which code a test gets + +| Test environment | Code the test gets | +| ----------------------------------------------------------------------- | ------------------ | +| [Browser mode](https://vitest.dev/guide/browser/), `jsdom`, `happy-dom` | Client | +| `node` | Server | + +Take a module with an isomorphic function whose server implementation reads a secret: + +```ts title="src/runtime.ts" +import { createIsomorphicFn } from '@tanstack/react-start' +import { readSecret } from './secrets.server' + +export const describeRuntime = createIsomorphicFn() + .server(() => `server with ${readSecret()}`) + .client(() => 'client') +``` + +In a client test `describeRuntime()` returns `'client'`, and `./secrets.server` is never loaded. In a server test it runs the server implementation. + +`createServerOnlyFn` and `createClientOnlyFn` behave as in the app too: the function runs in its own environment and throws in the other one. + +## Routes in a test run + +A test can import a route file or the generated route tree. + +The route tree is generated once, when Vitest starts, and only for a project that has a router entry and a root route. It is not regenerated while Vitest watches. After you add, move or delete a route file, restart Vitest. + +A test run never writes to your route files. The dev server fills in an empty route file and corrects the path in a file you moved. A test run leaves both as they are and logs a warning. + +In client code a route loses its `server`, `ssr` and `headers` options, as in the app. That holds for every module that calls `createFileRoute`, `createRootRoute` or `createRootRouteWithContext`, including one outside the routes directory. + +## Mocking server functions in client tests + +A client test has no server. When client code calls a server function in a test run, no request is sent. The call goes to a mock that the test registered for that function with `mockServerFn`. + +Take a route whose loader gets a post from a server function: + +```ts title="src/posts.ts" +import { notFound } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { findPost } from './db.server' + +export const fetchPost = createServerFn() + .validator((postId: string) => postId) + .handler(async ({ data }) => { + const post = await findPost(data) + if (!post) { + throw notFound() + } + return post + }) +``` + +```tsx title="src/routes/posts.$postId.tsx" +import { createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../posts' + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ params }) => fetchPost({ data: params.postId }), + component: PostPage, +}) + +function PostPage() { + const post = Route.useLoaderData() + + return

{post.title}

+} +``` + +The test renders the route. The mock answers the loader's call in place of the server: + +```tsx title="tests/post-page.client.test.tsx" +import { cleanup, render, screen } from '@testing-library/react' +import { + RouterProvider, + createMemoryHistory, + createRouter, +} from '@tanstack/react-router' +import { mockServerFn } from '@tanstack/react-start/testing' +import { afterEach, expect, test } from 'vitest' +import { fetchPost } from '../src/posts' +import { routeTree } from '../src/routeTree.gen' + +afterEach(() => { + cleanup() +}) + +test('the post page shows the title of the post', async () => { + mockServerFn(fetchPost, ({ data }) => ({ + id: data, + title: 'Testing with TanStack Start', + })) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts/42'] }), + }) + + render() + + expect((await screen.findByRole('heading')).textContent).toBe( + 'Testing with TanStack Start', + ) +}) +``` + +The mock stands for the server side of the function: its server middleware, its validator and its handler. It is called where the app would send the request, so the function's client middleware runs as in the app, before the mock and after it. + +A mock also answers a call that is made in the module that defines the server function. A module mock (`vi.mock`) cannot replace such a call, because it only changes what other modules import. + +A call to a server function that has no mock fails with an error that names the function: + +``` +The server function "fetchPost" (/src/posts.ts) was called in a client test, where no server runs. Answer the call with mockServerFn() before it is made. +``` + +### `mockServerFn(serverFn, mock)` + +Registers `mock` as the answer to every call of `serverFn`. A mock that a test registers ends with that test, see [How long a mock lasts](#how-long-a-mock-lasts). A second call for the same function replaces the first mock. + +`mock` is typed from the server function. It gets one object: + +| Property | Type | Value | +| --------- | -------------------------- | ------------------------------------------------------------------------------ | +| `data` | The function's input | The `data` of the call, as the caller passed it. The validator has not run. | +| `method` | `'GET' \| 'POST'` | The method of the server function. | +| `headers` | `Headers` | The headers of the call, with the ones the function's client middleware added. | +| `signal` | `AbortSignal \| undefined` | The signal of the call. | + +`mock` returns what the call resolves to, or a promise for it. The return type is the handler's return type, literal types included: a mock of a handler that returns `{ status: 'ok' }` has to return exactly that. The value reaches the caller as it is. It is not passed through the serializer, so the test does not notice a value that the server could not send, such as a function. + +What `mock` throws rejects the call. To test how your code handles a redirect or a failed call, throw `redirect(...)` or an error in the mock. + +To check how a server function was called, pass a mock function of your test runner. Take a button that likes a post. `likePost` is a server function that takes the id of a post and returns its new number of likes: + +```tsx title="src/components/LikeButton.tsx" +import { useState } from 'react' +import { likePost } from '../posts' + +export function LikeButton({ postId }: { postId: string }) { + const [likes, setLikes] = useState() + + return ( + + ) +} +``` + +```tsx title="tests/like-button.client.test.tsx" +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { mockServerFn } from '@tanstack/react-start/testing' +import { afterEach, expect, test, vi } from 'vitest' +import { LikeButton } from '../src/components/LikeButton' +import { likePost } from '../src/posts' + +afterEach(() => { + cleanup() +}) + +test('likes the post and shows the new count', async () => { + const like = vi.fn(() => 5) + mockServerFn(likePost, like) + render() + + fireEvent.click(screen.getByRole('button', { name: 'Like' })) + + expect(await screen.findByRole('button', { name: '5 likes' })).toBeDefined() + expect(like).toHaveBeenCalledWith(expect.objectContaining({ data: '42' })) +}) +``` + +`mockServerFn` works in client tests only. In a server test it throws, because the function was not compiled for the client. A server test runs the function itself, as the next section shows. + +### `resetServerFnMocks()` + +Removes every mock that `mockServerFn` registered. Start ends the mocks of a test when the test ends, so most tests never call it. Use it to remove mocks before a test ends, for example to check that a call without a mock fails. + +## Testing server functions and middleware in server tests + +In a server test your code runs as it does on the server, and a server function runs in full: its middleware, its validator and its handler. The helpers for server tests come from `@tanstack/react-start/testing/server`. + +### Calling a server function + +On the server, a server function runs for a request. It reads the cookies of that request, sets headers on the response, and gets context from the middleware that ran before it. A server function that a test calls outside of a request fails: + +``` +No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime. In a test, run this code inside runInRequest(), which the testing/server entry of your Start package exports (for example '@tanstack/react-start/testing/server'). +``` + +`runInRequest` runs a callback as the code that handles one request to your server. Take `fetchPost` and `likePost` from above. `likePost` uses a middleware that finds the user of the session cookie: + +```ts title="src/middleware/auth.ts" +import { createMiddleware } from '@tanstack/react-start' +import { getCookie } from '@tanstack/react-start/server' +import { findUserBySession } from '../db.server' + +export const authMiddleware = createMiddleware({ type: 'function' }).server( + async ({ next }) => { + const user = await findUserBySession(getCookie('session')) + if (!user) { + throw new Error('Not signed in') + } + return next({ context: { user } }) + }, +) +``` + +```ts title="src/posts.ts" +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { addLike } from './db.server' +import { authMiddleware } from './middleware/auth' + +export const likePost = createServerFn({ method: 'POST' }) + .middleware([authMiddleware]) + .validator((postId: string) => postId) + .handler(async ({ data, context }) => { + setResponseHeader('cache-control', 'no-store') + // Counts each user once and returns the number of likes. + return addLike(data, context.user.id) + }) +``` + +```ts title="tests/posts.server.test.ts" +import { getResponseHeader } from '@tanstack/react-start/server' +import { runInRequest } from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { fetchPost, likePost } from '../src/posts' + +test('fetchPost returns the post', async () => { + const post = await runInRequest(() => fetchPost({ data: '1' })) + + expect(post.title).toBe('The first post') +}) + +test('fetchPost fails for a post that does not exist', async () => { + await expect( + runInRequest(() => fetchPost({ data: 'unknown' })), + ).rejects.toMatchObject({ isNotFound: true }) +}) + +test('likePost counts a user once', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + expect(await likePost({ data: '1' })).toBe(1) + expect(await likePost({ data: '1' })).toBe(1) + + expect(getResponseHeader('cache-control')).toBe('no-store') + }) +}) + +test('likePost refuses a request without a session', async () => { + await expect(runInRequest(() => likePost({ data: '1' }))).rejects.toThrow( + 'Not signed in', + ) +}) +``` + +The handlers in these tests use the real `./db.server`. A server test loads your server code as it is, so the test has to provide the data that code reads, for example a test database with a post `1` and a session `ada`. + +Each server function call inside the callback runs like a call that a loader makes while the server renders a page. The middleware of the function runs, client functions first and server functions after them, then the validator and the handler. The data and the result are passed as they are and do not go through the serializer. + +Start's request and response helpers work inside the callback: `getRequest`, `getCookie`, `setResponseHeader`, `getResponseHeader` and the other functions of `@tanstack/react-start/server`. A test can call several server functions in one request and check the response between the calls, as the third test does. + +### `runInRequest(options, callback)` + +Runs `callback` for one request. It resolves to what the callback returns and rejects with what the callback throws. `options` can be left out: `runInRequest(callback)`. + +| Option | Type | Value | +| ------------------ | -------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `url` | `string \| URL` | The URL of the request. A relative URL is resolved against `http://localhost`. The default is `/`. | +| `method` | `string` | The method of the request. The default is `GET`. | +| `headers` | `HeadersInit` | The headers of the request. Cookies go into the `cookie` header. | +| `request` | `Request` | A request that is used as it is. It takes the place of `url`, `method` and `headers`. | +| `context` | Your request context | The context your server entry passes to Start with a request. It is required when your app registers a request context. | +| `globalMiddleware` | `'skip'` | Leaves out the middleware of `src/start.ts`. [Global middleware](#global-middleware) describes it. | + +The request counts as a request for a page. Request middleware gets `handlerType: 'router'`, so a middleware that only acts on server function requests lets it through. The CSRF middleware in its usual setup is one of them. + +`getRouterInstance()` returns the router of your router entry, at the URL of the request. + +### Global middleware + +`runInRequest` runs the request middleware of `src/start.ts` before the callback, and the function middleware of `src/start.ts` with each server function call. Take an app whose request middleware reads the language of the request: + +```ts title="src/start.ts" +import { createMiddleware, createStart } from '@tanstack/react-start' + +type Locale = 'en' | 'de' + +const localeMiddleware = createMiddleware().server(({ next, request }) => { + const locale: Locale = request.headers + .get('accept-language') + ?.startsWith('de') + ? 'de' + : 'en' + return next({ context: { locale } }) +}) + +export const startInstance = createStart(() => ({ + requestMiddleware: [localeMiddleware], +})) +``` + +If the handler of `fetchPost` looks the post up with `findPost(data, context.locale)`, a test chooses the language with a header: + +```ts +test('fetchPost returns the post in the language of the request', async () => { + const post = await runInRequest( + { headers: { 'accept-language': 'de-DE' } }, + () => fetchPost({ data: '1' }), + ) + + expect(post.title).toBe('Der erste Beitrag') +}) +``` + +When a request middleware answers the request itself or throws, the callback does not run and `runInRequest` rejects. It rejects with what the middleware threw, or with an error that has the middleware's response as its `cause`. + +To keep the global middleware out of a test, pass `globalMiddleware: 'skip'`. Neither list of `src/start.ts` runs then. `context` takes the place of the context the two lists pass on: + +```ts +test('fetchPost returns the English post', async () => { + const post = await runInRequest( + { globalMiddleware: 'skip', context: { locale: 'en' } }, + () => fetchPost({ data: '1' }), + ) + + expect(post.title).toBe('The first post') +}) +``` + +The type of `context` comes from your start instance. TypeScript reports a missing property and a value the middleware could not have produced, such as `locale: 'fr'` here. The option needs no reference to a middleware, so it also works for middleware that `src/start.ts` does not export. A server function that lists one of the global middleware itself still runs it. + +### `mockMiddleware(middleware, mock)` + +Replaces a middleware in server tests. `likePost` needs a session, and the test below puts a user in its place: + +```ts title="tests/posts.server.test.ts" +import { + mockMiddleware, + runInRequest, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { authMiddleware } from '../src/middleware/auth' +import { likePost } from '../src/posts' + +test('likePost counts the like of a user', async () => { + mockMiddleware(authMiddleware, ({ next }) => + next({ context: { user: { id: 'u2', name: 'Grace' } } }), + ) + + await expect(runInRequest(() => likePost({ data: '2' }))).resolves.toBe(1) +}) +``` + +`mock` stands for the server function of the middleware and is typed from it. It gets what that function gets: `data`, `context`, `method`, `serverFnMeta`, `signal` and `next` for a function middleware, and `request`, `pathname`, `context`, `handlerType` and `next` for a request middleware. + +A mock goes on with the call by returning `next()`. When the middleware passes context on, `next` requires that context, because the code after the middleware reads it. A mock can also end the call the way the middleware can: by throwing, or by returning a `Response` in the mock of a request middleware. + +While a middleware is mocked, its client function does not run either. A server test would otherwise run that function in Node, where code written for a browser can fail. + +A mock registered inside the callback of `runInRequest` belongs to that request. It takes precedence over a mock of the test, and it ends with the request. If nothing in the request ran it, `runInRequest` rejects, because a mock that never runs usually means the test does not exercise what it was written for. + +The request middleware of `src/start.ts` has already run when the callback starts. Mock one of them before you call `runInRequest`. + +`mockMiddleware` replaces one middleware object. On the server, Start loads the file of a server function a second time, for the server side of the function. A middleware that is created in that file therefore exists twice, and a mock reaches only one of the two. Create a middleware that tests replace in a file of its own, like `src/middleware/auth.ts` above. + +### `runMiddleware(middleware, input, next)` + +Calls the server function of one middleware and nothing else. The middleware that it lists itself does not run, and neither does its validator or its client function. Call it inside `runInRequest`, which provides the request. + +```ts title="tests/auth.server.test.ts" +import { + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { authMiddleware } from '../src/middleware/auth' + +test('authMiddleware passes the user of the session on', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + const { context } = await runMiddleware(authMiddleware, {}) + + expect(context.user).toEqual({ id: 'u1', name: 'Ada' }) + }) +}) + +test('authMiddleware refuses a request without a session', async () => { + await runInRequest(async () => { + await expect(runMiddleware(authMiddleware, {})).rejects.toThrow( + 'Not signed in', + ) + }) +}) +``` + +`input` is what the server function of the middleware receives. Its type comes from the middleware. + +| Property | For | Value | +| -------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `data` | Function middleware | The validated data. It is required when the middleware or a middleware it lists has a validator. | +| `context` | Both | The context of the middleware that runs before this one. It is required when that context has a required property. | +| `method` | Function middleware | The method of the server function. The default is `GET`. | +| `signal` | Function middleware | The signal of the call. The default is the signal of the request. | +| `handlerType` | Request middleware | `'router'` for a page request, `'serverFn'` for a server function request. The default is `'router'`. | +| `serverFnMeta` | Both | The id, the name and the file of the server function that the call is for. | + +`next` is optional. It stands for everything that runs after the middleware, and it gets what the middleware passed on. For a function middleware it gets `context` and `sendContext`, and what it returns is the result of the call. For a request middleware it gets `context`, `request` and `pathname`, and it returns the `Response` of the request. Without it, the response is an empty one with status 200. + +`runMiddleware` resolves to an object: + +| Property | For | Value | +| ------------- | ------------------- | ----------------------------------------------------------------------------------------------- | +| `context` | Both | The context after the middleware: what it received and what it added. | +| `sendContext` | Function middleware | The context the middleware sends back to the client. | +| `result` | Function middleware | What `next` returned. | +| `response` | Request middleware | The response the middleware answers the request with: its own, or the one that `next` returned. | + +A request middleware often changes the response of the request. Take a middleware that derives a tenant from the host name: + +```ts title="src/middleware/tenant.ts" +import { createMiddleware } from '@tanstack/react-start' + +export const tenantMiddleware = createMiddleware().server( + async ({ next, request }) => { + const tenant = new URL(request.url).hostname.split('.')[0]! + if (tenant === 'www') { + return new Response('No tenant', { status: 404 }) + } + const result = await next({ context: { tenant } }) + result.response.headers.set('x-tenant', tenant) + return result + }, +) +``` + +```ts title="tests/tenant.server.test.ts" +import { + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test, vi } from 'vitest' +import { tenantMiddleware } from '../src/middleware/tenant' + +test('tenantMiddleware names the tenant in the context and in a header', async () => { + await runInRequest({ url: 'https://acme.example.com/posts' }, async () => { + const { context, response } = await runMiddleware( + tenantMiddleware, + {}, + ({ context }) => new Response(`Posts of ${context.tenant}`), + ) + + expect(context).toEqual({ tenant: 'acme' }) + expect(response.headers.get('x-tenant')).toBe('acme') + await expect(response.text()).resolves.toBe('Posts of acme') + }) +}) + +test('tenantMiddleware answers a request without a tenant itself', async () => { + await runInRequest({ url: 'https://www.example.com/posts' }, async () => { + const next = vi.fn() + const { response } = await runMiddleware(tenantMiddleware, {}, next) + + expect(response.status).toBe(404) + expect(next).not.toHaveBeenCalled() + }) +}) +``` + +A `Response` that a request middleware throws counts as its answer, as in the app, so `response` holds it. What a function middleware throws rejects the call. + +If `tenantMiddleware` is listed in `src/start.ts`, `runInRequest` also runs it for the request of the test, before the callback. For the second test that run would end the request. Such a test passes `globalMiddleware: 'skip'`. + +`runMiddleware` calls the real server function of a middleware, also while `mockMiddleware` replaces that middleware. + +## How long a mock lasts + +Start's plugin adds a setup file to every Vitest project. The file ends a mock of `mockServerFn` or `mockMiddleware` together with the test that registered it: + +- A mock registered in a test, or in a `beforeEach` hook, lasts until that test ends. +- A mock registered at the top of a test file, or in a `beforeAll` hook, lasts for the whole file. +- A mock registered with `mockMiddleware` inside the callback of `runInRequest` lasts until that request ends. + +Start adds the file through a plugin hook that Vitest has had since version 3.1. + +Tests that run at the same time (`test.concurrent`) share the mocks that are registered outside of `runInRequest`, and the first test that ends removes them for the others. In such tests, register a middleware mock inside the callback of `runInRequest`: each request keeps its own mocks. A mock of `mockServerFn` has no such scope, so concurrent client tests should not mock the same server function in different ways. + +## Limits + +- Vitest is the only supported test runner. +- `runInRequest` sends no HTTP request. A server function call inside it skips the serializer, and a test cannot call a server route through it. +- A test cannot call the handler of a server function without its middleware and its validator. To take a middleware out of the way, replace it with `mockMiddleware`. +- `mockMiddleware` cannot replace a middleware that is created in the same file as a server function that uses it. +- The route tree is not regenerated while Vitest watches. diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index f373ecba4f..22c7d3ad92 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -7,3 +7,4 @@ - For new browser tests, reuse the local error-checking fixture. The shared `test` from `@tanstack/router-e2e-utils` fails on unexpected `console.error`, including hydration errors; allow only expected errors with `whitelistErrors`. - HMR/watch tests edit real app sources. Reuse existing edit/restore helpers such as `createHmrFileEditor`, restore edits in teardown even after failures, and preserve the suites' single-worker and Nx `parallelism: false` settings. - `@tanstack/router-e2e-utils:test:unit` is a placeholder. Validate helper changes through consuming e2e projects. +- An e2e project resolves `@tanstack/*` to links into `packages/*`, which Vite and Vitest treat as source code: always compiled, never externalized. A user has them in `node_modules`. For changes to what our plugins tell a bundler or a test runner about dependencies (`resolve.noExternal`, `resolve.external`, `optimizeDeps`, inline lists), run the project as a user's project too with [`scripts/e2e/run-as-installed.mjs`](../scripts/e2e/run-as-installed.md); `e2e/react-start/vitest-*` do so in `test:e2e`. diff --git a/e2e/react-start/vitest-app/.gitignore b/e2e/react-start/vitest-app/.gitignore new file mode 100644 index 0000000000..e915670a21 --- /dev/null +++ b/e2e/react-start/vitest-app/.gitignore @@ -0,0 +1,7 @@ +node_modules +.DS_Store +dist +.output +.tanstack +*.local +__screenshots__ diff --git a/e2e/react-start/vitest-app/package.json b/e2e/react-start/vitest-app/package.json new file mode 100644 index 0000000000..5ab825b383 --- /dev/null +++ b/e2e/react-start/vitest-app/package.json @@ -0,0 +1,44 @@ +{ + "name": "tanstack-react-start-e2e-vitest-app", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "test:e2e": "pnpm run test:e2e:types && pnpm run test:e2e:linked && pnpm run test:e2e:cached && pnpm run test:e2e:installed", + "test:e2e:types": "tsc --noEmit", + "test:e2e:linked": "vitest --clearCache && vitest run", + "test:e2e:cached": "vitest run", + "test:e2e:installed": "node ../../../scripts/e2e/run-as-installed.mjs vitest run" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@testing-library/react": "catalog:", + "@types/node": "^22.10.2", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@vitejs/plugin-react": "catalog:", + "@vitest/browser-playwright": "5.0.4", + "jsdom": "catalog:", + "playwright": "^1.63.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "catalog:", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "test:e2e": { + "inputs": [ + "buildProduction", + "^production", + "dependentTaskOutputs", + "{workspaceRoot}/scripts/e2e/run-as-installed.mjs" + ] + } + } + } +} diff --git a/e2e/react-start/vitest-app/src/components/LikeButton.tsx b/e2e/react-start/vitest-app/src/components/LikeButton.tsx new file mode 100644 index 0000000000..36a3864a1a --- /dev/null +++ b/e2e/react-start/vitest-app/src/components/LikeButton.tsx @@ -0,0 +1,12 @@ +import { useState } from 'react' +import { likePost } from '../posts' + +export function LikeButton({ postId }: { postId: string }) { + const [likes, setLikes] = useState() + + return ( + + ) +} diff --git a/e2e/react-start/vitest-app/src/embedded/root.tsx b/e2e/react-start/vitest-app/src/embedded/root.tsx new file mode 100644 index 0000000000..d7781ef5c5 --- /dev/null +++ b/e2e/react-start/vitest-app/src/embedded/root.tsx @@ -0,0 +1,25 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' +import { readSecret } from '../server-only' + +// The root of a second route tree that is built by hand, for a part of the +// app that is embedded elsewhere. It is not in the routes directory, so the +// route generator never sees this module. +export const Route = createRootRoute({ + // Only the server uses the three options below. + server: { + handlers: { + GET: () => new Response(readSecret()), + }, + }, + headers: () => ({ 'x-secret-length': String(readSecret().length) }), + ssr: 'data-only', + component: EmbeddedRoot, +}) + +function EmbeddedRoot() { + return ( +
+ +
+ ) +} diff --git a/e2e/react-start/vitest-app/src/middleware/auth.ts b/e2e/react-start/vitest-app/src/middleware/auth.ts new file mode 100644 index 0000000000..3adbc956e3 --- /dev/null +++ b/e2e/react-start/vitest-app/src/middleware/auth.ts @@ -0,0 +1,13 @@ +import { createMiddleware } from '@tanstack/react-start' +import { getCookie } from '@tanstack/react-start/server' +import { findUserBySession } from '../server-only' + +export const authMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + const user = findUserBySession(getCookie('session')) + if (!user) { + throw new Error('Not signed in') + } + return next({ context: { user } }) + }, +) diff --git a/e2e/react-start/vitest-app/src/posts.ts b/e2e/react-start/vitest-app/src/posts.ts new file mode 100644 index 0000000000..90a13cb7e8 --- /dev/null +++ b/e2e/react-start/vitest-app/src/posts.ts @@ -0,0 +1,23 @@ +import { notFound } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { authMiddleware } from './middleware/auth' +import { addLike, findPost } from './server-only' + +export const fetchPost = createServerFn() + .validator((postId: string) => postId) + .handler(({ data, context }) => { + const post = findPost(data, context.locale) + if (!post) { + throw notFound() + } + return post + }) + +export const likePost = createServerFn({ method: 'POST' }) + .middleware([authMiddleware]) + .validator((postId: string) => postId) + .handler(({ data, context }) => { + setResponseHeader('cache-control', 'no-store') + return addLike(data, context.user.id) + }) diff --git a/e2e/react-start/vitest-app/src/routeTree.gen.ts b/e2e/react-start/vitest-app/src/routeTree.gen.ts new file mode 100644 index 0000000000..ae3849a161 --- /dev/null +++ b/e2e/react-start/vitest-app/src/routeTree.gen.ts @@ -0,0 +1,105 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ApiHealthRouteImport } from './routes/api/health' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiHealthRoute = ApiHealthRouteImport.update({ + id: '/api/health', + path: '/api/health', + getParentRoute: () => rootRouteImport, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/posts/$postId', + path: '/posts/$postId', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/health': typeof ApiHealthRoute + '/posts/$postId': typeof PostsPostIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/health': typeof ApiHealthRoute + '/posts/$postId': typeof PostsPostIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/health': typeof ApiHealthRoute + '/posts/$postId': typeof PostsPostIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/health' | '/posts/$postId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/health' | '/posts/$postId' + id: '__root__' | '/' | '/api/health' | '/posts/$postId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiHealthRoute: typeof ApiHealthRoute + PostsPostIdRoute: typeof PostsPostIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/health': { + id: '/api/health' + path: '/api/health' + fullPath: '/api/health' + preLoaderRoute: typeof ApiHealthRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/posts/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiHealthRoute: ApiHealthRoute, + PostsPostIdRoute: PostsPostIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.ts' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/e2e/react-start/vitest-app/src/router.tsx b/e2e/react-start/vitest-app/src/router.tsx new file mode 100644 index 0000000000..58f4d54e88 --- /dev/null +++ b/e2e/react-start/vitest-app/src/router.tsx @@ -0,0 +1,6 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/e2e/react-start/vitest-app/src/routes/__root.tsx b/e2e/react-start/vitest-app/src/routes/__root.tsx new file mode 100644 index 0000000000..e835ba678f --- /dev/null +++ b/e2e/react-start/vitest-app/src/routes/__root.tsx @@ -0,0 +1,16 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/e2e/react-start/vitest-app/src/routes/api/health.ts b/e2e/react-start/vitest-app/src/routes/api/health.ts new file mode 100644 index 0000000000..961d0911ae --- /dev/null +++ b/e2e/react-start/vitest-app/src/routes/api/health.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { readSecret } from '../../server-only' + +// A route with nothing for the client: Start leaves it out of the client's route tree. +export const Route = createFileRoute('/api/health')({ + server: { + handlers: { + GET: () => Response.json({ ok: true, secret: readSecret() }), + }, + }, +}) diff --git a/e2e/react-start/vitest-app/src/routes/index.tsx b/e2e/react-start/vitest-app/src/routes/index.tsx new file mode 100644 index 0000000000..db792756d1 --- /dev/null +++ b/e2e/react-start/vitest-app/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

+ + First post + +
+ ) +} diff --git a/e2e/react-start/vitest-app/src/routes/posts.$postId.tsx b/e2e/react-start/vitest-app/src/routes/posts.$postId.tsx new file mode 100644 index 0000000000..08987b34ce --- /dev/null +++ b/e2e/react-start/vitest-app/src/routes/posts.$postId.tsx @@ -0,0 +1,27 @@ +import { createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../posts' +import { readSecret } from '../server-only' + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ params }) => fetchPost({ data: params.postId }), + // Only the server uses the three options below. + server: { + handlers: { + POST: ({ params }) => + Response.json({ postId: params.postId, secret: readSecret() }), + }, + }, + headers: () => ({ 'x-secret-length': String(readSecret().length) }), + ssr: 'data-only', + component: PostPage, +}) + +function PostPage() { + const post = Route.useLoaderData() + + return ( +
+

{post.title}

+
+ ) +} diff --git a/e2e/react-start/vitest-app/src/server-only.ts b/e2e/react-start/vitest-app/src/server-only.ts new file mode 100644 index 0000000000..273722e9c5 --- /dev/null +++ b/e2e/react-start/vitest-app/src/server-only.ts @@ -0,0 +1,58 @@ +// Stands for code that must never load in a browser: a database client, a +// secret, a Node API. Loading it leaves a mark that tests can look for. +declare global { + var __SERVER_ONLY_MODULE_LOADED__: boolean | undefined +} + +globalThis.__SERVER_ONLY_MODULE_LOADED__ = true + +export function readSecret() { + return 'the server secret' +} + +export type Locale = 'en' | 'de' + +export interface Post { + id: string + title: string +} + +export interface User { + id: string + name: string +} + +const posts = new Map>([ + ['1', { en: 'The first post', de: 'Der erste Beitrag' }], + ['2', { en: 'The second post', de: 'Der zweite Beitrag' }], + ['3', { en: 'The third post', de: 'Der dritte Beitrag' }], +]) +const users = new Map([['ada', { id: 'u1', name: 'Ada' }]]) +const likes = new Map>() +const calls: Array = [] + +export function findPost(id: string, locale: Locale): Post | undefined { + const titles = posts.get(id) + return titles && { id, title: titles[locale] } +} + +/** The user of a session cookie. */ +export function findUserBySession(session: string | undefined) { + return session ? users.get(session) : undefined +} + +/** Counts each user once. Returns the number of likes of the post. */ +export function addLike(postId: string, userId: string): number { + const users = likes.get(postId) ?? new Set() + likes.set(postId, users.add(userId)) + return users.size +} + +/** The audit log of the app: the server functions that were called. */ +export function recordCall(name: string) { + calls.push(name) +} + +export function recordedCalls(): ReadonlyArray { + return calls +} diff --git a/e2e/react-start/vitest-app/src/start.ts b/e2e/react-start/vitest-app/src/start.ts new file mode 100644 index 0000000000..7511caa077 --- /dev/null +++ b/e2e/react-start/vitest-app/src/start.ts @@ -0,0 +1,27 @@ +import { createMiddleware, createStart } from '@tanstack/react-start' +import { recordCall } from './server-only' +import type { Locale } from './server-only' + +// The global middleware of the app. It is not exported, as in most apps. +// tests/posts.server.test.ts shows how a test runs it and how a test leaves +// it out. +const localeMiddleware = createMiddleware().server(({ next, request }) => { + const locale: Locale = request.headers + .get('accept-language') + ?.startsWith('de') + ? 'de' + : 'en' + return next({ context: { locale } }) +}) + +const auditMiddleware = createMiddleware({ type: 'function' }).server( + ({ next, serverFnMeta }) => { + recordCall(serverFnMeta.name) + return next() + }, +) + +export const startInstance = createStart(() => ({ + requestMiddleware: [localeMiddleware], + functionMiddleware: [auditMiddleware], +})) diff --git a/e2e/react-start/vitest-app/tests/jsdom.setup.ts b/e2e/react-start/vitest-app/tests/jsdom.setup.ts new file mode 100644 index 0000000000..0af0e221e5 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/jsdom.setup.ts @@ -0,0 +1,3 @@ +// jsdom has no layout, so it cannot scroll. The router scrolls to the top +// after a navigation. +window.scrollTo = () => {} diff --git a/e2e/react-start/vitest-app/tests/like-button.client.test.tsx b/e2e/react-start/vitest-app/tests/like-button.client.test.tsx new file mode 100644 index 0000000000..e36128e8d7 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/like-button.client.test.tsx @@ -0,0 +1,21 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { mockServerFn } from '@tanstack/react-start/testing' +import { afterEach, expect, test, vi } from 'vitest' +import { LikeButton } from '../src/components/LikeButton' +import { likePost } from '../src/posts' + +afterEach(() => { + cleanup() +}) + +test('a component sends its data to a server function and shows the answer', async () => { + const like = vi.fn(() => 5) + mockServerFn(likePost, like) + render() + + fireEvent.click(screen.getByRole('button', { name: 'Like' })) + + expect(await screen.findByRole('button', { name: '5 likes' })).toBeDefined() + expect(like).toHaveBeenCalledOnce() + expect(like).toHaveBeenCalledWith(expect.objectContaining({ data: '42' })) +}) diff --git a/e2e/react-start/vitest-app/tests/posts.server.test.ts b/e2e/react-start/vitest-app/tests/posts.server.test.ts new file mode 100644 index 0000000000..fb3af174dc --- /dev/null +++ b/e2e/react-start/vitest-app/tests/posts.server.test.ts @@ -0,0 +1,113 @@ +import { getRouterInstance } from '@tanstack/react-start' +import { getResponseHeader } from '@tanstack/react-start/server' +import { + mockMiddleware, + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { authMiddleware } from '../src/middleware/auth' +import { fetchPost, likePost } from '../src/posts' +import { recordedCalls } from '../src/server-only' + +test('runInRequest resolves to what a server function returns', async () => { + const post = await runInRequest(() => fetchPost({ data: '1' })) + + expect(post.title).toBe('The first post') +}) + +test('a server function runs behind the global middleware of src/start.ts', async () => { + const post = await runInRequest( + { headers: { 'accept-language': 'de-DE' } }, + () => fetchPost({ data: '1' }), + ) + + expect(post).toEqual({ id: '1', title: 'Der erste Beitrag' }) + // (the global function middleware of the app wrote its audit log) + expect(recordedCalls()).toContain('fetchPost') +}) + +test('a server function fails as in the app', async () => { + await expect( + runInRequest(() => fetchPost({ data: 'unknown' })), + ).rejects.toMatchObject({ isNotFound: true }) +}) + +test('a test checks between two calls and reads what a handler set on the response', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + expect(await likePost({ data: '1' })).toBe(1) + // (a user counts once) + expect(await likePost({ data: '1' })).toBe(1) + + expect(getResponseHeader('cache-control')).toBe('no-store') + }) +}) + +test('the middleware of a server function refuses a request without a session', async () => { + await expect(runInRequest(() => likePost({ data: '1' }))).rejects.toThrow( + 'Not signed in', + ) +}) + +test('mockMiddleware puts a user of the test in place of the session', async () => { + mockMiddleware(authMiddleware, ({ next }) => + next({ context: { user: { id: 'u2', name: 'Grace' } } }), + ) + + await expect(runInRequest(() => likePost({ data: '2' }))).resolves.toBe(1) +}) + +test('runMiddleware calls a middleware on its own', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + const { context } = await runMiddleware(authMiddleware, {}) + + expect(context.user).toEqual({ id: 'u1', name: 'Ada' }) + }) + + await runInRequest(async () => { + await expect(runMiddleware(authMiddleware, {})).rejects.toThrow( + 'Not signed in', + ) + }) +}) + +test('globalMiddleware: skip leaves the middleware of src/start.ts out', async () => { + const callsBefore = recordedCalls().length + + const post = await runInRequest( + { + // (the header would make the request middleware choose German) + headers: { 'accept-language': 'de-DE' }, + globalMiddleware: 'skip', + context: { locale: 'en' }, + }, + () => fetchPost({ data: '3' }), + ) + + expect(post.title).toBe('The third post') + expect(recordedCalls()).toHaveLength(callsBefore) +}) + +test('the context that stands for the global middleware is typed', () => { + // Checked by `tsc` (`test:e2e:types`), never called. + const check = () => [ + // @ts-expect-error the request middleware of src/start.ts passes a locale on + runInRequest({ globalMiddleware: 'skip' }, () => undefined), + runInRequest( + // @ts-expect-error the app has no French + { globalMiddleware: 'skip', context: { locale: 'fr' } }, + () => undefined, + ), + ] + + expect(check).toBeTypeOf('function') +}) + +test('the router of the app is at the URL of the request', async () => { + await runInRequest({ url: '/posts/1?from=test' }, async () => { + const router = await getRouterInstance() + + expect(router.history.location.href).toBe('/posts/1?from=test') + expect(Object.keys(router.routesById)).toContain('/posts/$postId') + }) +}) diff --git a/e2e/react-start/vitest-app/tests/route-files.client.test.ts b/e2e/react-start/vitest-app/tests/route-files.client.test.ts new file mode 100644 index 0000000000..5fa2dc4820 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/route-files.client.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from 'vitest' +import { Route as HealthRoute } from '../src/routes/api/health' +import { Route as PostRoute } from '../src/routes/posts.$postId' + +test('the options that only the server uses are not in client code', () => { + expect(Object.keys(PostRoute.options).sort()).toEqual(['component', 'loader']) + expect(Object.keys(HealthRoute.options)).toEqual([]) +}) + +test('the module that only server code uses is never loaded', () => { + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() +}) diff --git a/e2e/react-start/vitest-app/tests/route-files.server.test.ts b/e2e/react-start/vitest-app/tests/route-files.server.test.ts new file mode 100644 index 0000000000..c3b4d60113 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/route-files.server.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from 'vitest' +import { Route as HealthRoute } from '../src/routes/api/health' +import { Route as PostRoute } from '../src/routes/posts.$postId' + +test('the options that only the server uses are in server code', () => { + expect(Object.keys(PostRoute.options).sort()).toEqual([ + 'component', + 'headers', + 'loader', + 'server', + 'ssr', + ]) +}) + +test('a server route handler can be called', async () => { + const { handlers } = (HealthRoute.options as any).server + const response: Response = await handlers.GET({ + request: new Request('http://localhost/api/health'), + }) + + expect(await response.json()).toEqual({ + ok: true, + secret: 'the server secret', + }) +}) diff --git a/e2e/react-start/vitest-app/tests/route-modules.client.test.ts b/e2e/react-start/vitest-app/tests/route-modules.client.test.ts new file mode 100644 index 0000000000..22db660d3b --- /dev/null +++ b/e2e/react-start/vitest-app/tests/route-modules.client.test.ts @@ -0,0 +1,10 @@ +import { expect, test } from 'vitest' +import { Route } from '../src/embedded/root' + +test('a route module outside the routes directory has no server-only options in client code', () => { + expect(Object.keys(Route.options)).toEqual(['component']) +}) + +test('the module that only server code uses is never loaded', () => { + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() +}) diff --git a/e2e/react-start/vitest-app/tests/route-modules.server.test.ts b/e2e/react-start/vitest-app/tests/route-modules.server.test.ts new file mode 100644 index 0000000000..231372b0fb --- /dev/null +++ b/e2e/react-start/vitest-app/tests/route-modules.server.test.ts @@ -0,0 +1,11 @@ +import { expect, test } from 'vitest' +import { Route } from '../src/embedded/root' + +test('a route module outside the routes directory keeps its server-only options in server code', () => { + expect(Object.keys(Route.options).sort()).toEqual([ + 'component', + 'headers', + 'server', + 'ssr', + ]) +}) diff --git a/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx b/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx new file mode 100644 index 0000000000..f0018c1074 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx @@ -0,0 +1,42 @@ +import { cleanup, render, screen } from '@testing-library/react' +import { + RouterProvider, + createMemoryHistory, + createRouter, +} from '@tanstack/react-router' +import { mockServerFn } from '@tanstack/react-start/testing' +import { afterEach, expect, test } from 'vitest' +import { fetchPost } from '../src/posts' +import { routeTree } from '../src/routeTree.gen' + +afterEach(() => { + cleanup() +}) + +test('the route tree of the client has no server-only route', () => { + const router = createRouter({ routeTree, history: createMemoryHistory() }) + + expect(Object.keys(router.routesById).sort()).toEqual([ + '/', + '/posts/$postId', + '__root__', + ]) +}) + +test('a route renders what its loader gets from a server function', async () => { + mockServerFn(fetchPost, ({ data }) => ({ + id: data, + title: 'Testing with TanStack Start', + })) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts/42'] }), + }) + + render() + + expect((await screen.findByRole('heading')).textContent).toBe( + 'Testing with TanStack Start', + ) + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() +}) diff --git a/e2e/react-start/vitest-app/tests/route-tree.server.test.ts b/e2e/react-start/vitest-app/tests/route-tree.server.test.ts new file mode 100644 index 0000000000..cc47994485 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/route-tree.server.test.ts @@ -0,0 +1,14 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { expect, test } from 'vitest' +import { routeTree } from '../src/routeTree.gen' + +test('the route tree of the server has every route', () => { + const router = createRouter({ routeTree, history: createMemoryHistory() }) + + expect(Object.keys(router.routesById).sort()).toEqual([ + '/', + '/api/health', + '/posts/$postId', + '__root__', + ]) +}) diff --git a/e2e/react-start/vitest-app/tsconfig.json b/e2e/react-start/vitest-app/tsconfig.json new file mode 100644 index 0000000000..279e9c623c --- /dev/null +++ b/e2e/react-start/vitest-app/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "skipLibCheck": true, + "resolveJsonModule": true, + "noEmit": true, + "types": ["node", "vite/client"] + }, + "include": ["src", "tests", "vite.config.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-start/vitest-app/vite.config.ts b/e2e/react-start/vitest-app/vite.config.ts new file mode 100644 index 0000000000..26c913082e --- /dev/null +++ b/e2e/react-start/vitest-app/vite.config.ts @@ -0,0 +1,58 @@ +import { defineConfig } from 'vitest/config' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { playwright } from '@vitest/browser-playwright' + +// A Start app. The same config serves the app and its tests. +// +// `test:e2e` type-checks the project and runs these tests three times: +// - here, where `@tanstack/*` are links to `packages/*`, with an empty Vitest +// cache (`test:e2e:linked`), +// - here again, now with the compiled modules of the first run in Vitest's +// cache (`test:e2e:cached`): a test run must not depend on the Start +// compiler having seen a file in the same process, +// - in a copy that is installed like a user's project +// (`test:e2e:installed`, `scripts/e2e/run-as-installed.md` says why that +// differs). +export default defineConfig({ + plugins: [tanstackStart(), react()], + test: { + watch: false, + // Vitest keeps the modules it compiled in one cache for the whole + // repository. This project keeps its own, so that `test:e2e:linked` can + // empty it and compile every file with the packages as they are built now. + fsModuleCachePath: 'node_modules/.vitest-cache', + projects: [ + { + extends: true, + test: { + name: 'browser', + include: ['tests/**/*.client.test.ts?(x)'], + browser: { + enabled: true, + headless: true, + provider: playwright(), + instances: [{ browser: 'chromium' }], + }, + }, + }, + { + extends: true, + test: { + name: 'jsdom', + environment: 'jsdom', + include: ['tests/**/*.client.test.ts?(x)'], + setupFiles: ['tests/jsdom.setup.ts'], + }, + }, + { + extends: true, + test: { + name: 'node', + environment: 'node', + include: ['tests/**/*.server.test.ts'], + }, + }, + ], + }, +}) diff --git a/e2e/react-start/vitest-library/.gitignore b/e2e/react-start/vitest-library/.gitignore new file mode 100644 index 0000000000..e915670a21 --- /dev/null +++ b/e2e/react-start/vitest-library/.gitignore @@ -0,0 +1,7 @@ +node_modules +.DS_Store +dist +.output +.tanstack +*.local +__screenshots__ diff --git a/e2e/react-start/vitest-library/package.json b/e2e/react-start/vitest-library/package.json new file mode 100644 index 0000000000..920dcc4ef5 --- /dev/null +++ b/e2e/react-start/vitest-library/package.json @@ -0,0 +1,42 @@ +{ + "name": "tanstack-react-start-e2e-vitest-library", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "test:e2e": "pnpm run test:e2e:types && pnpm run test:e2e:linked && pnpm run test:e2e:cached && pnpm run test:e2e:installed", + "test:e2e:types": "tsc --noEmit", + "test:e2e:linked": "vitest --clearCache && vitest run", + "test:e2e:cached": "vitest run", + "test:e2e:installed": "node ../../../scripts/e2e/run-as-installed.mjs vitest run" + }, + "dependencies": { + "@tanstack/react-start": "workspace:^", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@vitejs/plugin-react": "catalog:", + "@vitest/browser-playwright": "5.0.4", + "jsdom": "catalog:", + "playwright": "^1.63.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "catalog:", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "test:e2e": { + "inputs": [ + "buildProduction", + "^production", + "dependentTaskOutputs", + "{workspaceRoot}/scripts/e2e/run-as-installed.mjs" + ] + } + } + } +} diff --git a/e2e/react-start/vitest-library/src/account.ts b/e2e/react-start/vitest-library/src/account.ts new file mode 100644 index 0000000000..a6663262be --- /dev/null +++ b/e2e/react-start/vitest-library/src/account.ts @@ -0,0 +1,10 @@ +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { sessionMiddleware } from './session' + +export const getAccount = createServerFn() + .middleware([sessionMiddleware]) + .handler(({ context }) => { + setResponseHeader('cache-control', 'private') + return { name: context.user } + }) diff --git a/e2e/react-start/vitest-library/src/greeting.ts b/e2e/react-start/vitest-library/src/greeting.ts new file mode 100644 index 0000000000..fb3cf17136 --- /dev/null +++ b/e2e/react-start/vitest-library/src/greeting.ts @@ -0,0 +1,24 @@ +import { createMiddleware, createServerFn } from '@tanstack/react-start' +import { readSecret } from './server-only' + +export const secretMiddleware = createMiddleware({ type: 'function' }) + .client(({ next }) => next({ headers: { 'x-greeting': 'from the client' } })) + .server(({ next }) => next({ context: { secret: readSecret() } })) + +export const greet = createServerFn({ method: 'POST' }) + .middleware([secretMiddleware]) + .validator((name: string) => { + if (!name) { + throw new Error('A name is required') + } + return name + }) + // (typed as a string: a mock returns the type of the handler, and the type + // of this template would be `Hello ${string}, ${string}`) + .handler(({ data, context }): string => `Hello ${data}, ${context.secret}`) + +// Stands for a route loader or a component in the file that defines the +// server function it calls. +export function welcome(name: string) { + return greet({ data: name }) +} diff --git a/e2e/react-start/vitest-library/src/runtime.ts b/e2e/react-start/vitest-library/src/runtime.ts new file mode 100644 index 0000000000..4137c7802d --- /dev/null +++ b/e2e/react-start/vitest-library/src/runtime.ts @@ -0,0 +1,14 @@ +import { + createClientOnlyFn, + createIsomorphicFn, + createServerOnlyFn, +} from '@tanstack/react-start' +import { readSecret } from './server-only' + +export const describeRuntime = createIsomorphicFn() + .server(() => `server with ${readSecret()}`) + .client(() => 'client') + +export const getSecret = createServerOnlyFn(() => readSecret()) + +export const getLanguage = createClientOnlyFn(() => navigator.language) diff --git a/e2e/react-start/vitest-library/src/server-only.ts b/e2e/react-start/vitest-library/src/server-only.ts new file mode 100644 index 0000000000..106cd6e23a --- /dev/null +++ b/e2e/react-start/vitest-library/src/server-only.ts @@ -0,0 +1,11 @@ +// Stands for code that must never load in a browser: a database client, a +// secret, a Node API. Loading it leaves a mark that tests can look for. +declare global { + var __SERVER_ONLY_MODULE_LOADED__: boolean | undefined +} + +globalThis.__SERVER_ONLY_MODULE_LOADED__ = true + +export function readSecret() { + return 'the server secret' +} diff --git a/e2e/react-start/vitest-library/src/session.ts b/e2e/react-start/vitest-library/src/session.ts new file mode 100644 index 0000000000..24566aa4d5 --- /dev/null +++ b/e2e/react-start/vitest-library/src/session.ts @@ -0,0 +1,23 @@ +import { createMiddleware } from '@tanstack/react-start' +import { getCookie } from '@tanstack/react-start/server' + +// A middleware in a file of its own, so that a test can replace it with +// `mockMiddleware` (see tests/account.server.test.ts). +export const sessionMiddleware = createMiddleware({ type: 'function' }) + .client(({ next }) => { + // Stands for client code that needs a browser. A server test runs the + // client function of a middleware first, as server rendering does. + globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__ = true + return next() + }) + .server(({ next }) => { + const user = getCookie('session') + if (!user) { + throw new Error('Not signed in') + } + return next({ context: { user } }) + }) + +declare global { + var __SESSION_CLIENT_MIDDLEWARE_RAN__: boolean | undefined +} diff --git a/e2e/react-start/vitest-library/src/tenant.ts b/e2e/react-start/vitest-library/src/tenant.ts new file mode 100644 index 0000000000..08f6b9a594 --- /dev/null +++ b/e2e/react-start/vitest-library/src/tenant.ts @@ -0,0 +1,15 @@ +import { createMiddleware } from '@tanstack/react-start' + +// A request middleware: it runs for every request, before any route or +// server function. tests/tenant.server.test.ts runs it on its own. +export const tenantMiddleware = createMiddleware().server( + async ({ next, request }) => { + const tenant = new URL(request.url).hostname.split('.')[0]! + if (tenant === 'www') { + return new Response('No tenant', { status: 404 }) + } + const result = await next({ context: { tenant } }) + result.response.headers.set('x-tenant', tenant) + return result + }, +) diff --git a/e2e/react-start/vitest-library/tests/account.server.test.ts b/e2e/react-start/vitest-library/tests/account.server.test.ts new file mode 100644 index 0000000000..069f83e4df --- /dev/null +++ b/e2e/react-start/vitest-library/tests/account.server.test.ts @@ -0,0 +1,97 @@ +import { getRouterInstance } from '@tanstack/react-start' +import { getResponseHeader } from '@tanstack/react-start/server' +import { + mockMiddleware, + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { beforeEach, expect, test } from 'vitest' +import { getAccount } from '../src/account' +import { sessionMiddleware } from '../src/session' + +beforeEach(() => { + globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__ = undefined +}) + +test('a server function cannot be called outside of a request', async () => { + await expect(getAccount()).rejects.toThrow( + /No Start context found.*runInRequest\(\)/, + ) +}) + +test('a server function runs its middleware and its handler for the request of the test', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + await expect(getAccount()).resolves.toEqual({ name: 'ada' }) + + expect(getResponseHeader('cache-control')).toBe('private') + }) + // (as during server rendering, the client function of the middleware ran) + expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBe(true) +}) + +test('runInRequest resolves to what the callback returns', async () => { + const account = await runInRequest( + { headers: { cookie: 'session=ada' } }, + () => getAccount(), + ) + + expect(account).toEqual({ name: 'ada' }) +}) + +test('a server function fails as in the app when its middleware refuses the request', async () => { + await expect(runInRequest(() => getAccount())).rejects.toThrow( + 'Not signed in', + ) +}) + +test('mockMiddleware replaces a middleware, its client function included', async () => { + mockMiddleware(sessionMiddleware, ({ next }) => + next({ context: { user: 'grace' } }), + ) + + await expect(runInRequest(() => getAccount())).resolves.toEqual({ + name: 'grace', + }) + expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBeUndefined() +}) + +test('a mock ends with the test that registered it', async () => { + await expect(runInRequest(() => getAccount())).rejects.toThrow( + 'Not signed in', + ) +}) + +test('a mock registered inside a request ends with that request', async () => { + await runInRequest(async () => { + mockMiddleware(sessionMiddleware, ({ next }) => + next({ context: { user: 'grace' } }), + ) + + await expect(getAccount()).resolves.toEqual({ name: 'grace' }) + }) + + await expect(runInRequest(() => getAccount())).rejects.toThrow( + 'Not signed in', + ) +}) + +test('runMiddleware calls the server function of one middleware', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + const { context } = await runMiddleware(sessionMiddleware, {}) + + expect(context).toEqual({ user: 'ada' }) + }) + + await runInRequest(async () => { + await expect(runMiddleware(sessionMiddleware, {})).rejects.toThrow( + 'Not signed in', + ) + }) + expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBeUndefined() +}) + +test('a project without a router entry has no router in a request', async () => { + await expect(runInRequest(() => getRouterInstance())).rejects.toThrow( + 'This project has no router entry', + ) +}) diff --git a/e2e/react-start/vitest-library/tests/greeting.client.test.ts b/e2e/react-start/vitest-library/tests/greeting.client.test.ts new file mode 100644 index 0000000000..9f58c5d6f4 --- /dev/null +++ b/e2e/react-start/vitest-library/tests/greeting.client.test.ts @@ -0,0 +1,39 @@ +import { mockServerFn } from '@tanstack/react-start/testing' +import { expect, test } from 'vitest' +import { greet, welcome } from '../src/greeting' + +test('a mock answers the call with the data of the call', async () => { + mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`) + + await expect(greet({ data: 'Ada' })).resolves.toBe('Hello Ada, from the mock') +}) + +// The test above registered a mock. Start's setup file ended it with that +// test, so no test of this file removes mocks itself. +test('a server function call without a mock fails with an error that names the function', async () => { + await expect(greet({ data: 'Ada' })).rejects.toThrow( + 'The server function "greet" (/src/greeting.ts) was called in a client test, where no server runs.', + ) +}) + +test('a mock answers a call that is made in the file of the server function', async () => { + mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`) + + await expect(welcome('Ada')).resolves.toBe('Hello Ada, from the mock') +}) + +test("the function's client middleware runs before the mock", async () => { + let header: string | null = null + mockServerFn(greet, ({ data, headers }) => { + header = headers.get('x-greeting') + return `Hello ${data}, from the mock` + }) + + await greet({ data: 'Ada' }) + + expect(header).toBe('from the client') +}) + +test('the handler, the validator and the server middleware are not in the client code', () => { + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() +}) diff --git a/e2e/react-start/vitest-library/tests/greeting.server.test.ts b/e2e/react-start/vitest-library/tests/greeting.server.test.ts new file mode 100644 index 0000000000..ce80023cdc --- /dev/null +++ b/e2e/react-start/vitest-library/tests/greeting.server.test.ts @@ -0,0 +1,50 @@ +import { mockServerFn } from '@tanstack/react-start/testing' +import { + mockMiddleware, + runInRequest, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { greet, secretMiddleware, welcome } from '../src/greeting' + +test('a server function runs its middleware, its validator and its handler', async () => { + await expect(runInRequest(() => greet({ data: 'Ada' }))).resolves.toBe( + 'Hello Ada, the server secret', + ) +}) + +test('a call that is made in the file of the server function runs it as well', async () => { + await expect(runInRequest(() => welcome('Ada'))).resolves.toBe( + 'Hello Ada, the server secret', + ) +}) + +test('the validator of a server function rejects bad input', async () => { + await expect(runInRequest(() => greet({ data: '' }))).rejects.toThrow( + 'A name is required', + ) +}) + +// On the server a server function runs for real. There is no request that a +// mock could answer. +test('mockServerFn refuses a server function in a server test', () => { + expect(() => + mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`), + ).toThrow( + 'mockServerFn() needs a server function that the Start compiler compiled for a client test', + ) +}) + +// `secretMiddleware` is created in the file of `greet`. The server loads that +// file a second time for the server side of `greet`, with a middleware object +// of its own, which the mock does not reach. +test('a middleware that is created in the file of its server function cannot be mocked', async () => { + await expect( + runInRequest(async () => { + mockMiddleware(secretMiddleware, ({ next }) => + next({ context: { secret: 'a mocked secret' } }), + ) + + await greet({ data: 'Ada' }) + }), + ).rejects.toThrow('Create the middleware in a file of its own to mock it.') +}) diff --git a/e2e/react-start/vitest-library/tests/runtime.client.test.ts b/e2e/react-start/vitest-library/tests/runtime.client.test.ts new file mode 100644 index 0000000000..56cd4f4bdc --- /dev/null +++ b/e2e/react-start/vitest-library/tests/runtime.client.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from 'vitest' +import { describeRuntime, getLanguage, getSecret } from '../src/runtime' + +test('an isomorphic function runs its client implementation', () => { + expect(describeRuntime()).toBe('client') +}) + +test('a client-only function runs', () => { + expect(getLanguage()).toBe(navigator.language) +}) + +test('a server-only function throws', () => { + expect(() => getSecret()).toThrow() +}) + +test('the module that only server code uses is never loaded', () => { + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() +}) diff --git a/e2e/react-start/vitest-library/tests/runtime.server.test.ts b/e2e/react-start/vitest-library/tests/runtime.server.test.ts new file mode 100644 index 0000000000..4d6204ed3a --- /dev/null +++ b/e2e/react-start/vitest-library/tests/runtime.server.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from 'vitest' +import { describeRuntime, getLanguage, getSecret } from '../src/runtime' + +test('an isomorphic function runs its server implementation', () => { + expect(describeRuntime()).toBe('server with the server secret') +}) + +test('a server-only function runs', () => { + expect(getSecret()).toBe('the server secret') +}) + +test('a client-only function throws', () => { + expect(() => getLanguage()).toThrow() +}) + +test('the module that server code uses is loaded', () => { + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBe(true) +}) diff --git a/e2e/react-start/vitest-library/tests/tenant.server.test.ts b/e2e/react-start/vitest-library/tests/tenant.server.test.ts new file mode 100644 index 0000000000..3636b8875d --- /dev/null +++ b/e2e/react-start/vitest-library/tests/tenant.server.test.ts @@ -0,0 +1,30 @@ +import { + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test, vi } from 'vitest' +import { tenantMiddleware } from '../src/tenant' + +test('a request middleware passes context on and can change the response', async () => { + await runInRequest({ url: 'https://acme.example.com/posts' }, async () => { + const { context, response } = await runMiddleware( + tenantMiddleware, + {}, + ({ context }) => new Response(`Posts of ${context.tenant}`), + ) + + expect(context).toEqual({ tenant: 'acme' }) + expect(response.headers.get('x-tenant')).toBe('acme') + await expect(response.text()).resolves.toBe('Posts of acme') + }) +}) + +test('a request middleware can answer the request itself', async () => { + await runInRequest({ url: 'https://www.example.com/posts' }, async () => { + const next = vi.fn() + const { response } = await runMiddleware(tenantMiddleware, {}, next) + + expect(response.status).toBe(404) + expect(next).not.toHaveBeenCalled() + }) +}) diff --git a/e2e/react-start/vitest-library/tsconfig.json b/e2e/react-start/vitest-library/tsconfig.json new file mode 100644 index 0000000000..2fa8651e3f --- /dev/null +++ b/e2e/react-start/vitest-library/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "skipLibCheck": true, + "resolveJsonModule": true, + "noEmit": true, + "types": ["node"] + }, + "include": ["src", "tests", "vitest.config.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-start/vitest-library/vitest.config.ts b/e2e/react-start/vitest-library/vitest.config.ts new file mode 100644 index 0000000000..ac9b6f1b1f --- /dev/null +++ b/e2e/react-start/vitest-library/vitest.config.ts @@ -0,0 +1,59 @@ +import { defineConfig } from 'vitest/config' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { playwright } from '@vitest/browser-playwright' + +// A package without routes and without a router entry, which depends on +// Start only. It needs the Start compiler, so that each test environment gets +// the code a Start app would run there. +// +// `test:e2e` type-checks the project and runs these tests three times: +// - here, where `@tanstack/*` are links to `packages/*`, with an empty Vitest +// cache (`test:e2e:linked`), +// - here again, now with the compiled modules of the first run in Vitest's +// cache (`test:e2e:cached`): a test run must not depend on the Start +// compiler having seen a file in the same process, +// - in a copy that is installed like a user's project +// (`test:e2e:installed`, `scripts/e2e/run-as-installed.md` says why that +// differs). +export default defineConfig({ + plugins: [tanstackStart(), react()], + test: { + watch: false, + // Vitest keeps the modules it compiled in one cache for the whole + // repository. This project keeps its own, so that `test:e2e:linked` can + // empty it and compile every file with the packages as they are built now. + fsModuleCachePath: 'node_modules/.vitest-cache', + projects: [ + { + extends: true, + test: { + name: 'browser', + include: ['tests/**/*.client.test.ts'], + browser: { + enabled: true, + headless: true, + provider: playwright(), + instances: [{ browser: 'chromium' }], + }, + }, + }, + { + extends: true, + test: { + name: 'jsdom', + environment: 'jsdom', + include: ['tests/**/*.client.test.ts'], + }, + }, + { + extends: true, + test: { + name: 'node', + environment: 'node', + include: ['tests/**/*.server.test.ts'], + }, + }, + ], + }, +}) diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 6d51a4c6d0..a99f2a2353 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -60,6 +60,24 @@ "default": "./dist/esm/client-rpc.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/server": { + "import": { + "types": "./dist/esm/testing/server.d.ts", + "default": "./dist/esm/testing/server.js" + } + }, "./server": { "react-server": { "types": "./dist/esm/server.rsc.d.ts", diff --git a/packages/react-start/src/plugin/vite.ts b/packages/react-start/src/plugin/vite.ts index 8849f39ea6..9323e02af0 100644 --- a/packages/react-start/src/plugin/vite.ts +++ b/packages/react-start/src/plugin/vite.ts @@ -105,7 +105,12 @@ export function tanstackStart( : ['react-dom/server']), // `@tanstack/react-store` has a dependency on `use-sync-external-store`, which is CJS. // It therefore needs to be included so that it is converted to ESM. - '@tanstack/react-router > @tanstack/react-store', + // The path starts at `@tanstack/react-start`, because a + // package that only uses Start's compile-time APIs (and runs + // its tests with this plugin) may not depend on + // `@tanstack/react-router` itself, and Vite resolves the path + // from the project. + '@tanstack/react-start > @tanstack/react-router > @tanstack/react-store', ...(options.optimizeDeps?.exclude?.find( (x) => x === '@tanstack/react-form', ) diff --git a/packages/react-start/src/testing.ts b/packages/react-start/src/testing.ts new file mode 100644 index 0000000000..0384b6fb65 --- /dev/null +++ b/packages/react-start/src/testing.ts @@ -0,0 +1,10 @@ +export { + mockServerFn, + resetServerFnMocks, +} from '@tanstack/start-client-core/testing' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from '@tanstack/start-client-core/testing' diff --git a/packages/react-start/src/testing/client-rpc.ts b/packages/react-start/src/testing/client-rpc.ts new file mode 100644 index 0000000000..80b041a388 --- /dev/null +++ b/packages/react-start/src/testing/client-rpc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-client-core/testing/client-rpc' diff --git a/packages/react-start/src/testing/server.ts b/packages/react-start/src/testing/server.ts new file mode 100644 index 0000000000..ec2ad1c8d8 --- /dev/null +++ b/packages/react-start/src/testing/server.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/testing' diff --git a/packages/react-start/vite.config.ts b/packages/react-start/vite.config.ts index 652e4ef842..6395099e44 100644 --- a/packages/react-start/vite.config.ts +++ b/packages/react-start/vite.config.ts @@ -29,6 +29,9 @@ export default mergeConfig( './src/client.tsx', './src/hydration.ts', './src/client-rpc.ts', + './src/testing.ts', + './src/testing/client-rpc.ts', + './src/testing/server.ts', './src/server.tsx', './src/server.rsc.ts', './src/server-rpc.ts', diff --git a/packages/router-generator/src/generator.ts b/packages/router-generator/src/generator.ts index 91f87dadda..f47ea63af9 100644 --- a/packages/router-generator/src/generator.ts +++ b/packages/router-generator/src/generator.ts @@ -209,6 +209,7 @@ export class Generator { public targetTemplate: TargetTemplate private root: string + private writeRouteFiles: boolean private routesDirectoryPath: string private sessionId?: string private fs: fs @@ -243,10 +244,21 @@ export class Generator { private static componentPieceRegex = /[./](component|errorComponent|notFoundComponent|pendingComponent|loader|lazy)[.]/ - constructor(opts: { config: Config; root: string; fs?: fs }) { + constructor(opts: { + config: Config + root: string + fs?: fs + /** + * `false` keeps the generator from scaffolding empty route files and from + * updating the route path or factory in existing ones. Only the route tree + * is written. A route file that would have been written gets a warning. + */ + writeRouteFiles?: boolean + }) { this.config = opts.config this.logger = logging({ disabled: this.config.disableLogging }) this.root = opts.root + this.writeRouteFiles = opts.writeRouteFiles ?? true this.fs = opts.fs || DefaultFileSystem this.generatedRouteTreePath = this.getGeneratedRouteTreePath() this.targetTemplate = getTargetTemplate(this.config) @@ -1034,6 +1046,12 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved let shouldWriteTree = false // now we need to either scaffold the file or transform it if (!existingRouteFile.fileContent) { + if (!this.writeRouteFiles) { + this.logger.warn( + `Warning: Route file "${node.fullPath}" is empty. It is left as it is and is not included in the route tree, because this run does not write route files.`, + ) + return null + } shouldWriteRouteFile = true shouldWriteTree = true // Creating a new lazy route file @@ -1129,8 +1147,14 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved ) } if (transformResult.result === 'modified') { - updatedCacheEntry.fileContent = transformResult.output - shouldWriteRouteFile = true + if (this.writeRouteFiles) { + updatedCacheEntry.fileContent = transformResult.output + shouldWriteRouteFile = true + } else { + this.logger.warn( + `Warning: Route file "${node.fullPath}" is out of date: its route path or route factory does not match its location. It is left as it is, because this run does not write route files.`, + ) + } } } @@ -1369,6 +1393,11 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved // scaffold the root route if (!rootNodeFile.fileContent) { + if (!this.writeRouteFiles) { + throw new Error( + `The root route file "${node.fullPath}" is empty, and this run does not write route files.`, + ) + } const rootTemplate = this.targetTemplate.rootRoute const rootRouteContent = await fillTemplate( this.config, diff --git a/packages/router-generator/tests/write-route-files.test.ts b/packages/router-generator/tests/write-route-files.test.ts new file mode 100644 index 0000000000..14f7340ef8 --- /dev/null +++ b/packages/router-generator/tests/write-route-files.test.ts @@ -0,0 +1,107 @@ +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { Generator, getConfig } from '../src' + +const rootRouteSource = `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +` + +let tempDir: string | undefined + +afterEach(async () => { + vi.restoreAllMocks() + if (tempDir) { + await fs.rm(tempDir, { recursive: true, force: true }) + tempDir = undefined + } +}) + +/** A project whose generator writes the route tree and no route file. */ +async function createProject(routes: Record) { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-tree-only-')) + const routesDirectory = path.join(tempDir, 'routes') + await fs.mkdir(routesDirectory) + for (const [file, content] of Object.entries(routes)) { + await fs.writeFile(path.join(routesDirectory, file), content) + } + const generatedRouteTree = path.join(tempDir, 'routeTree.gen.ts') + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'info').mockImplementation(() => {}) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const generator = new Generator({ + config: getConfig( + { + routesDirectory, + generatedRouteTree, + tmpDir: path.join(tempDir, 'tmp'), + }, + tempDir, + ), + root: tempDir, + writeRouteFiles: false, + }) + return { + generator, + // (the generator names route files with forward slashes on every system) + route: (file: string) => + path.join(routesDirectory, file).replaceAll('\\', '/'), + routeTree: () => fs.readFile(generatedRouteTree, 'utf8'), + warnings: () => warn.mock.calls.map((args) => args.join(' ')).join('\n'), + } +} + +describe('generator that does not write route files', () => { + it('leaves a route file whose route path is out of date as it is and warns', async () => { + const movedRouteSource = `import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/moved-from')({ + component: () => 'moved', +}) +` + const project = await createProject({ + '__root.tsx': rootRouteSource, + 'moved.tsx': movedRouteSource, + }) + + await project.generator.run() + + expect(await fs.readFile(project.route('moved.tsx'), 'utf8')).toBe( + movedRouteSource, + ) + // The route tree has the route by the location of its file. + const routeTree = await project.routeTree() + expect(routeTree).toContain(`'/moved'`) + expect(routeTree).not.toContain('moved-from') + expect(project.warnings()).toContain( + `Route file "${project.route('moved.tsx')}" is out of date`, + ) + }) + + it('leaves an empty route file empty and out of the route tree, and warns', async () => { + const project = await createProject({ + '__root.tsx': rootRouteSource, + 'empty.tsx': '', + }) + + await project.generator.run() + + expect(await fs.readFile(project.route('empty.tsx'), 'utf8')).toBe('') + expect(await project.routeTree()).not.toContain('empty') + expect(project.warnings()).toContain( + `Route file "${project.route('empty.tsx')}" is empty`, + ) + }) + + it('fails for an empty root route file, which it cannot fill', async () => { + const project = await createProject({ '__root.tsx': '' }) + + await expect(project.generator.run()).rejects.toThrow( + `The root route file "${project.route('__root.tsx')}" is empty`, + ) + expect(await fs.readFile(project.route('__root.tsx'), 'utf8')).toBe('') + }) +}) diff --git a/packages/router-plugin/src/core/host-options.ts b/packages/router-plugin/src/core/host-options.ts new file mode 100644 index 0000000000..bf8b4ad6a8 --- /dev/null +++ b/packages/router-plugin/src/core/host-options.ts @@ -0,0 +1,28 @@ +import type { Config } from './config' + +/** + * Lets a plugin that embeds the route generator, such as TanStack Start, + * change when it runs. Every function is called late, once the bundler's + * config is known, and every option defaults to the standalone behaviour. + */ +export interface RouterGeneratorHostOptions { + /** Return `false` to create no generator at all for this config. */ + enabled?: (opts: { config: Config; root: string }) => boolean + /** Return `false` to ignore file changes after the first run. */ + watch?: () => boolean + /** Return `false` to keep the generator from writing route files. */ + writeRouteFiles?: () => boolean +} + +/** + * Lets a plugin that embeds the code splitter, such as TanStack Start, change + * what it handles. The function is called for each module. + */ +export interface RouterCodeSplitterHostOptions { + /** + * Return `true` to also handle a module that calls a route factory but is + * unknown to the route generator. Nothing is split out of such a module; + * only the route options listed in `deleteNodes` are removed from it. + */ + deleteNodesInUnknownRoutes?: () => boolean +} diff --git a/packages/router-plugin/src/core/router-code-splitter-plugin.ts b/packages/router-plugin/src/core/router-code-splitter-plugin.ts index ecc7607d59..1e09bf8cf2 100644 --- a/packages/router-plugin/src/core/router-code-splitter-plugin.ts +++ b/packages/router-plugin/src/core/router-code-splitter-plugin.ts @@ -26,6 +26,7 @@ import type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator' import type { CodeSplitCompilerPlugin } from './code-splitter/plugins' import type { Config } from './config' import type { HmrStyle } from './hmr' +import type { RouterCodeSplitterHostOptions } from './host-options' import type { RouterPluginContext } from './router-plugin-context' import type { UnpluginFactory, @@ -82,6 +83,7 @@ export function createRouterCodeSplitterPlugin( options: Partial Config)> | undefined = {}, routerPluginContext: RouterPluginContext, hmrStyle: HmrStyle = 'vite', + hostOptions: RouterCodeSplitterHostOptions = {}, ): ReturnType Config)> | undefined>> { let ROOT: string = process.cwd() let userConfig: Config @@ -209,6 +211,34 @@ export function createRouterCodeSplitterPlugin( return compiledReferenceRoute } + const handleDeletingNodesInUnknownRoute = ( + code: string, + id: string, + ): UnpluginTransformResult => { + const deleteNodes = userConfig.codeSplittingOptions?.deleteNodes + if (!deleteNodes?.length) { + return null + } + + if (debug) { + console.info('Deleting nodes in route unknown to the generator: ', id) + } + + // Without split groupings the reference compiler only removes the listed + // route options and the code that nothing else uses anymore. + return compileCodeSplitReferenceRoute({ + code, + codeSplitGroupings: [], + targetFramework: userConfig.target, + filename: id, + id, + isProduction, + deleteNodes: new Set(deleteNodes), + addHmr: false, + hmrStyle, + }) + } + const handleCompilingVirtualFile = ( code: string, id: string, @@ -277,6 +307,10 @@ export function createRouterCodeSplitterPlugin( ) } + if (hostOptions.deleteNodesInUnknownRoutes?.()) { + return handleDeletingNodesInUnknownRoute(code, normalizedId) + } + return null }, }, diff --git a/packages/router-plugin/src/core/router-generator-plugin.ts b/packages/router-plugin/src/core/router-generator-plugin.ts index 50dde9f55c..27e5dfc393 100644 --- a/packages/router-plugin/src/core/router-generator-plugin.ts +++ b/packages/router-plugin/src/core/router-generator-plugin.ts @@ -7,6 +7,7 @@ import type { GeneratorEvent } from '@tanstack/router-generator' import type { FSWatcher } from 'chokidar' import type { UnpluginFactory } from 'unplugin' import type { Config } from './config' +import type { RouterGeneratorHostOptions } from './host-options' import type { RouterPluginContext } from './router-plugin-context' const PLUGIN_NAME = 'unplugin:router-generator' @@ -14,10 +15,11 @@ const PLUGIN_NAME = 'unplugin:router-generator' export function createRouterGeneratorPlugin( options: Partial Config)> | undefined = {}, routerPluginContext: RouterPluginContext, + hostOptions: RouterGeneratorHostOptions = {}, ): ReturnType Config)> | undefined>> { let ROOT: string = process.cwd() let userConfig: Config - let generator: Generator + let generator: Generator | undefined const getRoutesDirectoryPath = () => { return isAbsolute(userConfig.routesDirectory) @@ -34,9 +36,14 @@ export function createRouterGeneratorPlugin( } else { userConfig = getConfig(options, ROOT) } + if (hostOptions.enabled?.({ config: userConfig, root: ROOT }) === false) { + generator = undefined + return + } generator = new Generator({ config: userConfig, root: ROOT, + writeRouteFiles: hostOptions.writeRouteFiles?.(), }) } @@ -54,6 +61,10 @@ export function createRouterGeneratorPlugin( generatorEvent = { path: filePath, type: opts.event } } + if (!generator) { + return + } + try { await generator.run(generatorEvent) routerPluginContext.routesByFile = generator.getRoutesByFileMap() @@ -66,6 +77,9 @@ export function createRouterGeneratorPlugin( name: 'tanstack:router-generator', enforce: 'pre', async watchChange(id, { event }) { + if (hostOptions.watch?.() === false) { + return + } await generate({ file: id, event, diff --git a/packages/router-plugin/src/vite.ts b/packages/router-plugin/src/vite.ts index 3608887f33..2d40788e2a 100644 --- a/packages/router-plugin/src/vite.ts +++ b/packages/router-plugin/src/vite.ts @@ -6,6 +6,10 @@ import { createRouterGeneratorPlugin } from './core/router-generator-plugin' import { unpluginRouterComposedFactory } from './core/router-composed-plugin' import { createRouterPluginContext } from './core/router-plugin-context' import type { CodeSplittingOptions, Config } from './core/config' +import type { + RouterCodeSplitterHostOptions, + RouterGeneratorHostOptions, +} from './core/host-options' import type { RouterPluginContext } from './core/router-plugin-context' type RouterPluginOptions = Partial Config)> | undefined @@ -24,10 +28,11 @@ const defaultRouterPluginContext = createRouterPluginContext() const tanstackRouterGenerator = ( options?: RouterPluginOptions, routerPluginContext?: RouterPluginContext, + hostOptions?: RouterGeneratorHostOptions, ) => { const pluginContext = routerPluginContext ?? defaultRouterPluginContext return createVitePlugin((pluginOptions: RouterPluginOptions) => - createRouterGeneratorPlugin(pluginOptions, pluginContext), + createRouterGeneratorPlugin(pluginOptions, pluginContext, hostOptions), )(options) } @@ -43,10 +48,16 @@ const tanstackRouterGenerator = ( const tanStackRouterCodeSplitter = ( options?: RouterPluginOptions, routerPluginContext?: RouterPluginContext, + hostOptions?: RouterCodeSplitterHostOptions, ) => { const pluginContext = routerPluginContext ?? defaultRouterPluginContext return createVitePlugin((pluginOptions: RouterPluginOptions) => - createRouterCodeSplitterPlugin(pluginOptions, pluginContext), + createRouterCodeSplitterPlugin( + pluginOptions, + pluginContext, + undefined, + hostOptions, + ), )(options) } diff --git a/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts b/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts index dca96bfa28..5f251537ef 100644 --- a/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts +++ b/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts @@ -189,6 +189,69 @@ export const Route = createFileRoute('/unshared')({ }) }) +describe('a route module the route generator does not know', () => { + const file = routeFile('unknown') + const code = ` +import { createFileRoute } from '@tanstack/react-router' +import { secret } from './server-only' +export const Route = createFileRoute('/unknown')({ + server: { handlers: { GET: () => new Response(secret) } }, + component: () =>

unknown

, +}) +` + const options: Partial = { + codeSplittingOptions: { deleteNodes: ['server'] }, + } + + it('is left as it is', async () => { + const splitter = await createCodeSplitterTransforms(options, {}) + + expect(splitter.reference(code, file)).toBeNull() + }) + + // A plugin that embeds the code splitter can run where no generator does, + // e.g. TanStack Start for the tests of a package without routes. + it('loses the route options to delete, and nothing else, when the host plugin asks for it', async () => { + const splitter = await createCodeSplitterTransforms( + options, + {}, + undefined, + { deleteNodesInUnknownRoutes: () => true }, + ) + + const reference = splitter.reference(code, file)! + // (the import only the deleted option used goes with it) + expect(reference).not.toContain('server') + expect(importSources(reference)).toEqual(['@tanstack/react-router']) + expect(reference).toContain('

unknown

') + expect(reference).not.toContain('tsr-split') + await expectValidModules({ reference }) + }) + + it('is left as it is when the host plugin asks for it and there are no route options to delete', async () => { + const splitter = await createCodeSplitterTransforms({}, {}, undefined, { + deleteNodesInUnknownRoutes: () => true, + }) + + expect(splitter.reference(code, file)).toBeNull() + }) + + it('does not change how a route module the generator knows is split', async () => { + const routes = { [file]: '/unknown' } + const hosted = await createCodeSplitterTransforms( + options, + routes, + undefined, + { deleteNodesInUnknownRoutes: () => true }, + ) + const standalone = await createCodeSplitterTransforms(options, routes) + + const reference = hosted.reference(code, file) + expect(reference).toContain('tsr-split=component') + expect(reference).toBe(standalone.reference(code, file)) + }) +}) + describe('route HMR plugin without code splitting', () => { function transformWith( options: Partial & { target: 'solid' | 'vue' }, diff --git a/packages/router-plugin/tests/regression-helpers.ts b/packages/router-plugin/tests/regression-helpers.ts index df482ffe78..9df375881b 100644 --- a/packages/router-plugin/tests/regression-helpers.ts +++ b/packages/router-plugin/tests/regression-helpers.ts @@ -26,6 +26,7 @@ import { getModuleErrors } from './validate-module' import type { Config } from '../src/core/config' import type { CodeSplitGroupings } from '../src/core/constants' import type { HmrStyle } from '../src/core/hmr' +import type { RouterCodeSplitterHostOptions } from '../src/core/host-options' import type { TransformResult, UnpluginOptions } from 'unplugin' import type { ESTree } from 'vite' @@ -189,12 +190,14 @@ const sharedPluginName = 'tanstack-router:code-splitter:compile-shared-file' * Drives the three code-splitter transforms the way a bundler does, for the * given route files (absolute path to route id). `configPlugins` are the * plugins of the resolved Vite config; by default the code splitter itself, - * so its plugin-order check runs. + * so its plugin-order check runs. `hostOptions` are those of a plugin that + * embeds the code splitter. */ export async function createCodeSplitterTransforms( options: Partial, routes: Record, configPlugins: Array<{ name: string }> = [{ name: referencePluginName }], + hostOptions?: RouterCodeSplitterHostOptions, ) { const context = createRouterPluginContext() for (const [file, routeId] of Object.entries(routes)) { @@ -203,6 +206,8 @@ export async function createCodeSplitterTransforms( const plugins = createRouterCodeSplitterPlugin( { target: 'react', autoCodeSplitting: true, ...options }, context, + undefined, + hostOptions, ) const pluginArray = Array.isArray(plugins) ? plugins : [plugins] const byName = (name: string) => { diff --git a/packages/router-plugin/tests/router-generator-plugin.test.ts b/packages/router-plugin/tests/router-generator-plugin.test.ts new file mode 100644 index 0000000000..0278d5870d --- /dev/null +++ b/packages/router-plugin/tests/router-generator-plugin.test.ts @@ -0,0 +1,152 @@ +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { createRouterGeneratorPlugin } from '../src/core/router-generator-plugin' +import { createRouterPluginContext } from '../src/core/router-plugin-context' +import type { RouterGeneratorHostOptions } from '../src/core/host-options' +import type { UnpluginOptions } from 'unplugin' + +const rootRouteSource = `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +` + +const routeSource = (routePath: string) => + `import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('${routePath}')({ + component: () => 'route', +}) +` + +let tempDir: string | undefined + +afterEach(async () => { + if (tempDir) { + await fs.rm(tempDir, { recursive: true, force: true }) + tempDir = undefined + } +}) + +/** + * A project with the generator plugin as a plugin that embeds it sets it up, + * driven the way Vite drives it. + */ +async function createProject( + routes: Record, + hostOptions?: RouterGeneratorHostOptions, +) { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-plugin-')) + const root = tempDir + const routesDirectory = path.join(root, 'routes') + const generatedRouteTree = path.join(root, 'routeTree.gen.ts') + await fs.mkdir(routesDirectory) + for (const [file, content] of Object.entries(routes)) { + await fs.writeFile(path.join(routesDirectory, file), content) + } + const plugin = createRouterGeneratorPlugin( + { + target: 'react', + routesDirectory, + generatedRouteTree, + tmpDir: path.join(root, 'tmp'), + disableLogging: true, + }, + createRouterPluginContext(), + hostOptions, + ) as UnpluginOptions + return { + route: (file: string) => path.join(routesDirectory, file), + routeTree: () => fs.readFile(generatedRouteTree, 'utf8'), + /** Vite resolved its config. */ + async start() { + const configResolved = plugin.vite!.configResolved as (config: { + root: string + }) => Promise + await configResolved.call({}, { root }) + }, + /** Vite's file watcher saw a new file. */ + async add(file: string, content: string) { + const added = path.join(routesDirectory, file) + await fs.writeFile(added, content) + const watchChange = plugin.watchChange as ( + id: string, + change: { event: 'create' | 'update' | 'delete' }, + ) => Promise + await watchChange.call({}, added, { event: 'create' }) + }, + } +} + +describe('route generator plugin', () => { + it('writes the route tree at startup and when a route is added', async () => { + const project = await createProject({ '__root.tsx': rootRouteSource }) + + await project.start() + expect(await project.routeTree()).not.toContain(`'/added'`) + + await project.add('added.tsx', routeSource('/added')) + expect(await project.routeTree()).toContain(`'/added'`) + }) +}) + +describe('route generator plugin embedded in a host plugin', () => { + it('generates nothing when the host disables it', async () => { + const project = await createProject( + { '__root.tsx': rootRouteSource }, + { enabled: () => false }, + ) + + await project.start() + await project.add('added.tsx', routeSource('/added')) + + await expect(project.routeTree()).rejects.toThrow('ENOENT') + }) + + it('tells the host the config and the root it would generate for', async () => { + const seen: Array<{ routesDirectory: string; root: string }> = [] + const project = await createProject( + { '__root.tsx': rootRouteSource }, + { + enabled: ({ config, root }) => { + seen.push({ routesDirectory: config.routesDirectory, root }) + return true + }, + }, + ) + + await project.start() + + expect(seen).toEqual([ + { routesDirectory: path.dirname(project.route('x')), root: tempDir }, + ]) + expect(await project.routeTree()).toContain('rootRouteImport') + }) + + it('writes the route tree at startup only when the host turns watching off', async () => { + const project = await createProject( + { '__root.tsx': rootRouteSource }, + { watch: () => false }, + ) + + await project.start() + const routeTree = await project.routeTree() + await project.add('added.tsx', routeSource('/added')) + + expect(await project.routeTree()).toBe(routeTree) + }) + + it('leaves route files as they are when the host turns writing them off', async () => { + const moved = routeSource('/moved-from') + const project = await createProject( + { '__root.tsx': rootRouteSource, 'moved.tsx': moved }, + { writeRouteFiles: () => false }, + ) + + await project.start() + + expect(await fs.readFile(project.route('moved.tsx'), 'utf8')).toBe(moved) + expect(await project.routeTree()).toContain(`'/moved'`) + }) +}) diff --git a/packages/solid-start/package.json b/packages/solid-start/package.json index 2f378426cc..b49670d8c9 100644 --- a/packages/solid-start/package.json +++ b/packages/solid-start/package.json @@ -57,6 +57,24 @@ "default": "./dist/esm/client-rpc.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/server": { + "import": { + "types": "./dist/esm/testing/server.d.ts", + "default": "./dist/esm/testing/server.js" + } + }, "./server-rpc": { "import": { "types": "./dist/esm/server-rpc.d.ts", diff --git a/packages/solid-start/src/testing.ts b/packages/solid-start/src/testing.ts new file mode 100644 index 0000000000..0384b6fb65 --- /dev/null +++ b/packages/solid-start/src/testing.ts @@ -0,0 +1,10 @@ +export { + mockServerFn, + resetServerFnMocks, +} from '@tanstack/start-client-core/testing' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from '@tanstack/start-client-core/testing' diff --git a/packages/solid-start/src/testing/client-rpc.ts b/packages/solid-start/src/testing/client-rpc.ts new file mode 100644 index 0000000000..80b041a388 --- /dev/null +++ b/packages/solid-start/src/testing/client-rpc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-client-core/testing/client-rpc' diff --git a/packages/solid-start/src/testing/server.ts b/packages/solid-start/src/testing/server.ts new file mode 100644 index 0000000000..ec2ad1c8d8 --- /dev/null +++ b/packages/solid-start/src/testing/server.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/testing' diff --git a/packages/solid-start/vite.config.ts b/packages/solid-start/vite.config.ts index 2c1a42d0e4..0e94478654 100644 --- a/packages/solid-start/vite.config.ts +++ b/packages/solid-start/vite.config.ts @@ -29,6 +29,9 @@ export default mergeConfig( './src/client.tsx', './src/hydration.ts', './src/client-rpc.ts', + './src/testing.ts', + './src/testing/client-rpc.ts', + './src/testing/server.ts', './src/ssr-rpc.ts', './src/server-rpc.ts', './src/server.tsx', diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json index c74dce13aa..d094c94fa7 100644 --- a/packages/start-client-core/package.json +++ b/packages/start-client-core/package.json @@ -60,6 +60,24 @@ "default": "./dist/esm/client-rpc/index.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing/index.d.ts", + "default": "./dist/esm/testing/index.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/vitest": { + "import": { + "types": "./dist/esm/testing/vitest.d.ts", + "default": "./dist/esm/testing/vitest.js" + } + }, "./hydration": { "import": { "types": "./dist/esm/hydration.d.ts", @@ -120,5 +138,13 @@ "@arethetypeswrong/cli": "catalog:", "publint": "catalog:", "rimraf": "catalog:" + }, + "peerDependencies": { + "vitest": ">=3.1.0" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } } } diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx index e9a8b92d85..bda11979a8 100644 --- a/packages/start-client-core/src/index.tsx +++ b/packages/start-client-core/src/index.tsx @@ -40,6 +40,8 @@ export { type FunctionClientResultWithContext, type AssignAllClientContextBeforeNext, type AssignAllMiddleware, + type AssignAllServerFnContext, + type AssignAllServerRequestContext, type FunctionMiddlewareAfterValidator, type FunctionMiddlewareClientFn, type FunctionMiddlewareServerFnResult, diff --git a/packages/start-client-core/src/testing/client-rpc.ts b/packages/start-client-core/src/testing/client-rpc.ts new file mode 100644 index 0000000000..663386aaec --- /dev/null +++ b/packages/start-client-core/src/testing/client-rpc.ts @@ -0,0 +1,2 @@ +// What compiled client code imports in a test run, in place of `../client-rpc`. +export { createClientRpc } from './createClientRpc' diff --git a/packages/start-client-core/src/testing/createClientRpc.ts b/packages/start-client-core/src/testing/createClientRpc.ts new file mode 100644 index 0000000000..6f843973d8 --- /dev/null +++ b/packages/start-client-core/src/testing/createClientRpc.ts @@ -0,0 +1,24 @@ +import { TSS_SERVER_FUNCTION } from '../constants' +import { callServerFnMock, registerClientRpc } from './serverFnMocks' +import type { ClientFnMeta } from '../constants' + +/** + * The `createClientRpc` of a test run. The one of the app sends the call to + * the server (`../client-rpc/createClientRpc`). A client test has no server, + * so this one passes the call to the mock that `mockServerFn` registered. + */ +export function createClientRpc(functionId: string) { + const url = process.env.TSS_SERVER_FN_BASE + functionId + const serverFnMeta: ClientFnMeta = { id: functionId } + registerClientRpc(functionId) + + const clientFn = (...args: Array) => { + return callServerFnMock(functionId, args[0]) + } + + return Object.assign(clientFn, { + url, + serverFnMeta, + [TSS_SERVER_FUNCTION]: true, + }) +} diff --git a/packages/start-client-core/src/testing/index.ts b/packages/start-client-core/src/testing/index.ts new file mode 100644 index 0000000000..c62c2fabf9 --- /dev/null +++ b/packages/start-client-core/src/testing/index.ts @@ -0,0 +1,8 @@ +export { mockServerFn, resetServerFnMocks } from './serverFnMocks' +export { registerMockStore, saveMocks } from './mockStores' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from './serverFnMocks' diff --git a/packages/start-client-core/src/testing/mockStores.ts b/packages/start-client-core/src/testing/mockStores.ts new file mode 100644 index 0000000000..483d5b5913 --- /dev/null +++ b/packages/start-client-core/src/testing/mockStores.ts @@ -0,0 +1,32 @@ +/** + * The registries of `mockServerFn` and `mockMiddleware`. Each registers its + * map here, so that one hook of the test runner can put all of them back + * after a test. + */ +const stores = new Set>() + +/** @internal */ +export function registerMockStore(store: Map): void { + stores.add(store) +} + +/** + * Remembers every mock that is registered now and returns the function that + * restores exactly those. The setup file of a test runner calls it before + * each test and the returned function after it: a mock from the test itself + * or from `beforeEach` then ends with the test, and a mock from the top of + * the file or from `beforeAll` stays for the file. + * + * @internal + */ +export function saveMocks(): () => void { + const saved = Array.from(stores, (store) => [store, new Map(store)] as const) + return () => { + for (const [store, entries] of saved) { + store.clear() + for (const [key, value] of entries) { + store.set(key, value) + } + } + } +} diff --git a/packages/start-client-core/src/testing/serverFnMocks.ts b/packages/start-client-core/src/testing/serverFnMocks.ts new file mode 100644 index 0000000000..0659f2457d --- /dev/null +++ b/packages/start-client-core/src/testing/serverFnMocks.ts @@ -0,0 +1,144 @@ +import { registerMockStore } from './mockStores' +import type { FetcherBase, Method } from '../createServerFn' + +/** + * Answers for the server function calls of client tests. + * + * A client test has no server. So when a test runner compiles a project, the + * client code of a server function gets the `createClientRpc` of + * `./createClientRpc` instead of the one that sends a request. That one asks + * this module for the answer a test registered with `mockServerFn`, and fails + * when there is none. + */ + +/** What a mock gets of a server function call. */ +export interface ServerFnMockContext { + /** + * The `data` of the call, as the caller passed it. The function's validator + * has not run: it runs on the server, which the mock stands for. + */ + data: TData + method: Method + /** The headers of the call, with what the function's client middleware added. */ + headers: Headers + signal: AbortSignal | undefined +} + +/** A server function as client code has it. */ +export type AnyClientServerFn = FetcherBase & + ((...args: Array) => Promise) + +/** The `data` a server function is called with. */ +export type ServerFnMockData = TServerFn extends ( + options: infer TOptions, + ...args: Array +) => unknown + ? 'data' extends keyof NonNullable + ? NonNullable['data'] + : undefined + : never + +/** + * Stands for everything of a server function that runs on the server: its + * server middleware, its validator and its handler. It returns what the call + * resolves to, or throws what the call rejects with. + */ +export type ServerFnMock = ( + ctx: ServerFnMockContext>, +) => Awaited> | Promise>> + +type AnyServerFnMock = (ctx: ServerFnMockContext) => unknown + +/** The ids of the server functions that were compiled for this client test. */ +const clientRpcIds = new Set() +const mocks = new Map() + +registerMockStore(mocks) + +/** + * Answers the calls of a server function in a client test. A mock that a test + * or a `beforeEach` hook registers ends with that test; one from the top of + * the file or from `beforeAll` stays for the file. The mock is typed from the + * server function: it gets the `data` the function is called with, and + * returns what the function's handler returns. + * + * The function's client middleware runs as in the app. The mock is called + * where the app would send the request. + */ +export function mockServerFn( + serverFn: TServerFn, + mock: ServerFnMock, +): void { + const id = (serverFn as { serverFnMeta?: { id?: string } }).serverFnMeta?.id + if (id === undefined || !clientRpcIds.has(id)) { + throw new Error( + 'mockServerFn() needs a server function that the Start compiler compiled for a client test: ' + + 'one created with createServerFn().handler(), imported in a test that runs in a browser, in jsdom or in happy-dom, ' + + "with Start's plugin in the test runner's config. " + + 'In a server test a server function runs for real and has no request to answer.', + ) + } + mocks.set(id, mock) +} + +/** + * Removes every mock of `mockServerFn` now. Start's plugin already restores + * the mocks after each test, so this is only for removing them earlier. + */ +export function resetServerFnMocks(): void { + mocks.clear() +} + +/** Called by the `createClientRpc` of a test run for each function it creates. */ +export function registerClientRpc(id: string): void { + clientRpcIds.add(id) +} + +/** + * Called by the `createClientRpc` of a test run in place of the request. + * Resolves to what the response of the server would be read as. + */ +export async function callServerFnMock( + id: string, + call: { + data?: unknown + method: Method + headers?: HeadersInit + signal?: AbortSignal + }, +): Promise<{ result: unknown }> { + const mock = mocks.get(id) + if (!mock) { + throw new Error( + `The server function ${describeServerFn(id)} was called in a client test, where no server runs. ` + + 'Answer the call with mockServerFn() before it is made.', + ) + } + return { + result: await mock({ + data: call.data, + method: call.method, + headers: new Headers(call.headers), + signal: call.signal, + }), + } +} + +/** + * The name and the file of a server function, read from its id. The compiler + * of a dev server or a test run encodes both in the id. + */ +function describeServerFn(id: string): string { + try { + const bytes = Uint8Array.from( + atob(id.replace(/-/g, '+').replace(/_/g, '/')), + (char) => char.charCodeAt(0), + ) + const { file, export: exportName } = JSON.parse( + new TextDecoder().decode(bytes), + ) as { file: string; export: string } + return `"${exportName.replace(/_createServerFn_handler$/, '')}" (${file.replace(/\?.*$/, '')})` + } catch { + return `with the id "${id}"` + } +} diff --git a/packages/start-client-core/src/testing/vitest.ts b/packages/start-client-core/src/testing/vitest.ts new file mode 100644 index 0000000000..b366363502 --- /dev/null +++ b/packages/start-client-core/src/testing/vitest.ts @@ -0,0 +1,6 @@ +// The setup file Start's plugin adds to a Vitest run. After each test the +// mocks of `mockServerFn` and `mockMiddleware` are what they were before it. +import { beforeEach } from 'vitest' +import { saveMocks } from './mockStores' + +beforeEach(() => saveMocks()) diff --git a/packages/start-client-core/src/tests/serverFnMocks.test-d.ts b/packages/start-client-core/src/tests/serverFnMocks.test-d.ts new file mode 100644 index 0000000000..f8354fc2fb --- /dev/null +++ b/packages/start-client-core/src/tests/serverFnMocks.test-d.ts @@ -0,0 +1,58 @@ +import { expectTypeOf, test } from 'vitest' +import { createServerFn } from '../createServerFn' +import { mockServerFn } from '../testing/index' +import type { ServerFnMockContext } from '../testing/index' + +const getUser = createServerFn({ method: 'POST' }) + .validator((input: { id: string }) => input) + .handler(({ data }) => ({ id: data.id, age: data.id.length })) + +const getTime = createServerFn().handler(() => Date.now()) + +const search = createServerFn() + .validator((input?: { query: string }) => input) + .handler(({ data }) => data?.query.split(' ') ?? []) + +test('a mock gets the data the server function is called with', () => { + mockServerFn(getUser, (ctx) => { + expectTypeOf(ctx).toEqualTypeOf>() + expectTypeOf(ctx.data).toEqualTypeOf<{ id: string }>() + expectTypeOf(ctx.method).toEqualTypeOf<'GET' | 'POST'>() + expectTypeOf(ctx.headers).toEqualTypeOf() + expectTypeOf(ctx.signal).toEqualTypeOf() + return { id: ctx.data.id, age: 1 } + }) +}) + +test('a mock of a server function without input gets no data', () => { + mockServerFn(getTime, ({ data }) => { + expectTypeOf(data).toEqualTypeOf() + return 0 + }) +}) + +test('a mock of a server function with optional input may get no data', () => { + mockServerFn(search, ({ data }) => { + expectTypeOf(data).toEqualTypeOf<{ query: string } | undefined>() + return [] + }) +}) + +test('a mock returns what the handler returns, now or later', () => { + mockServerFn(getUser, () => ({ id: 'a', age: 1 })) + mockServerFn(getUser, async () => ({ id: 'a', age: 1 })) + + // @ts-expect-error the handler returns an object + mockServerFn(getUser, () => 'a') + // @ts-expect-error the age of the handler's object is a number + mockServerFn(getUser, async () => ({ id: 'a', age: 'old' })) + // @ts-expect-error the handler returns a number + mockServerFn(getTime, () => 'now') +}) + +test('only a server function can be mocked', () => { + const plain = async (options: { data: string }) => options.data + + // @ts-expect-error a plain function is no server function + mockServerFn(plain, () => '') +}) diff --git a/packages/start-client-core/tests/serverFnMocks.test.ts b/packages/start-client-core/tests/serverFnMocks.test.ts new file mode 100644 index 0000000000..4c1a3dd81e --- /dev/null +++ b/packages/start-client-core/tests/serverFnMocks.test.ts @@ -0,0 +1,192 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { redirect } from '@tanstack/router-core' +import { createMiddleware } from '../src/createMiddleware' +import { createServerFn } from '../src/createServerFn' +import { resetServerFnMocks, mockServerFn } from '../src/testing' +import { createClientRpc } from '../src/testing/client-rpc' +import type { AnyClientServerFn } from '../src/testing' + +/** The id the compiler of a dev server or a test run gives a server function. */ +function devId(name: string, file = '/src/greeting.ts') { + return Buffer.from( + JSON.stringify({ + file: `${file}?tss-serverfn-split`, + export: `${name}_createServerFn_handler`, + }), + ).toString('base64url') +} + +type Greet = AnyClientServerFn & + ((options: { data: string }) => Promise) + +/** + * A server function as the compiler leaves it in the client code of a test + * run: `.handler()` gets `createClientRpc(id)` in place of the handler. + */ +function clientServerFn( + id: string, + builder: { handler: unknown } = createServerFn({ method: 'POST' }), +) { + return (builder.handler as (extractedFn: unknown) => Greet)( + createClientRpc(id), + ) +} + +/** + * This package's own code is not compiled, so Start's isomorphic functions + * run their server implementation here and need a request context. + */ +function call(fn: () => Promise) { + return runWithStartContext( + { + getRouter() { + throw new Error('A server function call does not need a router') + }, + request: new Request('http://localhost/'), + startOptions: {}, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + fn, + ) +} + +afterEach(() => { + resetServerFnMocks() +}) + +describe('a server function call in a client test', () => { + test('resolves to what its mock returns for the data of the call', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, ({ data, method }) => `Hello ${data} by ${method}`) + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe( + 'Hello Ada by POST', + ) + }) + + test('resolves to what an async mock resolves to', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, async ({ data }) => `Hello ${data}`) + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe('Hello Ada') + }) + + test("runs the function's client middleware, and the mock gets the headers it adds", async () => { + const order: Array = [] + const greet = clientServerFn( + devId('greet'), + createServerFn({ method: 'POST' }).middleware([ + createMiddleware({ type: 'function' }).client(async ({ next }) => { + order.push('client middleware before') + const result = await next({ headers: { 'x-from-client': 'yes' } }) + order.push('client middleware after') + return result + }), + ]), + ) + mockServerFn(greet, ({ headers }) => { + order.push('mock') + return `x-from-client: ${headers.get('x-from-client')}` + }) + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe( + 'x-from-client: yes', + ) + expect(order).toEqual([ + 'client middleware before', + 'mock', + 'client middleware after', + ]) + }) + + test('rejects with what its mock throws', async () => { + const greet = clientServerFn(devId('greet')) + const failure = new Error('No such user') + mockServerFn(greet, () => { + throw failure + }) + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toBe(failure) + }) + + test('rejects with the redirect its mock throws', async () => { + const greet = clientServerFn(devId('greet')) + const toLogin = redirect({ to: '/login' }) + mockServerFn(greet, () => { + throw toLogin + }) + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toBe(toLogin) + }) + + test('is answered by the last mock of the function', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, () => 'first') + mockServerFn(greet, () => 'second') + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe('second') + }) + + test('without a mock rejects with an error that names the function and its file', async () => { + const greet = clientServerFn(devId('greet', '/src/features/greeting.ts')) + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toThrow( + 'The server function "greet" (/src/features/greeting.ts) was called in a client test, where no server runs. Answer the call with mockServerFn() before it is made.', + ) + }) + + test('without a mock rejects with an error that has the id, when the id names no function', async () => { + const greet = clientServerFn('3f9a1c') + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toThrow( + 'The server function with the id "3f9a1c" was called in a client test', + ) + }) + + test('has no mock after resetServerFnMocks', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, () => 'mocked') + + resetServerFnMocks() + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toThrow( + 'was called in a client test', + ) + }) + + test('of one function is not answered by the mock of another', async () => { + const greet = clientServerFn(devId('greet')) + const farewell = clientServerFn(devId('farewell')) + mockServerFn(greet, () => 'Hello') + + await expect(call(() => farewell({ data: 'Ada' }))).rejects.toThrow( + 'The server function "farewell"', + ) + }) +}) + +describe('mockServerFn', () => { + // The server's and the app's own versions of a server function have an id + // too, but no test answers their calls. + test('refuses a server function that was not compiled for a client test', () => { + const notForATest = Object.assign(async () => 'sent', { + url: '/_serverFn/abc', + serverFnMeta: { id: 'abc' }, + }) as unknown as Greet + + expect(() => mockServerFn(notForATest, () => 'mocked')).toThrow( + 'mockServerFn() needs a server function that the Start compiler compiled for a client test', + ) + }) + + test('refuses a function that is no server function', () => { + const plain = (async () => 'plain') as unknown as Greet + + expect(() => mockServerFn(plain, () => 'mocked')).toThrow( + 'mockServerFn() needs a server function', + ) + }) +}) diff --git a/packages/start-client-core/vite.config.ts b/packages/start-client-core/vite.config.ts index 71e163a1ed..597d0376ba 100644 --- a/packages/start-client-core/vite.config.ts +++ b/packages/start-client-core/vite.config.ts @@ -25,6 +25,9 @@ export default defineConfig(({ command }) => './src/index.tsx', './src/client/index.ts', './src/client-rpc/index.ts', + './src/testing/index.ts', + './src/testing/client-rpc.ts', + './src/testing/vitest.ts', './src/hydration/constants.ts', './src/hydration.ts', './src/hydration/runtime.ts', diff --git a/packages/start-plugin-core/AGENTS.md b/packages/start-plugin-core/AGENTS.md index cd73bbf307..dcea879e59 100644 --- a/packages/start-plugin-core/AGENTS.md +++ b/packages/start-plugin-core/AGENTS.md @@ -5,3 +5,5 @@ - Compiler output must match runtime contracts in `start-client-core`, `start-fn-stubs`, and `start-server-core`. For `createServerFn`, cover client, SSR caller, and server-provider output separately in [`tests/createServerFn/createServerFn.test.ts`](tests/createServerFn/createServerFn.test.ts). - Use a built Start e2e app to validate generated imports and runtime behavior together; compiler snapshots alone do not exercise that integration. - The shared compiler serves both Vite and Rsbuild. For shared compiler changes, check the relevant adapter suites in `tests/vite/` and `tests/rsbuild/`, plus affected Start e2e modes for build, server-function, or HMR behavior. +- A test run (`isVitestRun`) gets its own config plan. It names Start's packages in `resolve.noExternal` with regular expressions, a documented workaround for Vitest (`createTestRunNoExternal` in [`src/vite/planning.ts`](src/vite/planning.ts)). A run inside this repository cannot show a mistake there; check changes with the `test:e2e:installed` script of `e2e/react-start/vitest-library` ([why](../../scripts/e2e/run-as-installed.md)). +- Vitest keeps compiled modules on disk across runs, so in a test run the compiler may never see a file. Nothing a test run needs may depend on what the compiler recorded in the process (the server function resolver of a test run skips the id check for that reason). `test:e2e:cached` of `e2e/react-start/vitest-*` runs the tests from that cache. diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index 1945ab7ba6..ca1183a6c0 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -116,6 +116,7 @@ "@tanstack/router-generator": "workspace:*", "@tanstack/router-plugin": "workspace:*", "@tanstack/router-utils": "workspace:*", + "@tanstack/start-client-core": "workspace:*", "@tanstack/start-server-core": "workspace:*", "exsolve": "^1.1.3", "lightningcss": "^1.33.0", diff --git a/packages/start-plugin-core/src/config-context.ts b/packages/start-plugin-core/src/config-context.ts index 825860a595..dc8bc895ad 100644 --- a/packages/start-plugin-core/src/config-context.ts +++ b/packages/start-plugin-core/src/config-context.ts @@ -3,6 +3,7 @@ import { createNormalizedOutputDirectories, deriveRouterBasepath, resolveStartEntryPlan, + resolveStartTestEntryPlan, } from './planning' import type { TanStackStartOutputConfig } from './schema' import type { @@ -15,6 +16,11 @@ export interface StartConfigContext { resolvedStartConfig: ResolvedStartConfig getConfig: GetConfigFn resolveEntries: () => ReturnType + /** + * The entries of a project under a test runner. The router entry is + * optional there, see `isTestRun`. + */ + resolveTestEntries: () => ReturnType } export function createStartConfigContext(opts: { @@ -25,6 +31,12 @@ export function createStartConfigContext(opts: { core: { framework: TanStackStartCoreOptions['framework'] }, root: string, ) => TanStackStartOutputConfig + /** + * Whether the bundler runs for a test runner. `getConfig` then does not + * require a router entry: `resolvedStartConfig.routerFilePath` is an empty + * string when the project has none. + */ + isTestRun?: () => boolean }): StartConfigContext { const resolvedStartConfig: ResolvedStartConfig = { root: '', @@ -48,6 +60,9 @@ export function createStartConfigContext(opts: { let resolvedEntryPlanCache: | ReturnType | undefined + let resolvedTestEntryPlanCache: + | ReturnType + | undefined function requireRoot(): string { if (!resolvedStartConfig.root) { @@ -89,9 +104,33 @@ export function createStartConfigContext(opts: { return resolvedEntryPlanCache } + function getResolvedTestEntryPlan() { + if (resolvedTestEntryPlanCache) { + return resolvedTestEntryPlanCache + } + + resolvedTestEntryPlanCache = resolveStartTestEntryPlan({ + root: requireRoot(), + startConfig: getStartConfig(), + defaultEntryPaths: opts.corePluginOpts.defaultEntryPaths, + }) + + Object.assign(resolvedStartConfig, { + srcDirectory: resolvedTestEntryPlanCache.srcDirectory, + startFilePath: resolvedTestEntryPlanCache.startFilePath, + routerFilePath: resolvedTestEntryPlanCache.routerFilePath ?? '', + }) + + return resolvedTestEntryPlanCache + } + const getConfig: GetConfigFn = () => { const startConfig = getStartConfig() - getResolvedEntryPlan() + if (opts.isTestRun?.()) { + getResolvedTestEntryPlan() + } else { + getResolvedEntryPlan() + } return { startConfig, resolvedStartConfig } } @@ -100,10 +139,15 @@ export function createStartConfigContext(opts: { return getResolvedEntryPlan() } + function resolveTestEntries() { + return getResolvedTestEntryPlan() + } + return { resolvedStartConfig, getConfig, resolveEntries, + resolveTestEntries, } } diff --git a/packages/start-plugin-core/src/planning.ts b/packages/start-plugin-core/src/planning.ts index 11f25d14d3..d9f703300c 100644 --- a/packages/start-plugin-core/src/planning.ts +++ b/packages/start-plugin-core/src/planning.ts @@ -89,11 +89,47 @@ export function createServerFnBasePath(opts: { return joinPaths(['/', opts.routerBasepath, opts.serverFnBase, '/']) } +/** + * The entries of a project whose code runs under a test runner. Such a project + * may be an app or a package that only uses Start's compile-time APIs, so the + * router entry is optional, unless the config names one. + */ +export interface ResolvedStartTestEntryPlan extends Omit< + ResolvedStartEntryPlan, + 'routerFilePath' | 'entryPaths' +> { + routerFilePath: string | undefined + entryPaths: Omit & { + router: string | undefined + } +} + export function resolveStartEntryPlan(opts: { root: string startConfig: TanStackStartOutputConfig defaultEntryPaths: TanStackStartCoreOptions['defaultEntryPaths'] }): ResolvedStartEntryPlan { + return resolveEntryPlan(opts, true) +} + +export function resolveStartTestEntryPlan(opts: { + root: string + startConfig: TanStackStartOutputConfig + defaultEntryPaths: TanStackStartCoreOptions['defaultEntryPaths'] +}): ResolvedStartTestEntryPlan { + return resolveEntryPlan(opts, false) +} + +function resolveEntryPlan( + opts: { + root: string + startConfig: TanStackStartOutputConfig + defaultEntryPaths: TanStackStartCoreOptions['defaultEntryPaths'] + }, + routerEntryRequired: TRouterRequired, +): TRouterRequired extends true + ? ResolvedStartEntryPlan + : ResolvedStartTestEntryPlan { const srcDirectory = join(opts.root, opts.startConfig.srcDirectory) const startFilePath = resolveEntry({ @@ -109,7 +145,9 @@ export function resolveStartEntryPlan(opts: { configuredEntry: opts.startConfig.router.entry, defaultEntry: 'router', resolvedSrcDirectory: srcDirectory, - required: true, + // (a configured entry has to exist: a typo in the config is not a project + // without a router) + required: routerEntryRequired || !!opts.startConfig.router.entry, }) const clientEntryPath = resolveEntry({ @@ -138,5 +176,7 @@ export function resolveStartEntryPlan(opts: { start: startFilePath ?? opts.defaultEntryPaths.start, router: routerFilePath, }, - } + } as TRouterRequired extends true + ? ResolvedStartEntryPlan + : ResolvedStartTestEntryPlan } diff --git a/packages/start-plugin-core/src/start-router-plugin/has-route-tree-sources.ts b/packages/start-plugin-core/src/start-router-plugin/has-route-tree-sources.ts new file mode 100644 index 0000000000..bf25520a8f --- /dev/null +++ b/packages/start-plugin-core/src/start-router-plugin/has-route-tree-sources.ts @@ -0,0 +1,29 @@ +import { readdirSync } from 'node:fs' +import { rootPathId } from '@tanstack/router-generator' +import type { Config } from '@tanstack/router-generator' + +/** + * Whether a project has what a route tree is generated from: a router entry, + * and either a virtual route config or a routes directory with a root route. + * + * A package that only uses Start's compile-time APIs has neither, and under a + * test runner nothing is generated for it. + */ +export function hasRouteTreeSources(opts: { + routerFilePath: string + generatorConfig: Pick +}): boolean { + if (!opts.routerFilePath) { + return false + } + if (opts.generatorConfig.virtualRouteConfig) { + return true + } + try { + return readdirSync(opts.generatorConfig.routesDirectory).some((name) => + name.startsWith(`${rootPathId}.`), + ) + } catch { + return false + } +} diff --git a/packages/start-plugin-core/src/test-mode.ts b/packages/start-plugin-core/src/test-mode.ts new file mode 100644 index 0000000000..596b9cff6a --- /dev/null +++ b/packages/start-plugin-core/src/test-mode.ts @@ -0,0 +1,11 @@ +/** + * Whether a bundler config is being resolved by Vitest in order to run tests. + * + * Vitest resolves its config with the `serve` command and, unless the user + * picks another one, the `test` mode. `process.env.VITEST` alone is not + * enough: it is also set in the processes that run the test files, where a + * test may start a real dev server or a build of the app. + */ +export function isVitestRun(env: { command: string; mode: string }): boolean { + return env.command === 'serve' && env.mode === 'test' && !!process.env.VITEST +} diff --git a/packages/start-plugin-core/src/types.ts b/packages/start-plugin-core/src/types.ts index db94e343d5..d96b660d98 100644 --- a/packages/start-plugin-core/src/types.ts +++ b/packages/start-plugin-core/src/types.ts @@ -145,6 +145,10 @@ export interface TanStackStartCoreOptions { export interface ResolvedStartConfig { root: string startFilePath: string | undefined + /** + * An empty string when a project that runs under a test runner has no + * router entry. An app always has one. + */ routerFilePath: string srcDirectory: string basePaths: NormalizedBasePaths diff --git a/packages/start-plugin-core/src/vite/planning.ts b/packages/start-plugin-core/src/vite/planning.ts index fa11b98c47..4e9160f7c6 100644 --- a/packages/start-plugin-core/src/vite/planning.ts +++ b/packages/start-plugin-core/src/vite/planning.ts @@ -8,7 +8,10 @@ import { } from '../constants' import { getBundlerOptions } from '../utils' import type { CompileStartFrameworkOptions } from '../types' -import type { ResolvedStartEntryPlan } from '../planning' +import type { + ResolvedStartEntryPlan, + ResolvedStartTestEntryPlan, +} from '../planning' import type * as vite from 'vite' export interface ViteResolvedEntryAliases { @@ -114,11 +117,7 @@ export function createViteConfigPlan(opts: { }), }, resolve: { - noExternal: [ - '@tanstack/start**', - `@tanstack/${opts.framework}-start**`, - ...opts.noExternal, - ], + noExternal: createNoExternal(opts), alias: { ...opts.entryAliases.alias, }, @@ -126,6 +125,130 @@ export function createViteConfigPlan(opts: { } satisfies Pick } +/** + * The part of the Vite config that code needs when Vitest runs it: Start's + * packages go through the compiler instead of being pre-bundled or + * externalized, and the entries that exist can be imported. Nothing here + * plans a build or a dev server of the app. + */ +export function createViteTestConfigPlan(opts: { + framework: CompileStartFrameworkOptions + entryPaths: ResolvedStartTestEntryPlan['entryPaths'] + optimizeDepsExclude: Array + noExternal: Array +}) { + const alias: Record = { + [ENTRY_POINTS.client]: normalizePath(opts.entryPaths.client), + [ENTRY_POINTS.server]: normalizePath(opts.entryPaths.server), + [ENTRY_POINTS.start]: normalizePath(opts.entryPaths.start), + } + // Without a router entry the alias stays unset, and the placeholder of + // `testRunRouterEntryPlugin` answers the import. + if (opts.entryPaths.router) { + alias[ENTRY_POINTS.router] = normalizePath(opts.entryPaths.router) + } + // Compiled client code imports `createClientRpc` from this module. No + // server takes the request of a client test, so the call goes to the mock + // that `mockServerFn` registered instead. + alias[`@tanstack/${opts.framework}-start/client-rpc`] = + `@tanstack/${opts.framework}-start/testing/client-rpc` + + return { + environments: { + [START_ENVIRONMENT_NAMES.client]: { + optimizeDeps: { + exclude: opts.optimizeDepsExclude, + include: createTestRunOptimizeDepsInclude(opts.framework), + }, + }, + }, + resolve: { + noExternal: createTestRunNoExternal(opts), + alias, + }, + } satisfies Pick +} + +/** + * Dependencies of Router Core that a browser test loads, by a path from the + * Start package of the project, which also resolves when the project depends + * on Start only. + * + * Start's packages are not pre-bundled, so Vite's scan at start-up does not + * see what they import. Vite found these when a test first imported them, + * pre-bundled them and reloaded the page. Vitest's browser mode does not + * survive that reliably: a test iframe could fail to start ("did not become + * ready within 60000ms"). + */ +function createTestRunOptimizeDepsInclude( + framework: CompileStartFrameworkOptions, +): Array { + const routerCore = `@tanstack/${framework}-start > @tanstack/${framework}-router > @tanstack/router-core` + return ['cookie-es', 'seroval', 'seroval-plugins/web'].map( + (dependency) => `${routerCore} > ${dependency}`, + ) +} + +function createNoExternal(opts: { + framework: CompileStartFrameworkOptions + noExternal: Array +}) { + return [ + '@tanstack/start**', + `@tanstack/${opts.framework}-start**`, + ...opts.noExternal, + ] +} + +/** + * The packages of `createNoExternal` for a test runner, with Start's own + * packages named by regular expressions instead of wildcards. + * + * WORKAROUND for Vitest, 4.0.5 to 5.1 at least. It was not reported upstream + * when this was written; link the issue here once there is one. Vitest + * decides by the path of a file whether Vite compiles it or Node loads it as + * it is, and reads `resolve.noExternal` for that. It turns each `*` of a + * string into `[\w/]+` (`processWildcard` in Vitest's + * `packages/vitest/src/node/plugins/testConfig.ts`, added by + * vitest-dev/vitest#8862), which does not match a `-`. So + * `@tanstack/start**` did not match `@tanstack/start-client-core`, nor any + * other package with a dash after `start`. + * + * What went wrong: in a project that installs Start from the registry, a + * jsdom, happy-dom or Node test ran those packages without the Start + * compiler. Their functions with a client and a server implementation then + * ran the server one in a client test, and a server function call failed + * with "No Start context found in AsyncLocalStorage". Inside this repository + * nothing fails, because Vitest always compiles a linked workspace package. + * + * Why regular expressions: Vitest tests one against the path of the file as + * it is, and Vite tests it against the name of the package. The expressions + * below match the name where it is the whole string, and where it follows + * `/node_modules/` in a path. + * + * The app's config keeps the wildcards, which Vite matches as intended. + * + * The regression test is the run of `e2e/react-start/vitest-library` as a + * user's project (`scripts/e2e/run-as-installed.md`). Remove this function, + * and use `createNoExternal`, once the Vitest versions Start is used with + * match a `-` with a wildcard. + */ +function createTestRunNoExternal(opts: { + framework: CompileStartFrameworkOptions + noExternal: Array +}): Array { + return [ + startPackagesPattern('start'), + startPackagesPattern(`${opts.framework}-start`), + ...opts.noExternal, + ] +} + +/** Matches the packages whose name starts with `@tanstack/`. */ +function startPackagesPattern(prefix: string) { + return new RegExp(`(?:^|/node_modules/)@tanstack/${prefix}`) +} + export function createViteDefineConfig(opts: { command: 'serve' | 'build' mode: string | undefined diff --git a/packages/start-plugin-core/src/vite/plugin.ts b/packages/start-plugin-core/src/vite/plugin.ts index 5e5bca4a2e..c712db37f2 100644 --- a/packages/start-plugin-core/src/vite/plugin.ts +++ b/packages/start-plugin-core/src/vite/plugin.ts @@ -7,6 +7,7 @@ import { createStartConfigContext, } from '../config-context' import { START_ENVIRONMENT_NAMES } from '../constants' +import { isVitestRun } from '../test-mode' import { createServerFnBasePath, normalizePublicBase, @@ -20,6 +21,7 @@ import { createViteConfigPlan, createViteDefineConfig, createViteResolvedEntryAliases, + createViteTestConfigPlan, } from './planning' import { devServerPlugin } from './dev-server-plugin/plugin' import { previewServerPlugin } from './preview-server-plugin/plugin' @@ -37,6 +39,11 @@ import { } from './output-directory' import { postServerBuild } from './post-server-build' import { serializationAdaptersPlugin } from './serialization-adapters-plugin' +import { + excludeFromTestRuns, + testRunRouterEntryPlugin, + vitestSetupFilePlugin, +} from './test-run' import type { TanStackStartVitePluginCoreOptions, ViteRscForwardSsrResolverStrategy, @@ -50,10 +57,17 @@ export function tanStackStartVite( ): Array { const normalizedStartPluginOpts = startPluginOpts ?? {} + // Whether Vitest resolves this config to run tests. The plugins below then + // compile code as in the app, but none of them serves or builds the app, + // and a project without a router entry or without routes is fine. + let testRun = false + const isTestRun = () => testRun + const configContext = createStartConfigContext({ corePluginOpts, startPluginOpts: normalizedStartPluginOpts, parseConfig: parseStartConfig, + isTestRun, }) const { getConfig, resolvedStartConfig } = configContext const serverFnProviderEnv = corePluginOpts.providerEnvironmentName @@ -91,7 +105,9 @@ export function tanStackStartVite( { name: 'tanstack-start-core:config', enforce: 'pre', - async config(viteConfig, { command }) { + async config(viteConfig, env) { + const { command } = env + testRun = isVitestRun(env) const publicBase = normalizePublicBase(viteConfig.base) applyResolvedBaseAndOutput({ resolvedStartConfig, @@ -126,12 +142,6 @@ export function tanStackStartVite( routerBasepath, serverFnBase: startConfig.serverFns.base, }) - const resolvedEntryPlan = configContext.resolveEntries() - - const entryAliases = createViteResolvedEntryAliases({ - entryPaths: resolvedEntryPlan.entryPaths, - }) - const startPackageName = `@tanstack/${corePluginOpts.framework}-start` as const @@ -164,6 +174,45 @@ export function tanStackStartVite( }, }) + const define = createViteDefineConfig({ + command, + mode: viteConfig.mode, + serverFnBase: TSS_SERVER_FN_BASE, + routerBasepath, + spaEnabled: startConfig.spa?.enabled, + // The dev server that serves these styles does not exist in a test run. + devSsrStylesEnabled: !testRun && startConfig.dev.ssrStyles.enabled, + devSsrStylesBasepath: + startConfig.dev.ssrStyles.basepath ?? + resolvedStartConfig.basePaths.publicBase, + inlineCssEnabled: + command === 'build' && startConfig.server.build.inlineCss.enabled, + staticNodeEnv: startConfig.server.build.staticNodeEnv, + disableCsrfMiddlewareWarning: + startConfig.serverFns.disableCsrfMiddlewareWarning, + }) + + if (testRun) { + const testConfigPlan = createViteTestConfigPlan({ + framework: corePluginOpts.framework, + entryPaths: configContext.resolveTestEntries().entryPaths, + optimizeDepsExclude: crawlFrameworkPkgsResult.optimizeDeps.exclude, + noExternal: crawlFrameworkPkgsResult.ssr.noExternal.sort(), + }) + + return { + environments: testConfigPlan.environments, + resolve: testConfigPlan.resolve, + define, + } + } + + const resolvedEntryPlan = configContext.resolveEntries() + + const entryAliases = createViteResolvedEntryAliases({ + entryPaths: resolvedEntryPlan.entryPaths, + }) + const viteConfigPlan = createViteConfigPlan({ viteConfig, command, @@ -182,22 +231,7 @@ export function tanStackStartVite( appType: viteConfig.appType ?? 'custom', environments: viteConfigPlan.environments, resolve: viteConfigPlan.resolve, - define: createViteDefineConfig({ - command, - mode: viteConfig.mode, - serverFnBase: TSS_SERVER_FN_BASE, - routerBasepath, - spaEnabled: startConfig.spa?.enabled, - devSsrStylesEnabled: startConfig.dev.ssrStyles.enabled, - devSsrStylesBasepath: - startConfig.dev.ssrStyles.basepath ?? - resolvedStartConfig.basePaths.publicBase, - inlineCssEnabled: - command === 'build' && startConfig.server.build.inlineCss.enabled, - staticNodeEnv: startConfig.server.build.staticNodeEnv, - disableCsrfMiddlewareWarning: - startConfig.serverFns.disableCsrfMiddlewareWarning, - }), + define, builder: { sharedPlugins: true, async buildApp(builder) { @@ -211,10 +245,12 @@ export function tanStackStartVite( } }, }, - createPostBuildPlugin({ - getConfig, - postServerBuild, - }), + excludeFromTestRuns( + createPostBuildPlugin({ + getConfig, + postServerBuild, + }), + ), // Server function plugin handles: // 1. Identifying createServerFn().handler() calls // 2. Extracting server functions to separate modules @@ -230,6 +266,7 @@ export function tanStackStartVite( serverFnProviderModuleDirectives: corePluginOpts.serverFnProviderModuleDirectives, providerEnvName: serverFnProviderEnv, + isTestRun, }), importProtectionPlugin({ getConfig, @@ -237,12 +274,21 @@ export function tanStackStartVite( environments, providerEnvName: serverFnProviderEnv, }), - tanStackStartRouter(normalizedStartPluginOpts, getConfig, corePluginOpts), + tanStackStartRouter( + normalizedStartPluginOpts, + getConfig, + corePluginOpts, + isTestRun, + ), loadEnvPlugin(), - createDevClientEntryPlugin({ - framework: corePluginOpts.framework, - getClientEntry: () => configContext.resolveEntries().entryPaths.client, - }), + vitestSetupFilePlugin(isTestRun), + testRunRouterEntryPlugin(), + excludeFromTestRuns( + createDevClientEntryPlugin({ + framework: corePluginOpts.framework, + getClientEntry: () => configContext.resolveEntries().entryPaths.client, + }), + ), startManifestPlugin({ getConfig, }), @@ -252,18 +298,20 @@ export function tanStackStartVite( // before passing to the SSR handler. // Registered BEFORE devServerPlugin so this middleware is added to the Connect stack first, // ensuring all subsequent middlewares (CSS, SSR, etc.) see the rewritten URL. - createDevBaseRewritePlugin({ - shouldRewriteDevBase: () => needsDevBaseRewrite, - resolvedStartConfig, - }), - devServerPlugin({ - getConfig, - devSsrStylesEnabled: - normalizedStartPluginOpts.dev?.ssrStyles?.enabled ?? true, - installDevServerMiddleware: - normalizedStartPluginOpts.vite?.installDevServerMiddleware, - }), - previewServerPlugin(), + excludeFromTestRuns([ + createDevBaseRewritePlugin({ + shouldRewriteDevBase: () => needsDevBaseRewrite, + resolvedStartConfig, + }), + devServerPlugin({ + getConfig, + devSsrStylesEnabled: + normalizedStartPluginOpts.dev?.ssrStyles?.enabled ?? true, + installDevServerMiddleware: + normalizedStartPluginOpts.vite?.installDevServerMiddleware, + }), + previewServerPlugin(), + ]), ...(corePluginOpts.serializationAdapters?.length ? [ serializationAdaptersPlugin({ diff --git a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts index 3a93e286d1..de224bc8f3 100644 --- a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts @@ -200,11 +200,24 @@ function invalidateModuleNodes( } } -function getDevServerFnValidatorModule(): string { - return ` -export async function getServerFnById(id, _access) { +/** + * The resolver of a dev server. A function id names the file and the export + * of the function. `validateId` first asks the compiler whether it compiled + * a server function with that id, because a dev server takes ids from HTTP + * requests. + * + * A test run passes `validateId: false`. No request reaches it from outside, + * and a test runner can serve a compiled file from its cache, so that the + * compiler never sees the file and has no record of its functions. + */ +function getDevServerFnResolverModule(opts: { validateId: boolean }): string { + const validateId = opts.validateId + ? ` const validateIdImport = ${JSON.stringify(validateServerFnIdVirtualModule)} + '?id=' + id - await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport) + await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport)` + : '' + return ` +export async function getServerFnById(id, _access) {${validateId} const decoded = Buffer.from(id, 'base64url').toString('utf8') const devServerFn = JSON.parse(decoded) const mod = await import(/* @vite-ignore */ devServerFn.file) @@ -243,6 +256,11 @@ export interface StartCompilerPluginOptions { * The Vite environment name for the server function provider. */ providerEnvName: string + /** + * Whether the bundler runs for a test runner. The resolver of a test run + * finds a server function without the compiler's record of it. + */ + isTestRun?: () => boolean } export function startCompilerPlugin( @@ -670,7 +688,9 @@ export function startCompilerPlugin( } if (this.environment.mode !== 'build') { - return getDevServerFnValidatorModule() + return getDevServerFnResolverModule({ + validateId: !opts.isTestRun?.(), + }) } // When SSR is the provider, server-only-referenced functions aren't in the manifest, diff --git a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts index 8df06af4f5..97172bae93 100644 --- a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts @@ -8,6 +8,7 @@ import { normalizePath } from 'vite' import { VITE_ENVIRONMENT_NAMES } from '../../constants' import { startGeneratorConfig } from '../../start-router-plugin/generator-config' import { pruneServerOnlySubtrees } from '../../start-router-plugin/pruneServerOnlySubtrees' +import { hasRouteTreeSources } from '../../start-router-plugin/has-route-tree-sources' import { SERVER_PROP } from '../../start-router-plugin/constants' import { escapeRegExp } from '../../utils' import type { GetConfigFn } from '../../types' @@ -34,6 +35,13 @@ export function tanStackStartRouter( startPluginOpts: TanStackStartInputConfig, getConfig: GetConfigFn, corePluginOpts: TanStackStartVitePluginCoreOptions, + /** + * Whether Vitest resolves the config to run tests. The route tree is then + * generated once, at startup, and only for a project that has routes; route + * files are never written; and a route file does not have to be known to + * the generator to lose its server-only options in client code. + */ + isTestRun: () => boolean = () => false, ): Array { const routerPluginContext = createRouterPluginContext() @@ -109,6 +117,10 @@ export function tanStackStartRouter( return null } if (!generatorInstance) { + if (isTestRun()) { + // No generator runs for a project without routes. + return null + } throw new Error('Generator instance not initialized') } const crawlingResult = await generatorInstance.getCrawlingResult() @@ -147,21 +159,38 @@ export function tanStackStartRouter( clientRouteTree: clientTreeGeneratorPlugin, }), routerPluginContext, + { + enabled: ({ config }) => + !isTestRun() || + hasRouteTreeSources({ + routerFilePath: getConfig().resolvedStartConfig.routerFilePath, + generatorConfig: config, + }), + watch: () => !isTestRun(), + writeRouteFiles: () => !isTestRun(), + }, + ), + tanStackRouterCodeSplitter( + () => { + const routerConfig = getConfig().startConfig.router + return { + ...routerConfig, + codeSplittingOptions: { + ...routerConfig.codeSplittingOptions, + deleteNodes: ['ssr', 'server', 'headers'], + // Vitest has no HMR. + addHmr: !isTestRun(), + }, + plugin: { + vite: { environmentName: VITE_ENVIRONMENT_NAMES.client }, + }, + } + }, + routerPluginContext, + { + deleteNodesInUnknownRoutes: isTestRun, + }, ), - tanStackRouterCodeSplitter(() => { - const routerConfig = getConfig().startConfig.router - return { - ...routerConfig, - codeSplittingOptions: { - ...routerConfig.codeSplittingOptions, - deleteNodes: ['ssr', 'server', 'headers'], - addHmr: true, - }, - plugin: { - vite: { environmentName: VITE_ENVIRONMENT_NAMES.client }, - }, - } - }, routerPluginContext), tanStackRouterCodeSplitter(() => { const routerConfig = getConfig().startConfig.router return { diff --git a/packages/start-plugin-core/src/vite/test-run.ts b/packages/start-plugin-core/src/vite/test-run.ts new file mode 100644 index 0000000000..1a9a2ff644 --- /dev/null +++ b/packages/start-plugin-core/src/vite/test-run.ts @@ -0,0 +1,92 @@ +import { fileURLToPath } from 'node:url' +import { normalizePath } from 'vite' +import { ENTRY_POINTS } from '../constants' +import { isVitestRun } from '../test-mode' +import { createVirtualModule } from './createVirtualModule' +import type { Plugin, PluginOption } from 'vite' + +/** + * Leaves the given plugins out of a config that Vitest resolves to run + * tests. They serve or build the app, which a test run does not do. + */ +export function excludeFromTestRuns(option: PluginOption): PluginOption { + if (Array.isArray(option)) { + return option.map(excludeFromTestRuns) + } + if (!option) { + return option + } + if (option instanceof Promise) { + return option.then(excludeFromTestRuns) + } + + const plugin = option as Plugin + const apply = plugin.apply + return { + ...plugin, + apply(config, env) { + if (isVitestRun(env)) { + return false + } + if (typeof apply === 'function') { + return apply.call(this, config, env) + } + return apply === undefined || apply === env.command + }, + } +} + +/** The part of a Vitest project that a plugin may change. */ +interface VitestProject { + config: { setupFiles: Array } +} + +/** Vitest calls this hook of a Vite plugin for each of its projects (3.1+). */ +interface VitestPluginHooks { + configureVitest?: (context: { project: VitestProject }) => void +} + +/** + * Adds Start's setup file to every Vitest project of a test run. The file + * ends the mocks of `mockServerFn` and `mockMiddleware` with the test that + * registered them. + * + * The file goes in through `configureVitest`, because `test.setupFiles` + * returned from the `config` hook only reaches a browser project. + */ +export function vitestSetupFilePlugin(isTestRun: () => boolean): Plugin { + const plugin: Plugin & VitestPluginHooks = { + name: 'tanstack-start-core:vitest-setup-file', + configureVitest({ project }) { + if (!isTestRun()) { + return + } + const setupFile = normalizePath( + fileURLToPath( + import.meta.resolve('@tanstack/start-client-core/testing/vitest'), + ), + ) + if (!project.config.setupFiles.includes(setupFile)) { + project.config.setupFiles.push(setupFile) + } + }, + } + return plugin +} + +/** + * Answers the import of the router entry in a test run of a project that has + * none, such as a package that only uses Start's compile-time APIs. Start's + * server code imports the entry, and without an answer Vite fails to load + * that code at all. A project with a router entry has an alias for the + * import, which wins over this placeholder. + */ +export function testRunRouterEntryPlugin(): Plugin { + return createVirtualModule({ + name: 'tanstack-start-core:test-run-router-entry', + moduleId: ENTRY_POINTS.router, + enforce: 'pre', + apply: (_config, env) => isVitestRun(env), + load: () => 'export function getRouter() {}\n', + }) +} diff --git a/packages/start-plugin-core/tests/entry-planning.test.ts b/packages/start-plugin-core/tests/entry-planning.test.ts index b8a71675a1..66b32a7097 100644 --- a/packages/start-plugin-core/tests/entry-planning.test.ts +++ b/packages/start-plugin-core/tests/entry-planning.test.ts @@ -9,7 +9,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { normalize } from 'pathe' import { afterEach, describe, expect, test } from 'vitest' -import { resolveStartEntryPlan } from '../src/planning' +import { + resolveStartEntryPlan, + resolveStartTestEntryPlan, +} from '../src/planning' import { parseStartConfig as parseRsbuildStartConfig } from '../src/rsbuild/schema' import { parseStartConfig as parseViteStartConfig } from '../src/vite/schema' @@ -114,3 +117,48 @@ describe('server entry planning', () => { }, ) }) + +describe('entry planning for a project under a test runner', () => { + // A package that only uses Start's compile-time APIs has no router. + test('plans a project without a router entry', () => { + const root = mkdtempSync(join(tmpdir(), 'tanstack-start-entry-')) + roots.add(root) + mkdirSync(join(root, 'src')) + const startConfig = parseViteStartConfig({}, corePluginOpts, root) + + const plan = resolveStartTestEntryPlan({ + root, + startConfig, + defaultEntryPaths, + }) + + expect(plan.routerFilePath).toBeUndefined() + expect(plan.entryPaths).toEqual({ + ...defaultEntryPaths, + router: undefined, + }) + }) + + test('plans the entries of an app as the app does', () => { + const root = createRoot() + writeFileSync(join(root, 'src', 'start.ts'), 'export {}\n') + const startConfig = parseViteStartConfig({}, corePluginOpts, root) + const opts = { root, startConfig, defaultEntryPaths } + + expect(resolveStartTestEntryPlan(opts)).toEqual(resolveStartEntryPlan(opts)) + }) + + // A typo in the config is not a project without a router. + test('fails for a configured router entry that does not exist', () => { + const root = createRoot() + const startConfig = parseViteStartConfig( + { router: { entry: './missing-router.ts' } }, + corePluginOpts, + root, + ) + + expect(() => + resolveStartTestEntryPlan({ root, startConfig, defaultEntryPaths }), + ).toThrow('missing-router.ts') + }) +}) diff --git a/packages/start-plugin-core/tests/has-route-tree-sources.test.ts b/packages/start-plugin-core/tests/has-route-tree-sources.test.ts new file mode 100644 index 0000000000..f8539693ab --- /dev/null +++ b/packages/start-plugin-core/tests/has-route-tree-sources.test.ts @@ -0,0 +1,86 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, test } from 'vitest' +import { hasRouteTreeSources } from '../src/start-router-plugin/has-route-tree-sources' + +const roots = new Set() + +function createRoutesDirectory(files: Array) { + const root = mkdtempSync(join(tmpdir(), 'tanstack-start-routes-')) + roots.add(root) + const routesDirectory = join(root, 'src', 'routes') + mkdirSync(routesDirectory, { recursive: true }) + for (const file of files) { + writeFileSync(join(routesDirectory, file), 'export {}\n') + } + return routesDirectory +} + +afterEach(() => { + for (const root of roots) { + rmSync(root, { recursive: true, force: true }) + } + roots.clear() +}) + +describe('hasRouteTreeSources', () => { + test('is true for a router entry and a routes directory with a root route', () => { + const routesDirectory = createRoutesDirectory(['__root.tsx', 'index.tsx']) + + expect( + hasRouteTreeSources({ + routerFilePath: '/app/src/router.tsx', + generatorConfig: { routesDirectory }, + }), + ).toBe(true) + }) + + test('is false without a router entry', () => { + const routesDirectory = createRoutesDirectory(['__root.tsx', 'index.tsx']) + + expect( + hasRouteTreeSources({ + routerFilePath: '', + generatorConfig: { routesDirectory }, + }), + ).toBe(false) + }) + + test('is false for a routes directory without a root route', () => { + const routesDirectory = createRoutesDirectory(['index.tsx', '__rooted.tsx']) + + expect( + hasRouteTreeSources({ + routerFilePath: '/app/src/router.tsx', + generatorConfig: { routesDirectory }, + }), + ).toBe(false) + }) + + test('is false when the routes directory does not exist', () => { + const routesDirectory = join(createRoutesDirectory([]), 'missing') + + expect( + hasRouteTreeSources({ + routerFilePath: '/app/src/router.tsx', + generatorConfig: { routesDirectory }, + }), + ).toBe(false) + }) + + // Virtual routes name their root route file themselves. + test('is true for a virtual route config, whatever the routes directory holds', () => { + const routesDirectory = join(createRoutesDirectory([]), 'missing') + + expect( + hasRouteTreeSources({ + routerFilePath: '/app/src/router.tsx', + generatorConfig: { + routesDirectory, + virtualRouteConfig: './routes.ts', + }, + }), + ).toBe(true) + }) +}) diff --git a/packages/start-plugin-core/tests/integration/start-app.ts b/packages/start-plugin-core/tests/integration/start-app.ts index ca5603ac2c..471932838f 100644 --- a/packages/start-plugin-core/tests/integration/start-app.ts +++ b/packages/start-plugin-core/tests/integration/start-app.ts @@ -7,7 +7,8 @@ * * The app links the workspace's `@tanstack/react-start` and the * `@tanstack/react-router`, `react` and `react-dom` it uses, as an installed - * app would. + * app would. A package that only uses Start's compile-time APIs links fewer + * (`createStartApp`'s `dependencies`). */ import { realpathSync } from 'node:fs' import { @@ -64,10 +65,18 @@ export interface StartApp { * `vite` or `rsbuild` in the app's directory does (the generator and * Rsbuild's virtual modules write under it). Both are undone when the test * finishes. + * + * `dependencies` are the packages the app depends on besides + * `@tanstack/react-start`: only these resolve from the app's directory. */ export async function createStartApp( files: Record, prefix = 'start-app-', + dependencies: Array = [ + '@tanstack/react-router', + 'react', + 'react-dom', + ], ): Promise { const root = realpathSync(await mkdtemp(path.join(os.tmpdir(), prefix))) const cwd = process.cwd() @@ -79,7 +88,7 @@ export async function createStartApp( const links: Record = { '@tanstack/react-start': reactStartDir, } - for (const name of ['@tanstack/react-router', 'react', 'react-dom']) { + for (const name of dependencies) { links[name] = realpathSync(path.join(reactStartDir, 'node_modules', name)) } for (const [name, target] of Object.entries(links)) { @@ -183,6 +192,58 @@ export async function startViteDevServer( return server } +export interface ViteTestServer { + server: ViteDevServer + /** The warnings Vite logged while the server started. */ + warnings: Array +} + +/** + * Starts the Vite server a test runner creates to run a project's tests: the + * `serve` command and the `test` mode, as Vitest resolves its config, without + * HMR. These tests run in a Vitest worker themselves (`process.env.VITEST`), + * so Start's plugin sees what it sees in a user's Vitest run. Closed when + * the test finishes. + * + * `browser`: as for tests that run in a browser, the server pre-bundles the + * dependencies of the client. + */ +export async function startViteTestServer( + app: StartApp, + options: StartOptions = {}, + browser = false, +): Promise { + const warnings: Array = [] + const customLogger = createLogger('error') + customLogger.warn = (message) => warnings.push(message) + customLogger.warnOnce = customLogger.warn + const server = await createServer({ + root: app.root, + configFile: false, + mode: 'test', + customLogger, + // (Vite starts pre-bundling when the server takes requests, which a + // server in middleware mode does at once) + server: { middlewareMode: browser, hmr: false }, + // (the pre-bundle is written when it is ready, not when a page has loaded) + optimizeDeps: { holdUntilCrawlEnd: false }, + plugins: [await startPlugin('vite', options)], + }) + onTestFinished(async () => { + // Closing the server does not wait for a pre-bundle in progress, which + // would then be written into the removed app directory. + const optimizer = server.environments.client.depsOptimizer + if (browser && optimizer) { + await optimizer.scanProcessing + await Promise.all( + optimizer.metadata.depInfoList.map((dep) => dep.processing), + ) + } + await server.close() + }) + return { server, warnings } +} + /** * Waits until the dev server's file watcher reports changes in `dir` (of the * app). The generator prints the first route tree before the watcher exists diff --git a/packages/start-plugin-core/tests/integration/start-test-run.test.ts b/packages/start-plugin-core/tests/integration/start-test-run.test.ts new file mode 100644 index 0000000000..a38b2b90f8 --- /dev/null +++ b/packages/start-plugin-core/tests/integration/start-test-run.test.ts @@ -0,0 +1,367 @@ +/** + * The Vite server a test runner creates for a project that uses Start + * (`startViteTestServer`): `tanstackStart()` compiles the project's code as in + * the app, but does not serve the app. So a package that only uses Start's + * compile-time APIs needs neither a router entry nor routes, and a test run + * leaves the project's route files alone. + */ +import path from 'node:path' +import { isRunnableDevEnvironment } from 'vite' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { + appFiles, + createStartApp, + startViteTestServer, + until, + watcherReady, +} from './start-app' +import type { ViteDevServer } from 'vite' + +const timeout = 60_000 + +const head = `import { createFileRoute } from '@tanstack/react-router'\n` + +const serverOnly = `export const secret = 'MARK_SECRET'\n` + +/** The code of a module of the app, as the client or the server gets it. */ +async function compiled( + server: ViteDevServer, + environment: 'client' | 'ssr', + file: string, +) { + const result = await server.environments[environment]!.transformRequest( + `/${file}`, + ) + return result!.code +} + +/** Loads a module on the server, as a test runner loads a test file. */ +function importOnServer(server: ViteDevServer, id: string) { + const environment = server.environments.ssr! + if (!isRunnableDevEnvironment(environment)) { + throw new Error('The server environment cannot run modules.') + } + return environment.runner.import(id) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('a package without a router entry and without routes', () => { + const files = { + 'src/server-only.ts': serverOnly, + 'src/runtime.ts': `import { createIsomorphicFn } from '@tanstack/react-start' +import { secret } from './server-only' +export const where = createIsomorphicFn() + .server(() => 'MARK_SERVER ' + secret) + .client(() => 'MARK_CLIENT') +`, + } + + // The config of an app was planned, which needs a router entry: + // "Could not resolve entry for router entry: router in /src". + test( + "the client gets the client's code and the server gets the server's", + async () => { + const app = await createStartApp(files, 'start-library-', [ + 'react', + 'react-dom', + ]) + const { server } = await startViteTestServer(app) + + const client = await compiled(server, 'client', 'src/runtime.ts') + expect(client).toContain('MARK_CLIENT') + expect(client).not.toContain('MARK_SERVER') + expect(client).not.toContain('server-only') + + const ssr = await compiled(server, 'ssr', 'src/runtime.ts') + expect(ssr).toContain('MARK_SERVER') + expect(ssr).toContain('server-only') + expect(ssr).not.toContain('MARK_CLIENT') + }, + timeout, + ) + + // A client test has no server to send a server function call to. The + // client code gets the `createClientRpc` that asks `mockServerFn`'s mocks, + // in place of the one that sends the request. + test( + "the client code of a server function calls the test's mocks, not a server", + async () => { + const app = await createStartApp( + { + 'src/greeting.ts': `import { createServerFn } from '@tanstack/react-start' +export const greet = createServerFn({ method: 'POST' }).handler(() => 'MARK_HANDLER') +`, + }, + 'start-library-', + ['react', 'react-dom'], + ) + const { server } = await startViteTestServer(app) + + const client = await compiled(server, 'client', 'src/greeting.ts') + expect(client).not.toContain('MARK_HANDLER') + expect(client).toMatch(/react-start\/dist\/esm\/testing\/client-rpc\.js/) + }, + timeout, + ) + + // A test runner can keep compiled modules across runs (Vitest does, on + // disk). The call site of a server function then comes from that cache, the + // compiler of the new process never sees it and has no record of the + // function. The resolver asked the compiler for that record and failed + // with "Invalid server function ID". + test( + 'the server finds a server function whose call site this process did not compile', + async () => { + const app = await createStartApp( + { + 'src/greeting.ts': `import { createServerFn } from '@tanstack/react-start' +export const greet = createServerFn({ method: 'POST' }).handler(() => 'MARK_HANDLER') +`, + }, + 'start-library-', + ) + const earlier = await startViteTestServer(app) + const callSite = await compiled(earlier.server, 'ssr', 'src/greeting.ts') + const id = /createSsrRpc\)?\(\s*["']([^"']+)["']/.exec(callSite)?.[1] + expect(id).toBeTypeOf('string') + await earlier.server.close() + + const { server } = await startViteTestServer(app) + const resolver = await importOnServer( + server, + '#tanstack-start-server-fn-resolver', + ) + + const serverFn = await resolver.getServerFnById(id, { origin: 'server' }) + expect(serverFn).toBeTypeOf('function') + expect(serverFn.serverFnMeta).toMatchObject({ name: 'greet' }) + }, + timeout, + ) + + // Start's server code imports the router entry. In a package without one, + // Vite could not load that code at all: 'Missing "#tanstack-router-entry" + // specifier in "@tanstack/start-server-core" package'. + test( + "a server module that uses Start's server helpers loads", + async () => { + const app = await createStartApp( + { + 'src/session.ts': `import { getCookie } from '@tanstack/react-start/server' +export const readSession = () => getCookie('session') +`, + }, + 'start-library-', + ) + const { server } = await startViteTestServer(app) + + const session = await importOnServer(server, '/src/session.ts') + + expect(session.readSession).toBeTypeOf('function') + }, + timeout, + ) + + // The route generator ran for every project: it logged an error for the + // missing routes directory. + test( + 'no route tree is generated and nothing is logged', + async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const app = await createStartApp(files, 'start-library-', [ + 'react', + 'react-dom', + ]) + const { warnings } = await startViteTestServer(app) + + await expect(app.read('src/routeTree.gen.ts')).rejects.toThrow('ENOENT') + expect(error).not.toHaveBeenCalled() + expect(warnings).toEqual([]) + }, + timeout, + ) + + // Start asked Vite to pre-bundle `@tanstack/react-store` by a path through + // `@tanstack/react-router`, which only resolves from a project that + // depends on the router itself. Vite warned ("Failed to resolve + // dependency"), and a browser got the store's CommonJS dependency as it is. + test( + 'that depends on Start only: Vite pre-bundles what the router Start uses loads in a browser', + async () => { + const app = await createStartApp(files, 'start-library-', [ + 'react', + 'react-dom', + ]) + const { server, warnings } = await startViteTestServer(app, {}, true) + + expect(warnings).toEqual([]) + const preBundled = server.environments.client.depsOptimizer!.metadata + expect( + preBundled.depInfoList.filter((dep) => + dep.id.endsWith('> @tanstack/react-store'), + ), + ).toHaveLength(1) + // Router Core's dependencies were found only when a test imported them. + // Vite then pre-bundled them and reloaded the page, and Vitest's browser + // mode could lose a test iframe to that reload. + expect( + preBundled.depInfoList + .map((dep) => dep.id.split(' > ').at(-1)) + .filter((id) => + ['cookie-es', 'seroval', 'seroval-plugins/web'].includes(id!), + ) + .sort(), + ).toEqual(['cookie-es', 'seroval', 'seroval-plugins/web']) + }, + timeout, + ) + + // Only the modules the route generator found lost their server-only route + // options in client code, and no generator runs for this package. + test( + 'a route module loses its server-only options in client code', + async () => { + const app = await createStartApp({ + 'src/server-only.ts': serverOnly, + 'src/widget.tsx': `${head}import { secret } from './server-only' +export const Route = createFileRoute('/widget')({ + server: { handlers: { GET: () => new Response('MARK_HANDLER ' + secret) } }, + headers: () => ({ 'x-mark': 'MARK_HEADERS' }), + ssr: false, + loader: () => 'MARK_LOADER', + component: () => 'MARK_COMPONENT', +}) +`, + }) + const { server } = await startViteTestServer(app) + + const client = await compiled(server, 'client', 'src/widget.tsx') + expect(client).toContain('MARK_LOADER') + expect(client).toContain('MARK_COMPONENT') + expect(client).not.toContain('MARK_HANDLER') + expect(client).not.toContain('MARK_HEADERS') + expect(client).not.toContain('ssr:') + expect(client).not.toContain('server-only') + + const ssr = await compiled(server, 'ssr', 'src/widget.tsx') + expect(ssr).toContain('MARK_HANDLER') + expect(ssr).toContain('MARK_HEADERS') + expect(ssr).toContain('server-only') + }, + timeout, + ) +}) + +describe('an app with routes', () => { + /** What the generator logged as a warning. */ + function generatorWarnings() { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + return () => warn.mock.calls.map((args) => args.join(' ')).join('\n') + } + + test( + 'the route tree is generated when the server starts', + async () => { + const app = await createStartApp( + appFiles({ + 'src/routes/about.tsx': `${head}export const Route = createFileRoute('/about')({ component: () => 'MARK_ABOUT' })\n`, + }), + ) + await startViteTestServer(app) + + expect(await app.read('src/routeTree.gen.ts')).toContain(`'/about'`) + }, + timeout, + ) + + // A dev server and a build update the route path of a route file that was + // moved, and fill an empty route file. A test run does not edit sources. + test( + 'route files are left as they are, with a warning', + async () => { + const stale = `${head}export const Route = createFileRoute('/moved-from')({ component: () => 'MARK_MOVED' })\n` + const app = await createStartApp( + appFiles({ + 'src/routes/moved.tsx': stale, + 'src/routes/empty.tsx': '', + }), + ) + const logged = generatorWarnings() + await startViteTestServer(app) + + expect(await app.read('src/routes/moved.tsx')).toBe(stale) + expect(await app.read('src/routes/empty.tsx')).toBe('') + // (the tree has the route by its location and leaves out the empty file) + const routeTree = await app.read('src/routeTree.gen.ts') + expect(routeTree).toContain(`'/moved'`) + expect(routeTree).not.toContain('moved-from') + expect(routeTree).not.toContain('empty') + expect(logged()).toContain( + `Route file "${path.join(app.root, 'src/routes/moved.tsx')}" is out of date`, + ) + expect(logged()).toContain( + `Route file "${path.join(app.root, 'src/routes/empty.tsx')}" is empty`, + ) + }, + timeout, + ) + + test( + 'a route added while the server runs does not change the route tree', + async () => { + const app = await createStartApp(appFiles()) + const { server } = await startViteTestServer(app) + const routeTree = await app.read('src/routeTree.gen.ts') + await watcherReady(app, server, 'src/routes') + + const added = path.join(app.root, 'src/routes/added.tsx') + let seen = false + server.watcher.on('all', (_event, file) => { + seen ||= path.resolve(file) === added + }) + await app.write({ + 'src/routes/added.tsx': `${head}export const Route = createFileRoute('/added')({ component: () => 'MARK_ADDED' })\n`, + }) + await until(() => Promise.resolve(seen), 'the file watcher of the route') + // (a dev server writes the tree within this time) + await new Promise((resolve) => setTimeout(resolve, 1_000)) + + expect(await app.read('src/routeTree.gen.ts')).toBe(routeTree) + }, + timeout, + ) + + // A route file the generator knows is compiled as in the app: its + // components are split out of client code, and its server-only options go. + test( + 'a route file is code-split and loses its server-only options in client code', + async () => { + const app = await createStartApp( + appFiles({ + 'src/server-only.ts': serverOnly, + 'src/routes/api.tsx': `${head}import { secret } from '../server-only' +export const Route = createFileRoute('/api')({ + server: { handlers: { GET: () => new Response('MARK_HANDLER ' + secret) } }, + component: () => 'MARK_COMPONENT', +}) +`, + }), + ) + const { server } = await startViteTestServer(app) + + const client = await compiled(server, 'client', 'src/routes/api.tsx') + expect(client).toContain('tsr-split=component') + expect(client).not.toContain('MARK_COMPONENT') + expect(client).not.toContain('MARK_HANDLER') + expect(client).not.toContain('server-only') + + const ssr = await compiled(server, 'ssr', 'src/routes/api.tsx') + expect(ssr).toContain('MARK_HANDLER') + expect(ssr).toContain('server-only') + }, + timeout, + ) +}) diff --git a/packages/start-plugin-core/tests/test-mode.test.ts b/packages/start-plugin-core/tests/test-mode.test.ts new file mode 100644 index 0000000000..17e48544f0 --- /dev/null +++ b/packages/start-plugin-core/tests/test-mode.test.ts @@ -0,0 +1,36 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { isVitestRun } from '../src/test-mode' + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('isVitestRun', () => { + test('is true for the config Vitest resolves to run tests', () => { + vi.stubEnv('VITEST', 'true') + + expect(isVitestRun({ command: 'serve', mode: 'test' })).toBe(true) + }) + + // A test file can start a dev server or a build of the app. Both run in a + // process where Vitest has set `VITEST`. + test.each([ + { command: 'serve', mode: 'development' }, + { command: 'build', mode: 'production' }, + { command: 'build', mode: 'test' }, + ])( + 'is false for the $command command in $mode mode inside a Vitest process', + (env) => { + vi.stubEnv('VITEST', 'true') + + expect(isVitestRun(env)).toBe(false) + }, + ) + + // `vite dev --mode test` serves the app. + test('is false for a dev server in test mode outside Vitest', () => { + vi.stubEnv('VITEST', undefined) + + expect(isVitestRun({ command: 'serve', mode: 'test' })).toBe(false) + }) +}) diff --git a/packages/start-plugin-core/tests/vite/test-config-plan.test.ts b/packages/start-plugin-core/tests/vite/test-config-plan.test.ts new file mode 100644 index 0000000000..3b34113b3e --- /dev/null +++ b/packages/start-plugin-core/tests/vite/test-config-plan.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, test } from 'vitest' +import { ENTRY_POINTS } from '../../src/constants' +import { createViteTestConfigPlan } from '../../src/vite/planning' + +const entryPaths = { + client: '/app/src/client.tsx', + server: '/app/src/server.ts', + start: '/app/src/start.ts', +} + +describe('createViteTestConfigPlan', () => { + test('aliases every entry of an app', () => { + const plan = createViteTestConfigPlan({ + framework: 'react', + entryPaths: { ...entryPaths, router: '/app/src/router.tsx' }, + optimizeDepsExclude: [], + noExternal: [], + }) + + expect(plan.resolve.alias).toMatchObject({ + [ENTRY_POINTS.client]: '/app/src/client.tsx', + [ENTRY_POINTS.server]: '/app/src/server.ts', + [ENTRY_POINTS.start]: '/app/src/start.ts', + [ENTRY_POINTS.router]: '/app/src/router.tsx', + }) + }) + + // Start's packages then resolve the placeholder router entry they ship. + test('leaves the router entry of a package without one unaliased', () => { + const plan = createViteTestConfigPlan({ + framework: 'react', + entryPaths: { ...entryPaths, router: undefined }, + optimizeDepsExclude: [], + noExternal: [], + }) + + expect(plan.resolve.alias).toMatchObject({ + [ENTRY_POINTS.client]: '/app/src/client.tsx', + [ENTRY_POINTS.server]: '/app/src/server.ts', + [ENTRY_POINTS.start]: '/app/src/start.ts', + }) + expect(ENTRY_POINTS.router in plan.resolve.alias).toBe(false) + }) + + // No server takes the request of a client test, so the module that sends + // it is replaced by the one that asks the mocks of `mockServerFn`. + test.each(['react', 'solid', 'vue'] as const)( + 'sends the server function calls of %s client code to the mocks', + (framework) => { + const plan = createViteTestConfigPlan({ + framework, + entryPaths: { ...entryPaths, router: undefined }, + optimizeDepsExclude: [], + noExternal: [], + }) + + expect(plan.resolve.alias).toMatchObject({ + [`@tanstack/${framework}-start/client-rpc`]: `@tanstack/${framework}-start/testing/client-rpc`, + }) + }, + ) + + test('keeps the libraries built on Start out of pre-bundling and externalization', () => { + const plan = createViteTestConfigPlan({ + framework: 'solid', + entryPaths: { ...entryPaths, router: undefined }, + optimizeDepsExclude: ['a-start-library'], + noExternal: ['a-start-library'], + }) + + expect(plan.environments.client.optimizeDeps.exclude).toEqual([ + 'a-start-library', + ]) + expect(plan.resolve.noExternal).toContain('a-start-library') + }) + + // Vitest decides by a file's path whether Vite compiles the file or Node + // loads it as it is. Its translation of the wildcards the app's config + // uses (`@tanstack/start**`) does not match a `-`: of Start's own packages + // only `@tanstack/react-start` was compiled in a project that installs them + // from the registry, and a server function call in a jsdom test failed + // with "No Start context found in AsyncLocalStorage". + describe("names Start's own packages so that a test runner finds them", () => { + const plan = createViteTestConfigPlan({ + framework: 'react', + entryPaths: { ...entryPaths, router: undefined }, + optimizeDepsExclude: [], + noExternal: [], + }) + const isNamed = (value: string) => + plan.resolve.noExternal.some( + (pattern) => typeof pattern !== 'string' && pattern.test(value), + ) + + test.each([ + '@tanstack/react-start', + '@tanstack/react-start-client', + '@tanstack/react-start-server', + '@tanstack/start-client-core', + '@tanstack/start-server-core', + '@tanstack/start-storage-context', + '@tanstack/start-fn-stubs', + ])('%s, by the path of a file and by its name', (name) => { + // (as pnpm installs it, as npm installs it, and as Vite asks) + expect( + isNamed( + `/app/node_modules/.pnpm/${name.replace('/', '+')}@1.0.0/node_modules/${name}/dist/esm/index.js`, + ), + ).toBe(true) + expect(isNamed(`/app/node_modules/${name}/dist/esm/index.js`)).toBe(true) + expect(isNamed(name)).toBe(true) + }) + + test.each([ + // another package of the scope + '/app/node_modules/@tanstack/react-router/dist/esm/index.js', + // the Start package of another framework + '/app/node_modules/@tanstack/solid-start/dist/esm/index.js', + // a project whose own directory is named like a Start package + '/home/me/@tanstack/start-app/src/index.ts', + '/home/me/@tanstack/start-app/node_modules/react/index.js', + ])('and not %s', (file) => { + expect(isNamed(file)).toBe(false) + }) + }) + + // A test runner decides what it builds and serves. + test('plans no build and no dependency scan of the app', () => { + const plan = createViteTestConfigPlan({ + framework: 'react', + entryPaths: { ...entryPaths, router: '/app/src/router.tsx' }, + optimizeDepsExclude: [], + noExternal: [], + }) + + expect(Object.keys(plan.environments)).toEqual(['client']) + expect(Object.keys(plan.environments.client)).toEqual(['optimizeDeps']) + expect(plan.environments.client.optimizeDeps).not.toHaveProperty('entries') + }) +}) diff --git a/packages/start-plugin-core/tests/vite/test-run.test.ts b/packages/start-plugin-core/tests/vite/test-run.test.ts new file mode 100644 index 0000000000..e1c9b2f3b6 --- /dev/null +++ b/packages/start-plugin-core/tests/vite/test-run.test.ts @@ -0,0 +1,161 @@ +import { existsSync } from 'node:fs' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { + excludeFromTestRuns, + testRunRouterEntryPlugin, + vitestSetupFilePlugin, +} from '../../src/vite/test-run' +import type { ConfigEnv, Plugin, PluginOption } from 'vite' + +const testRun: ConfigEnv = { command: 'serve', mode: 'test' } +const devServer: ConfigEnv = { command: 'serve', mode: 'development' } +const build: ConfigEnv = { command: 'build', mode: 'production' } + +/** Whether Vite applies the plugin for `env`, as Vite decides it. */ +function applies(plugin: Plugin, env: ConfigEnv) { + if (!plugin.apply) { + return true + } + if (typeof plugin.apply === 'function') { + return plugin.apply({}, env) + } + return plugin.apply === env.command +} + +async function flatten(option: PluginOption): Promise> { + const resolved = await option + if (!resolved) { + return [] + } + if (Array.isArray(resolved)) { + return (await Promise.all(resolved.map(flatten))).flat() + } + return [resolved as Plugin] +} + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('excludeFromTestRuns', () => { + test('leaves a plugin out of a test run and keeps it everywhere else', async () => { + vi.stubEnv('VITEST', 'true') + const [plugin] = await flatten(excludeFromTestRuns({ name: 'serves-app' })) + + expect(applies(plugin!, testRun)).toBe(false) + expect(applies(plugin!, devServer)).toBe(true) + expect(applies(plugin!, build)).toBe(true) + }) + + test('keeps the command a plugin applies to', async () => { + vi.stubEnv('VITEST', 'true') + const [plugin] = await flatten( + excludeFromTestRuns({ name: 'builds-app', apply: 'build' }), + ) + + expect(applies(plugin!, testRun)).toBe(false) + expect(applies(plugin!, devServer)).toBe(false) + expect(applies(plugin!, build)).toBe(true) + }) + + test("keeps a plugin's own decision outside a test run", async () => { + vi.stubEnv('VITEST', 'true') + const [plugin] = await flatten( + excludeFromTestRuns({ + name: 'production-only', + apply: (_config, env) => env.mode === 'production', + }), + ) + + expect(applies(plugin!, testRun)).toBe(false) + expect(applies(plugin!, devServer)).toBe(false) + expect(applies(plugin!, build)).toBe(true) + }) + + test('reaches the plugins inside arrays and promises, and keeps empty entries', async () => { + vi.stubEnv('VITEST', 'true') + const option = excludeFromTestRuns([ + { name: 'first' }, + null, + false, + [{ name: 'nested' }, Promise.resolve({ name: 'later' })], + ]) + + const plugins = await flatten(option) + expect(plugins.map((plugin) => plugin.name)).toEqual([ + 'first', + 'nested', + 'later', + ]) + expect(plugins.map((plugin) => applies(plugin, testRun))).toEqual([ + false, + false, + false, + ]) + }) +}) + +/** Calls a hook of a plugin, whether it is a function or has a handler. */ +function callHook(hook: unknown, ...args: Array): unknown { + const handler = + typeof hook === 'function' + ? hook + : (hook as { handler: (...args: Array) => unknown }).handler + return handler.call({}, ...args) +} + +describe('testRunRouterEntryPlugin', () => { + test('applies to a test run only', () => { + vi.stubEnv('VITEST', 'true') + const plugin = testRunRouterEntryPlugin() + + expect(applies(plugin, testRun)).toBe(true) + expect(applies(plugin, devServer)).toBe(false) + expect(applies(plugin, build)).toBe(false) + }) + + test('answers the import of the router entry with an entry that has no router', () => { + const plugin = testRunRouterEntryPlugin() + + const resolved = callHook(plugin.resolveId, '#tanstack-router-entry') + expect(resolved).toBeTypeOf('string') + expect(callHook(plugin.resolveId, '#tanstack-start-entry')).toBeUndefined() + + expect(callHook(plugin.load, resolved)).toBe( + 'export function getRouter() {}\n', + ) + }) +}) + +describe('vitestSetupFilePlugin', () => { + type ConfigureVitest = (context: { + project: { config: { setupFiles: Array } } + }) => void + + function configureVitest(isTestRun: boolean, setupFiles: Array) { + const plugin = vitestSetupFilePlugin(() => isTestRun) as Plugin & { + configureVitest: ConfigureVitest + } + plugin.configureVitest({ project: { config: { setupFiles } } }) + } + + test('adds the setup file of Start after the ones of the project, once', () => { + const setupFiles = ['/project/tests/setup.ts'] + + configureVitest(true, setupFiles) + configureVitest(true, setupFiles) + + expect(setupFiles).toHaveLength(2) + expect(setupFiles[0]).toBe('/project/tests/setup.ts') + expect(setupFiles[1]).toMatch(/start-client-core\/.*testing\/vitest\.js$/) + expect(existsSync(setupFiles[1]!)).toBe(true) + }) + + test('leaves a project alone outside of a test run', () => { + const setupFiles: Array = [] + + configureVitest(false, setupFiles) + + expect(setupFiles).toEqual([]) + }) +}) diff --git a/packages/start-server-core/package.json b/packages/start-server-core/package.json index 020747da69..949f89b507 100644 --- a/packages/start-server-core/package.json +++ b/packages/start-server-core/package.json @@ -88,6 +88,12 @@ "default": "./dist/esm/virtual-modules.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing/index.d.ts", + "default": "./dist/esm/testing/index.js" + } + }, "./package.json": "./package.json" }, "imports": { diff --git a/packages/start-server-core/src/testing/index.ts b/packages/start-server-core/src/testing/index.ts new file mode 100644 index 0000000000..24cfc195be --- /dev/null +++ b/packages/start-server-core/src/testing/index.ts @@ -0,0 +1,32 @@ +export { runInRequest } from './runInRequest' +export type { + GlobalMiddlewareContext, + RequestDescription, + RunInRequestOptions, +} from './runInRequest' +export { mockMiddleware } from './middlewareMocks' +export type { + FunctionMiddlewareMockOptions, + MiddlewareMock, + MiddlewareMockNext, + MiddlewareMockNextOptions, + MiddlewareMockResult, + RequestMiddlewareMockOptions, +} from './middlewareMocks' +export { runMiddleware } from './runMiddleware' +export type { + FunctionMiddlewareInput, + FunctionMiddlewarePassed, + FunctionMiddlewareRun, + RequestMiddlewareInput, + RequestMiddlewarePassed, + RequestMiddlewareRun, +} from './runMiddleware' +export type { + AnyMiddleware, + ContextOption, + MiddlewareAddedContext, + MiddlewareInputContext, + MiddlewareOutputContext, + MiddlewareSendContext, +} from './types' diff --git a/packages/start-server-core/src/testing/middlewareMocks.ts b/packages/start-server-core/src/testing/middlewareMocks.ts new file mode 100644 index 0000000000..3f57f9d493 --- /dev/null +++ b/packages/start-server-core/src/testing/middlewareMocks.ts @@ -0,0 +1,198 @@ +import { registerMockStore } from '@tanstack/start-client-core/testing' +import { getScope } from './scope' +import { getMiddlewareType } from './types' +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + Method, + ServerFnMeta, +} from '@tanstack/start-client-core' +import type { ActiveMiddlewareMock, MiddlewareMocks } from './scope' +import type { + AnyMiddleware, + ContextOption, + MiddlewareAddedContext, + MiddlewareInputContext, + MiddlewareSendContext, +} from './types' + +/** + * Mocks for middleware in server tests. + * + * `mockMiddleware` swaps the server and the client function of a middleware + * object for dispatchers, once. A dispatcher calls the mock that is active + * for the middleware, or the original function when there is none. Nothing + * of this is in the code an app ships. + */ + +declare const middlewareMockResult: unique symbol + +/** + * What `next()` resolves to in a mock. A mock returns it to let the call go + * on, as a middleware returns the result of its `next()`. + */ +export interface MiddlewareMockResult { + readonly [middlewareMockResult]: true +} + +/** What a mock passes to `next()`: what the mocked middleware passes. */ +export type MiddlewareMockNextOptions = + ContextOption> & + (TMiddleware extends AnyFunctionMiddleware + ? { sendContext?: MiddlewareSendContext } + : {}) + +/** + * `next()` of a mock. Its `context` is required when the mocked middleware + * adds context, because the code after it relies on that context. + */ +export type MiddlewareMockNext = + undefined extends MiddlewareAddedContext + ? ( + options?: MiddlewareMockNextOptions, + ) => Promise + : ( + options: MiddlewareMockNextOptions, + ) => Promise + +/** What the mock of a function middleware gets: what the middleware gets. */ +export interface FunctionMiddlewareMockOptions< + TMiddleware extends AnyFunctionMiddleware, +> { + data: TMiddleware['~types']['allOutput'] + context: MiddlewareInputContext + next: MiddlewareMockNext + method: Method + serverFnMeta: ServerFnMeta + signal: AbortSignal +} + +/** What the mock of a request middleware gets: what the middleware gets. */ +export interface RequestMiddlewareMockOptions< + TMiddleware extends AnyRequestMiddleware, +> { + request: Request + pathname: string + context: MiddlewareInputContext + next: MiddlewareMockNext + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta +} + +/** + * Stands for the server function of a middleware. It gets what the + * middleware gets. It goes on by returning `next()`, with the context the + * middleware adds, or it ends the call the way the middleware can: by + * throwing, or (a request middleware) by returning a `Response`. + */ +export type MiddlewareMock = + TMiddleware extends AnyFunctionMiddleware + ? ( + options: FunctionMiddlewareMockOptions, + ) => MiddlewareMockResult | Promise + : TMiddleware extends AnyRequestMiddleware + ? ( + options: RequestMiddlewareMockOptions, + ) => + | MiddlewareMockResult + | Response + | Promise + : never + +type AnyFn = (...args: Array) => any + +/** The mocks of the test file: registered outside a request scope. */ +const fileMocks: MiddlewareMocks = new Map() +/** The functions a middleware had before its dispatchers went in. */ +const originals = new WeakMap< + AnyMiddleware, + { server?: AnyFn; client?: AnyFn } +>() + +registerMockStore(fileMocks) + +function activeMock( + middleware: AnyMiddleware, +): ActiveMiddlewareMock | undefined { + return getScope()?.mocks.get(middleware) ?? fileMocks.get(middleware) +} + +function installDispatchers(middleware: AnyMiddleware) { + if (originals.has(middleware)) { + return + } + const options = middleware.options as { server?: AnyFn; client?: AnyFn } + const original = { server: options.server, client: options.client } + originals.set(middleware, original) + + options.server = (serverOptions) => { + const active = activeMock(middleware) + if (active) { + active.ran = true + return active.mock(serverOptions) + } + return original.server + ? original.server(serverOptions) + : serverOptions.next() + } + // A mocked middleware is out of the way as a whole. On the server a call + // runs the client function first, and that function can need a browser. + const client = original.client + if (client) { + options.client = (clientOptions) => + activeMock(middleware) ? clientOptions.next() : client(clientOptions) + } +} + +/** + * Replaces a middleware in server tests. The mock is typed from the + * middleware: it gets what the middleware's server function gets, and it + * passes on the context that function passes on. While a middleware is + * mocked, its client function does not run either. + * + * A mock registered inside `runInRequest` belongs to that request: it wins + * over a mock of the test, ends with the request, and the request fails when + * the mock never ran. A mock registered in a test or in `beforeEach` ends + * with the test. One registered at the top of the file or in `beforeAll` + * stays for the file. + */ +export function mockMiddleware( + middleware: TMiddleware, + mock: MiddlewareMock, +): void { + if (!getMiddlewareType(middleware)) { + throw new Error( + 'mockMiddleware() needs a middleware created with createMiddleware().', + ) + } + installDispatchers(middleware) + ;(getScope()?.mocks ?? fileMocks).set(middleware, { + mock: mock as AnyFn, + ran: false, + neverRan: new Error( + 'A middleware was mocked inside runInRequest() and did not run in that request. Either nothing in the request used it after the mock was registered ' + + '(the request middleware of src/start.ts has run before the callback starts: mock it before runInRequest()), ' + + 'or the server ran another copy of it: the server loads the file of a server function a second time, ' + + 'so a middleware that is created in that file exists twice. Create the middleware in a file of its own to mock it.', + ), + }) +} + +/** The server function a middleware was created with, mocked or not. */ +export function getOriginalServerFn( + middleware: AnyMiddleware, +): AnyFn | undefined { + const original = originals.get(middleware) + return original + ? original.server + : (middleware.options as { server?: AnyFn }).server +} + +/** Throws for a mock of a request scope that never ran. */ +export function assertMocksRan(mocks: MiddlewareMocks): void { + for (const active of mocks.values()) { + if (!active.ran) { + throw active.neverRan + } + } +} diff --git a/packages/start-server-core/src/testing/runInRequest.ts b/packages/start-server-core/src/testing/runInRequest.ts new file mode 100644 index 0000000000..a2965b5e00 --- /dev/null +++ b/packages/start-server-core/src/testing/runInRequest.ts @@ -0,0 +1,286 @@ +import { createServerHistory } from '@tanstack/history' +import { getNormalizedURL } from '@tanstack/router-core/ssr/server' +import { + createNullProtoObject, + flattenMiddlewares, + safeObjectMerge, +} from '@tanstack/start-client-core' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { + reconcileResponse, + withStartRequest, +} from '../internal-request-response' +import { assertMocksRan } from './middlewareMocks' +import { runWithScope } from './scope' +import type { AnyRouter, Expand, Register } from '@tanstack/router-core' +import type { + AnyRequestMiddleware, + AnyStartInstanceOptions, + AssignAllServerFnContext, + RouterEntry, + StartEntry, +} from '@tanstack/start-client-core' +import type { StartEvent } from '../internal-request-response' +import type { RequestOptions } from '../request-handler' +import type { TestRequestScope } from './scope' +import type { ContextOption } from './types' + +/** The request of a scope: a `Request`, or the parts to build one from. */ +export type RequestDescription = + | { request: Request; url?: never; method?: never; headers?: never } + | { + request?: never + /** Relative URLs are resolved against `http://localhost`. */ + url?: string | URL + method?: string + headers?: HeadersInit + } + +/** + * The context the global middleware of `src/start.ts` leaves for a server + * function: what the server entry passes in, and what the request middleware + * and the function middleware of the start instance add. + */ +export type GlobalMiddlewareContext = Expand< + AssignAllServerFnContext +> + +export type RunInRequestOptions = RequestDescription & + ( + | ({ + globalMiddleware?: undefined + // The request context the server entry passes to Start, see + // `Register['server']['requestContext']`. + } & Pick, 'context'>) + | ({ + /** + * Leaves out the middleware of `src/start.ts`, the request list and + * the function list. `context` then stands for what they pass on. + */ + globalMiddleware: 'skip' + } & ContextOption) + ) + +const NO_ROUTER = + 'This project has no router entry (src/router.tsx), so there is no router to return in a test.' + +async function loadRouter( + url: URL, + startOptions: AnyStartInstanceOptions, +): Promise { + // @ts-ignore The virtual entry is resolved by the bundler, as in createStartHandler. + const routerEntry: RouterEntry = await import('#tanstack-router-entry') + // (the placeholder entry of a project without a router returns nothing) + const router = (await routerEntry.getRouter()) as AnyRouter | undefined + if (!router) { + throw new Error(NO_ROUTER) + } + // As createStartHandler prepares the router of a request. + router.update({ + history: createServerHistory(url.pathname + url.search + url.hash), + origin: router.options.origin ?? url.origin, + basepath: process.env.TSS_ROUTER_BASEPATH || '/', + ...{ defaultSsr: startOptions.defaultSsr }, + }) + return router +} + +async function runScope( + event: StartEvent, + options: RunInRequestOptions, + callback: () => TResult | Promise, +): Promise { + const request = event.request + const url = getNormalizedURL(event.requestUrl).url + + // @ts-ignore The virtual entry is resolved by the bundler, as in createStartHandler. + const startEntry: StartEntry = await import('#tanstack-start-entry') + const appStartOptions: AnyStartInstanceOptions = + (await startEntry.startInstance?.getOptions()) ?? + ({} as AnyStartInstanceOptions) + const startOptions: AnyStartInstanceOptions = + options.globalMiddleware === 'skip' + ? { + ...appStartOptions, + requestMiddleware: undefined, + functionMiddleware: undefined, + } + : appStartOptions + + // The same set a request of the app keeps: a server function does not run + // a request middleware again that already ran for the request. + const executedRequestMiddlewares = new Set() + const requestMiddleware = flattenMiddlewares( + [...(startOptions.requestMiddleware ?? [])], + undefined, + executedRequestMiddlewares, + ) + + let routerPromise: Promise | undefined + const scope: TestRequestScope = { + request, + pathname: url.pathname, + mocks: new Map(), + } + const pipeline: { + request: Request + pathname: string + handlerType: 'router' + context: Record + response?: Response + } = { + request, + pathname: url.pathname, + handlerType: 'router', + context: createNullProtoObject( + options.context as Record | undefined, + ), + } + // Set once the last request middleware lets the request through. + let callbackRun: Promise | undefined + + const runCallback = async () => { + if (callbackRun) { + throw new Error( + 'runInRequest(): a request middleware called next() more than once.', + ) + } + callbackRun = (async () => + runWithStartContext( + { + getRouter: () => (routerPromise ??= loadRouter(url, startOptions)), + request, + startOptions, + contextAfterGlobalMiddlewares: pipeline.context, + executedRequestMiddlewares, + handlerType: 'router', + }, + callback, + ))() + await callbackRun + if (requestMiddleware.length) { + // What a request middleware gets from next(): a response that has the + // status and the headers the code in the callback set. + pipeline.response = reconcileResponse(new Response(null), event) + } + return pipeline + } + + const dispatch = async (index: number): Promise => { + const middleware = requestMiddleware[index] + if (!middleware) { + return runCallback() + } + const server = middleware.options.server as + | ((options: unknown) => unknown) + | undefined + if (!server) { + return dispatch(index + 1) + } + const result = await server({ + ...pipeline, + next: (nextOptions?: { context?: Record }) => { + if (nextOptions?.context) { + pipeline.context = safeObjectMerge( + pipeline.context, + nextOptions.context, + ) + } + return dispatch(index + 1) + }, + }) + if (result instanceof Response) { + pipeline.response = result + } + return pipeline + } + + return runWithScope(scope, async () => { + let middlewareError: { error: unknown } | undefined + try { + await dispatch(0) + } catch (error) { + middlewareError = { error } + } + if (!callbackRun) { + if (middlewareError) { + throw middlewareError.error + } + throw new Error( + `runInRequest(): a request middleware of src/start.ts ended the request${ + pipeline.response ? ` with status ${pipeline.response.status}` : '' + } before the callback ran. ` + + `Send a request the middleware lets through, replace the middleware with mockMiddleware(), or pass globalMiddleware: 'skip'. ` + + `To test the middleware itself, call it with runMiddleware().`, + { cause: pipeline.response }, + ) + } + // The callback is what the test is about: its error wins over what a + // middleware made of it, and the scope ends only when the callback has, + // also when a middleware did not wait for next(). + const value = await callbackRun + if (middlewareError) { + throw middlewareError.error + } + assertMocksRan(scope.mocks) + return value + }) +} + +function toRequest(options: RunInRequestOptions): Request { + if (options.request) { + return options.request + } + return new Request(new URL(options.url ?? '/', 'http://localhost'), { + method: options.method, + headers: options.headers, + }) +} + +/** + * Runs `callback` as code that handles one request to the app's server. + * + * The global request middleware of `src/start.ts` runs first. Inside the + * callback a server function can be called as a loader calls it while the + * server renders a page: its client middleware runs, then its server + * middleware, its validator and its handler. Start's request and response + * helpers (`getRequest`, `getCookie`, `setResponseHeader`, + * `getResponseHeader`, ...) work inside the callback as well. + * + * Resolves to what the callback returns, and rejects with what it throws. + */ +export function runInRequest( + callback: {} extends RunInRequestOptions + ? () => TResult | Promise + : never, +): Promise +export function runInRequest( + options: RunInRequestOptions, + callback: () => TResult | Promise, +): Promise +export async function runInRequest( + ...args: + | [callback: () => TResult | Promise] + | [options: RunInRequestOptions, callback: () => TResult | Promise] +): Promise { + const [options, callback] = args.length === 1 ? [{}, args[0]] : args + if (typeof callback !== 'function') { + throw new Error( + 'runInRequest() needs a callback: runInRequest(options, async () => { ... }).', + ) + } + const request = toRequest(options) + let result: Promise | undefined + const handleRequest = withStartRequest(async (_request, _options, event) => { + result = runScope(event, options, callback) + await result + return new Response(null) + }) + const response = await handleRequest(request, undefined) + if (!result) { + throw new Error( + `runInRequest(): Start does not accept the URL of the request, ${request.url} (status ${response.status}).`, + ) + } + return result +} diff --git a/packages/start-server-core/src/testing/runMiddleware.ts b/packages/start-server-core/src/testing/runMiddleware.ts new file mode 100644 index 0000000000..9fd4c8486e --- /dev/null +++ b/packages/start-server-core/src/testing/runMiddleware.ts @@ -0,0 +1,275 @@ +import { + createNullProtoObject, + safeObjectMerge, +} from '@tanstack/start-client-core' +import { getStartEvent, reconcileResponse } from '../internal-request-response' +import { getOriginalServerFn } from './middlewareMocks' +import { getScope } from './scope' +import { getMiddlewareType } from './types' +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + Method, + ServerFnMeta, +} from '@tanstack/start-client-core' +import type { TestRequestScope } from './scope' +import type { + AnyMiddleware, + ContextOption, + MiddlewareInputContext, + MiddlewareOutputContext, + MiddlewareSendContext, +} from './types' + +type DataOption = undefined extends TData + ? { data?: TData } + : { data: TData } + +/** What a function middleware's server function is called with. */ +export type FunctionMiddlewareInput = + DataOption & + ContextOption> & { + /** Defaults to `GET`. */ + method?: Method + /** Defaults to the signal of the request. */ + signal?: AbortSignal + serverFnMeta?: ServerFnMeta + } + +/** What a function middleware passed to `next()`. */ +export interface FunctionMiddlewarePassed< + TMiddleware extends AnyFunctionMiddleware, +> { + /** The context the middleware received, with what it added. */ + context: MiddlewareOutputContext + /** What the middleware sends back to the client. */ + sendContext: MiddlewareSendContext +} + +/** How a function middleware's server function ended. */ +export interface FunctionMiddlewareRun< + TMiddleware extends AnyFunctionMiddleware, + TResult, +> extends FunctionMiddlewarePassed { + /** What the `next` callback of the test returned. */ + result: TResult +} + +/** What a request middleware's server function is called with. */ +export type RequestMiddlewareInput = + ContextOption> & { + /** Defaults to `router`, a request for a page. */ + handlerType?: 'router' | 'serverFn' + serverFnMeta?: ServerFnMeta + } + +/** What a request middleware passed to `next()`. */ +export interface RequestMiddlewarePassed< + TMiddleware extends AnyRequestMiddleware, +> { + /** The context the middleware received, with what it added. */ + context: MiddlewareOutputContext + request: Request + pathname: string +} + +/** How a request middleware's server function ended. */ +export interface RequestMiddlewareRun< + TMiddleware extends AnyRequestMiddleware, +> { + /** + * The context the middleware passed on. It is the context the middleware + * received when the middleware did not call `next()`. + */ + context: MiddlewareOutputContext + /** + * The response the middleware answers the request with: its own, or the + * one that came back from `next()`. + */ + response: Response +} + +type AnyFn = (...args: Array) => any + +const defaultServerFnMeta: ServerFnMeta = { + id: 'runMiddleware', + name: 'runMiddleware', + filename: 'runMiddleware', +} + +async function runFunctionMiddleware( + scope: TestRequestScope, + server: AnyFn, + input: { + data?: unknown + context?: Record + method?: Method + signal?: AbortSignal + serverFnMeta?: ServerFnMeta + }, + next: AnyFn | undefined, +) { + const options = { + data: input.data, + context: createNullProtoObject(input.context), + method: input.method ?? 'GET', + serverFnMeta: input.serverFnMeta ?? defaultServerFnMeta, + signal: input.signal ?? scope.request.signal, + request: scope.request, + } + const returned = await server({ + ...options, + next: async ( + nextOptions: { + context?: Record + sendContext?: unknown + } = {}, + ) => { + const context = safeObjectMerge(options.context, nextOptions.context) + const sendContext = nextOptions.sendContext + const result = await next?.({ context, sendContext }) + return { ...options, ...nextOptions, context, sendContext, result } + }, + }) + + if (returned instanceof Response) { + return { + context: options.context, + sendContext: undefined, + result: returned, + } + } + if (!returned) { + throw new Error( + 'runMiddleware(): the middleware returned nothing. A middleware returns the result of next().', + ) + } + return { + context: returned.context, + sendContext: returned.sendContext, + result: returned.result, + } +} + +async function runRequestMiddleware( + scope: TestRequestScope, + server: AnyFn, + input: { + context?: Record + handlerType?: 'router' | 'serverFn' + serverFnMeta?: ServerFnMeta + }, + next: AnyFn | undefined, +) { + const event = getStartEvent() + const { request, pathname } = scope + let context = createNullProtoObject(input.context) + + let returned: unknown + try { + returned = await server({ + request, + pathname, + context, + handlerType: input.handlerType ?? 'router', + serverFnMeta: input.serverFnMeta, + next: async (nextOptions?: { context?: Record }) => { + context = safeObjectMerge(context, nextOptions?.context) + const nextResponse: unknown = await next?.({ + context, + request, + pathname, + }) + return { + request, + pathname, + context, + // As in the app, the middleware gets a response that has the status + // and the headers set through Start's response helpers. + response: reconcileResponse( + nextResponse instanceof Response + ? nextResponse + : new Response(null), + event, + ), + } + }, + }) + } catch (error) { + // A thrown Response answers the request, as in the app. + if (!(error instanceof Response)) { + throw error + } + returned = error + } + + const response = + returned instanceof Response + ? returned + : (returned as { response?: unknown } | undefined)?.response + if (!(response instanceof Response)) { + throw new Error( + 'runMiddleware(): the middleware returned no response. A request middleware returns the result of next() or a Response.', + ) + } + return { context, response: reconcileResponse(response, event) } +} + +/** + * Calls the server function of one middleware, and nothing else: not the + * middleware it lists itself, not its validator, not its client function. + * Use it inside `runInRequest`, which provides the request. + * + * `input` is what the middleware receives: for a function middleware the + * validated `data` and the `context` of the middleware before it, for a + * request middleware the `context`. + * + * `next` stands for everything after the middleware. It gets what the + * middleware passed on. What it returns is the result of the call for a + * function middleware, and the response of the request for a request + * middleware. + */ +export function runMiddleware< + TMiddleware extends AnyFunctionMiddleware, + TResult = undefined, +>( + middleware: TMiddleware, + input: FunctionMiddlewareInput, + next?: ( + passed: FunctionMiddlewarePassed, + ) => TResult | Promise, +): Promise> +export function runMiddleware( + middleware: TMiddleware, + input: RequestMiddlewareInput, + next?: ( + passed: RequestMiddlewarePassed, + ) => Response | void | Promise, +): Promise> +export async function runMiddleware( + middleware: AnyMiddleware, + input: Record, + next?: AnyFn, +): Promise { + const type = getMiddlewareType(middleware) + if (!type) { + throw new Error( + 'runMiddleware() needs a middleware created with createMiddleware().', + ) + } + const scope = getScope() + if (!scope) { + throw new Error( + 'runMiddleware() has to be called inside runInRequest(), which provides the request the middleware runs for.', + ) + } + const server = getOriginalServerFn(middleware) + if (!server) { + throw new Error( + 'runMiddleware(): the middleware has no server function. Only a function passed to .server() can be run.', + ) + } + return type === 'function' + ? runFunctionMiddleware(scope, server, input, next) + : runRequestMiddleware(scope, server, input, next) +} diff --git a/packages/start-server-core/src/testing/scope.ts b/packages/start-server-core/src/testing/scope.ts new file mode 100644 index 0000000000..69e4fcf34e --- /dev/null +++ b/packages/start-server-core/src/testing/scope.ts @@ -0,0 +1,32 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import type { AnyMiddleware } from './types' + +type AnyFn = (...args: Array) => any + +/** A mock that `mockMiddleware` registered. */ +export interface ActiveMiddlewareMock { + mock: AnyFn + ran: boolean + /** Created where the mock was registered, so its stack points there. */ + neverRan: Error +} + +export type MiddlewareMocks = Map + +/** What the helpers of a test share while `runInRequest` runs. */ +export interface TestRequestScope { + request: Request + pathname: string + /** The mocks registered inside this scope. They end with it. */ + mocks: MiddlewareMocks +} + +const scopes = new AsyncLocalStorage() + +export function runWithScope(scope: TestRequestScope, fn: () => T): T { + return scopes.run(scope, fn) +} + +export function getScope(): TestRequestScope | undefined { + return scopes.getStore() +} diff --git a/packages/start-server-core/src/testing/types.ts b/packages/start-server-core/src/testing/types.ts new file mode 100644 index 0000000000..4440344c1e --- /dev/null +++ b/packages/start-server-core/src/testing/types.ts @@ -0,0 +1,68 @@ +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + AssignAllServerFnContext, + AssignAllServerRequestContext, + FunctionMiddlewareWithTypes, + RequestMiddlewareWithTypes, +} from '@tanstack/start-client-core' +import type { Expand } from '@tanstack/router-core' + +export type AnyMiddleware = AnyFunctionMiddleware | AnyRequestMiddleware + +/** + * The context a middleware's server function receives: what the server entry, + * the global middleware and the middleware before it passed on. + */ +export type MiddlewareInputContext = + TMiddleware extends FunctionMiddlewareWithTypes< + infer TRegister, + infer TMiddlewares, + any, + any, + infer TServerSendContext, + any, + any + > + ? Expand< + AssignAllServerFnContext + > + : TMiddleware extends RequestMiddlewareWithTypes< + infer TRegister, + infer TMiddlewares, + any + > + ? Expand> + : never + +/** The context a middleware's server function passes to `next()`. */ +export type MiddlewareAddedContext = + TMiddleware['~types']['serverContext'] + +/** The context after a middleware: what it received and what it added. */ +export type MiddlewareOutputContext = Expand< + TMiddleware['~types']['allServerContext'] +> + +/** What a function middleware's server function sends back to the client. */ +export type MiddlewareSendContext = + TMiddleware['~types']['clientSendContext'] + +/** `{ context }`, required when the context has a required property. */ +export type ContextOption = undefined extends TContext + ? { context?: TContext } + : {} extends TContext + ? { context?: TContext } + : { context: TContext } + +/** + * The kind of a middleware, read from the object at runtime. The types of a + * middleware do not declare `options.type`. + */ +export function getMiddlewareType( + middleware: unknown, +): 'function' | 'request' | undefined { + const type = (middleware as { options?: { type?: unknown } } | undefined) + ?.options?.type + return type === 'function' || type === 'request' ? type : undefined +} diff --git a/packages/start-server-core/tests/testing.test-d.ts b/packages/start-server-core/tests/testing.test-d.ts new file mode 100644 index 0000000000..33ebe3e105 --- /dev/null +++ b/packages/start-server-core/tests/testing.test-d.ts @@ -0,0 +1,190 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '@tanstack/start-client-core' +import { mockMiddleware, runInRequest, runMiddleware } from '../src/testing' +import type { + FunctionMiddlewareRun, + MiddlewareMockResult, + RequestMiddlewareRun, +} from '../src/testing' + +// The functions below are only type-checked. This file also runs as a test +// file, and nothing in it may call the harness. + +const auth = createMiddleware({ type: 'function' }) + .validator((input: { token: string }) => input) + .server(({ next }) => next({ context: { user: { name: 'Ada' } } })) + +const greeting = createMiddleware({ type: 'function' }) + .middleware([auth]) + .server(({ next, context }) => + next({ context: { greeting: `Hello ${context.user.name}` } }), + ) + +const logging = createMiddleware({ type: 'function' }).server(({ next }) => + next(), +) + +const tenant = createMiddleware().server(({ next }) => + next({ context: { tenant: 'acme' } }), +) + +function checkRunInRequest() { + expectTypeOf(runInRequest(() => 5)).toEqualTypeOf>() + expectTypeOf(runInRequest(async () => 'a')).toEqualTypeOf>() + expectTypeOf( + runInRequest({ url: '/posts', headers: { cookie: 'a=b' } }, async () => ({ + ok: true, + })), + ).toEqualTypeOf>() + + void runInRequest({ request: new Request('http://localhost/') }, () => {}) + void runInRequest({ globalMiddleware: 'skip' }, () => {}) + + void runInRequest( + // @ts-expect-error a Request already has a URL + { request: new Request('http://localhost/'), url: '/posts' }, + () => {}, + ) + // @ts-expect-error the only value is 'skip' + void runInRequest({ globalMiddleware: 'run' }, () => {}) + // @ts-expect-error the callback is missing + void runInRequest({ url: '/posts' }) +} + +function checkMockOfFunctionMiddleware() { + mockMiddleware(auth, ({ data, context, method, signal, next }) => { + expectTypeOf(data).toEqualTypeOf<{ token: string }>() + expectTypeOf(context).toEqualTypeOf() + expectTypeOf(method).toEqualTypeOf<'GET' | 'POST'>() + expectTypeOf(signal).toEqualTypeOf() + expectTypeOf(next).returns.toEqualTypeOf>() + return next({ context: { user: { name: 'Grace' } } }) + }) + mockMiddleware(auth, async ({ next }) => + next({ context: { user: { name: 'Grace' } } }), + ) + mockMiddleware(auth, () => { + throw new Error('not signed in') + }) + + // @ts-expect-error the middleware passes a user on, so the mock has to + mockMiddleware(auth, ({ next }) => next()) + mockMiddleware(auth, ({ next }) => + // @ts-expect-error the name of the user is a string + next({ context: { user: { name: 5 } } }), + ) + // @ts-expect-error a mock returns the result of next() + mockMiddleware(auth, () => undefined) + // @ts-expect-error a function middleware cannot answer with a response + mockMiddleware(auth, () => new Response(null)) +} + +function checkMockSeesTheContextBeforeTheMiddleware() { + mockMiddleware(greeting, ({ context, next }) => { + expectTypeOf(context).toEqualTypeOf<{ user: { name: string } }>() + return next({ context: { greeting: 'Hi' } }) + }) + mockMiddleware(logging, ({ next }) => next()) +} + +function checkMockOfRequestMiddleware() { + mockMiddleware(tenant, ({ request, pathname, handlerType, next }) => { + expectTypeOf(request).toEqualTypeOf() + expectTypeOf(pathname).toEqualTypeOf() + expectTypeOf(handlerType).toEqualTypeOf<'serverFn' | 'router'>() + return next({ context: { tenant: 'other' } }) + }) + mockMiddleware(tenant, () => new Response(null, { status: 401 })) + + // @ts-expect-error the middleware passes a tenant on, so the mock has to + mockMiddleware(tenant, ({ next }) => next()) +} + +function checkOnlyMiddlewareCanBeMocked() { + const plain = () => {} + + // @ts-expect-error a plain function is no middleware + mockMiddleware(plain, () => new Response(null)) +} + +async function checkRunOfFunctionMiddleware() { + const run = await runMiddleware( + auth, + { data: { token: 'abc' } }, + ({ context }) => { + expectTypeOf(context).toEqualTypeOf<{ user: { name: string } }>() + return 5 + }, + ) + expectTypeOf(run).toExtend>() + expectTypeOf(run.result).toEqualTypeOf() + expectTypeOf(run.context).toEqualTypeOf<{ user: { name: string } }>() + + const asyncNext = await runMiddleware( + auth, + { data: { token: 'abc' } }, + async () => 'later', + ) + expectTypeOf(asyncNext.result).toEqualTypeOf() + + const withoutNext = await runMiddleware(logging, {}) + expectTypeOf(withoutNext.result).toEqualTypeOf() + + // @ts-expect-error the middleware validates data, so it gets data + void runMiddleware(auth, {}) + // @ts-expect-error the token is a string + void runMiddleware(auth, { data: { token: 5 } }) +} + +async function checkRunNeedsTheContextOfTheMiddlewareBefore() { + const run = await runMiddleware(greeting, { + data: { token: 'abc' }, + context: { user: { name: 'Ada' } }, + }) + expectTypeOf(run.context).toEqualTypeOf<{ + user: { name: string } + greeting: string + }>() + + // @ts-expect-error `auth` runs before it and passes a user on + void runMiddleware(greeting, { data: { token: 'abc' } }) +} + +async function checkRunOfRequestMiddleware() { + const run = await runMiddleware( + tenant, + { handlerType: 'serverFn' }, + ({ context, request, pathname }) => { + expectTypeOf(context).toEqualTypeOf<{ tenant: string }>() + expectTypeOf(request).toEqualTypeOf() + expectTypeOf(pathname).toEqualTypeOf() + return new Response('page') + }, + ) + expectTypeOf(run).toEqualTypeOf>() + expectTypeOf(run.response).toEqualTypeOf() + expectTypeOf(run.context).toEqualTypeOf<{ tenant: string }>() + + void runMiddleware(tenant, {}, () => {}) + // @ts-expect-error the rest of a request answers with a response + void runMiddleware(tenant, {}, () => 'page') + // @ts-expect-error a request middleware gets no data + void runMiddleware(tenant, { data: 'x' }) +} + +test('runInRequest resolves to what the callback returns', () => { + expectTypeOf(checkRunInRequest).toBeFunction() +}) + +test('a mock is typed from the middleware it replaces', () => { + expectTypeOf(checkMockOfFunctionMiddleware).toBeFunction() + expectTypeOf(checkMockSeesTheContextBeforeTheMiddleware).toBeFunction() + expectTypeOf(checkMockOfRequestMiddleware).toBeFunction() + expectTypeOf(checkOnlyMiddlewareCanBeMocked).toBeFunction() +}) + +test('runMiddleware types the input and the outcome from the middleware', () => { + expectTypeOf(checkRunOfFunctionMiddleware).toBeFunction() + expectTypeOf(checkRunNeedsTheContextOfTheMiddlewareBefore).toBeFunction() + expectTypeOf(checkRunOfRequestMiddleware).toBeFunction() +}) diff --git a/packages/start-server-core/tests/testing.test.ts b/packages/start-server-core/tests/testing.test.ts new file mode 100644 index 0000000000..c11848925f --- /dev/null +++ b/packages/start-server-core/tests/testing.test.ts @@ -0,0 +1,769 @@ +// @vitest-environment node + +// The setup file Start's plugin adds to a test run: mocks end with the test. +import '@tanstack/start-client-core/testing/vitest' +import { describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '@tanstack/router-core' +import { + createMiddleware, + createServerFn, + getRouterInstance, +} from '@tanstack/start-client-core' +import { createServerRpc } from '../src/createServerRpc' +import { + getCookie, + getRequest, + getResponseHeader, + getResponseStatus, + setResponseHeader, + setResponseStatus, +} from '../src/request-response' +import { mockMiddleware, runInRequest, runMiddleware } from '../src/testing' +import type { AnyRouter } from '@tanstack/router-core' +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, +} from '@tanstack/start-client-core' + +const app = vi.hoisted(() => ({ + requestMiddleware: [] as Array, + functionMiddleware: [] as Array, + router: undefined as unknown, +})) + +vi.mock('#tanstack-start-entry', () => ({ + startInstance: { + getOptions: () => ({ + requestMiddleware: app.requestMiddleware, + functionMiddleware: app.functionMiddleware, + }), + }, +})) + +vi.mock('#tanstack-router-entry', () => ({ + getRouter: () => app.router, +})) + +function useGlobalMiddleware(options: { + request?: Array + function?: Array +}) { + app.requestMiddleware = options.request ?? [] + app.functionMiddleware = options.function ?? [] + return () => { + app.requestMiddleware = [] + app.functionMiddleware = [] + } +} + +type CompiledServerFn = ((opts?: { data?: unknown }) => Promise) & { + __executeServer: (opts: unknown) => Promise +} + +// The compiled shape of a server function in the module that provides it: +// the RPC entry calls the function's server side. +function defineServerFn( + middleware: Array, + handler: (ctx: { data: any; context: any }) => unknown, +): CompiledServerFn { + const attach = createServerFn({ method: 'GET' }).middleware(middleware) + .handler as unknown as (...args: Array) => CompiledServerFn + const rpc = createServerRpc( + { id: 'test', name: 'test', filename: 'test.ts' }, + (opts: unknown) => serverFn.__executeServer(opts), + ) + const serverFn = attach(rpc, handler) + return serverFn +} + +function makeRouter(): AnyRouter { + const router = new RouterCore( + { + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: new BaseRootRoute({}), + }, + () => ({ + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn: () => void) => fn(), + }), + ) + router.isServer = true + return router +} + +describe('runInRequest', () => { + it('resolves to what the callback returns', async () => { + await expect(runInRequest(() => 'sync')).resolves.toBe('sync') + await expect(runInRequest(async () => 'async')).resolves.toBe('async') + }) + + it('rejects with what the callback throws', async () => { + const error = new Error('from the callback') + + await expect( + runInRequest(() => { + throw error + }), + ).rejects.toBe(error) + }) + + it('sends a GET request to http://localhost/ by default', async () => { + const request = await runInRequest(() => getRequest()) + + expect(request.method).toBe('GET') + expect(request.url).toBe('http://localhost/') + }) + + it('builds the request from url, method and headers', async () => { + await runInRequest( + { + url: '/posts/42?draft=1', + method: 'POST', + headers: { cookie: 'session=abc' }, + }, + () => { + expect(getRequest().url).toBe('http://localhost/posts/42?draft=1') + expect(getRequest().method).toBe('POST') + expect(getCookie('session')).toBe('abc') + }, + ) + }) + + it('takes a Request as it is', async () => { + const request = new Request('https://example.com/a') + + await expect(runInRequest({ request }, () => getRequest())).resolves.toBe( + request, + ) + }) + + it('lets a test read what a handler set on the response', async () => { + const save = defineServerFn([], () => { + setResponseHeader('cache-control', 'private') + setResponseStatus(201) + return 'saved' + }) + + await runInRequest(async () => { + expect(getResponseHeader('cache-control')).toBeUndefined() + + await expect(save()).resolves.toBe('saved') + + expect(getResponseHeader('cache-control')).toBe('private') + expect(getResponseStatus()).toBe(201) + }) + }) + + it('runs a server function as a loader calls it during server rendering', async () => { + const order: Array = [] + const middleware = createMiddleware({ type: 'function' }) + .client(({ next }) => { + order.push('client') + return next() + }) + .server(({ next }) => { + order.push('server') + return next({ context: { user: 'Ada' } }) + }) + const greet = defineServerFn([middleware], ({ data, context }) => { + order.push('handler') + return `${data} ${context.user}` + }) + + await expect(runInRequest(() => greet({ data: 'Hello' }))).resolves.toBe( + 'Hello Ada', + ) + expect(order).toEqual(['client', 'server', 'handler']) + }) + + it('fails a server function that is called outside of it', async () => { + const greet = defineServerFn([], () => 'hello') + + await expect(greet()).rejects.toThrow( + /No Start context found.*runInRequest\(\)/, + ) + }) + + describe('global middleware', () => { + it('runs the request middleware before the callback and passes its context on', async () => { + const order: Array = [] + const reset = useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next, context }) => { + order.push('request middleware') + const result = await next({ + context: { + tenant: + (context as unknown as { tenant?: string }).tenant ?? + 'default', + }, + }) + order.push('after') + return result + }), + ], + }) + const readTenant = defineServerFn([], ({ context }) => context.tenant) + + try { + const tenant = await runInRequest( + { context: { tenant: 'acme' } as {} }, + () => { + order.push('callback') + return readTenant() + }, + ) + + expect(tenant).toBe('acme') + expect(order).toEqual(['request middleware', 'callback', 'after']) + } finally { + reset() + } + }) + + it('runs the function middleware for a server function call', async () => { + const reset = useGlobalMiddleware({ + function: [ + createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { locale: 'de' } }), + ), + ], + }) + const readLocale = defineServerFn([], ({ context }) => context.locale) + + try { + await expect(runInRequest(() => readLocale())).resolves.toBe('de') + } finally { + reset() + } + }) + + it('leaves both lists out with globalMiddleware: skip, and uses the context of the test', async () => { + const requestMiddleware = vi.fn(({ next }) => next()) + const functionMiddleware = vi.fn(({ next }) => next()) + const reset = useGlobalMiddleware({ + request: [createMiddleware().server(requestMiddleware)], + function: [ + createMiddleware({ type: 'function' }).server(functionMiddleware), + ], + }) + const readUser = defineServerFn([], ({ context }) => context.user) + + try { + const user = await runInRequest( + { globalMiddleware: 'skip', context: { user: 'Ada' } as never }, + () => readUser(), + ) + + expect(user).toBe('Ada') + expect(requestMiddleware).not.toHaveBeenCalled() + expect(functionMiddleware).not.toHaveBeenCalled() + } finally { + reset() + } + }) + + it('still runs a global middleware that a server function lists itself, with globalMiddleware: skip', async () => { + const server = vi.fn() + const middleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + server() + return next() + }, + ) + const reset = useGlobalMiddleware({ function: [middleware] }) + const listsIt = defineServerFn([middleware], () => 'done') + const doesNot = defineServerFn([], () => 'done') + + try { + await runInRequest({ globalMiddleware: 'skip' }, () => doesNot()) + expect(server).not.toHaveBeenCalled() + + await runInRequest({ globalMiddleware: 'skip' }, () => listsIt()) + expect(server).toHaveBeenCalledTimes(1) + } finally { + reset() + } + }) + + it('does not run a request middleware again that a server function lists as well', async () => { + const server = vi.fn(({ next }) => next()) + const middleware = createMiddleware().server(server) + const reset = useGlobalMiddleware({ request: [middleware] }) + const fn = defineServerFn([middleware], () => 'done') + + try { + await runInRequest(() => fn()) + + expect(server).toHaveBeenCalledTimes(1) + } finally { + reset() + } + }) + + it('rejects when a request middleware ends the request before the callback', async () => { + const reset = useGlobalMiddleware({ + request: [ + createMiddleware().server(() => new Response(null, { status: 401 })), + ], + }) + const callback = vi.fn() + + try { + const error: Error = await runInRequest(callback).then( + () => { + throw new Error('the scope should have rejected') + }, + (reason) => reason, + ) + + expect(error.message).toMatch( + /ended the request with status 401 before the callback ran/, + ) + expect((error.cause as Response).status).toBe(401) + expect(callback).not.toHaveBeenCalled() + } finally { + reset() + } + }) + + it('rejects with what a request middleware throws', async () => { + const error = new Error('no session') + const reset = useGlobalMiddleware({ + request: [ + createMiddleware().server(() => { + throw error + }), + ], + }) + + try { + await expect(runInRequest(() => 'unreached')).rejects.toBe(error) + } finally { + reset() + } + }) + + it('rejects with the error of the callback when a middleware turns it into a response', async () => { + const error = new Error('from the callback') + const reset = useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next }) => { + try { + return await next() + } catch { + return new Response(null, { status: 500 }) + } + }), + ], + }) + + try { + await expect( + runInRequest(() => { + throw error + }), + ).rejects.toBe(error) + } finally { + reset() + } + }) + + it('waits for the callback when a middleware does not wait for next()', async () => { + const reset = useGlobalMiddleware({ + request: [ + createMiddleware().server(({ next }) => { + void next() + return new Response(null) + }), + ], + }) + let finished = false + + try { + const value = await runInRequest(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + finished = true + return 'done' + }) + + expect(value).toBe('done') + expect(finished).toBe(true) + } finally { + reset() + } + }) + + it('gives a middleware the response with what the callback set through the helpers', async () => { + let seen: Response | undefined + const reset = useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next }) => { + const result = await next() + seen = result.response + return result + }), + ], + }) + + try { + await runInRequest(() => { + setResponseStatus(404) + setResponseHeader('x-reason', 'missing') + }) + + expect(seen?.status).toBe(404) + expect(seen?.headers.get('x-reason')).toBe('missing') + } finally { + reset() + } + }) + }) + + describe('getRouterInstance', () => { + it('returns the router of the router entry at the URL of the request', async () => { + app.router = makeRouter() + + try { + const router = await runInRequest({ url: '/posts/42?page=2' }, () => + getRouterInstance(), + ) + + expect(router).toBe(app.router) + expect(router.history.location.href).toBe('/posts/42?page=2') + } finally { + app.router = undefined + } + }) + + it('fails in a project without a router entry', async () => { + await expect(runInRequest(() => getRouterInstance())).rejects.toThrow( + 'This project has no router entry', + ) + }) + }) +}) + +describe('concurrent requests', () => { + it('keep their requests, responses and request mocks apart', async () => { + const tag = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { tag: 'real' } }), + ) + const readTag = defineServerFn([tag], ({ context }) => { + setResponseHeader('x-tag', context.tag) + return context.tag + }) + const request = (name: string, delay: number) => + runInRequest({ url: `/${name}` }, async () => { + mockMiddleware(tag, ({ next }) => next({ context: { tag: name } })) + await new Promise((resolve) => setTimeout(resolve, delay)) + const value = await readTag() + return [value, getResponseHeader('x-tag'), getRequest().url] + }) + + const [a, b] = await Promise.all([request('a', 20), request('b', 0)]) + + expect(a).toEqual(['a', 'a', 'http://localhost/a']) + expect(b).toEqual(['b', 'b', 'http://localhost/b']) + }) +}) + +describe('mockMiddleware', () => { + const realServer = vi.fn() + const realClient = vi.fn() + const auth = createMiddleware({ type: 'function' }) + .client(({ next }) => { + realClient() + return next() + }) + .server(({ next }) => { + realServer() + return next({ context: { user: 'real' } }) + }) + const whoAmI = defineServerFn([auth], ({ context }) => context.user) + + // Registered at the top of the file: stays for every test of the file. + const fileLevel = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { source: 'real' } }), + ) + const readSource = defineServerFn( + [fileLevel], + ({ context }) => context.source, + ) + mockMiddleware(fileLevel, ({ next }) => + next({ context: { source: 'file mock' } }), + ) + + it('replaces the server function of a middleware and switches its client function off', async () => { + realServer.mockClear() + realClient.mockClear() + const mock = vi.fn(({ next }) => next({ context: { user: 'mocked' } })) + mockMiddleware(auth, mock) + + await expect(runInRequest(() => whoAmI({ data: 'x' }))).resolves.toBe( + 'mocked', + ) + + expect(mock).toHaveBeenCalledWith( + expect.objectContaining({ data: 'x', method: 'GET' }), + ) + expect(realServer).not.toHaveBeenCalled() + expect(realClient).not.toHaveBeenCalled() + }) + + it('ends with the test that registered it', async () => { + realServer.mockClear() + realClient.mockClear() + + await expect(runInRequest(() => whoAmI())).resolves.toBe('real') + + expect(realServer).toHaveBeenCalledTimes(1) + expect(realClient).toHaveBeenCalledTimes(1) + }) + + it('stays for the file when it was registered at the top of the file', async () => { + await expect(runInRequest(() => readSource())).resolves.toBe('file mock') + }) + + it('belongs to the request when it is registered inside runInRequest', async () => { + await runInRequest(async () => { + mockMiddleware(fileLevel, ({ next }) => + next({ context: { source: 'request mock' } }), + ) + + await expect(readSource()).resolves.toBe('request mock') + }) + + await expect(runInRequest(() => readSource())).resolves.toBe('file mock') + }) + + it('fails the request when a mock registered inside it never ran', async () => { + await expect( + runInRequest(() => { + mockMiddleware(auth, ({ next }) => next({ context: { user: 'x' } })) + }), + ).rejects.toThrow( + 'A middleware was mocked inside runInRequest() and did not run in that request.', + ) + }) + + it('reports the error of the callback, not a mock that never ran because of it', async () => { + const error = new Error('from the callback') + + await expect( + runInRequest(() => { + mockMiddleware(auth, ({ next }) => next({ context: { user: 'x' } })) + throw error + }), + ).rejects.toBe(error) + }) + + it('lets a mock end the call by throwing', async () => { + const error = new Error('not signed in') + mockMiddleware(auth, () => { + throw error + }) + + await expect(runInRequest(() => whoAmI())).rejects.toBe(error) + }) + + it('replaces a global request middleware when it is registered before the request', async () => { + const real = vi.fn() + const tenantMiddleware = createMiddleware().server(({ next }) => { + real() + return next({ context: { tenant: 'real' } }) + }) + const reset = useGlobalMiddleware({ request: [tenantMiddleware] }) + const readTenant = defineServerFn([], ({ context }) => context.tenant) + mockMiddleware(tenantMiddleware, ({ next, request }) => + next({ context: { tenant: new URL(request.url).hostname } }), + ) + + try { + await expect( + runInRequest({ url: 'https://acme.example/' }, () => readTenant()), + ).resolves.toBe('acme.example') + expect(real).not.toHaveBeenCalled() + } finally { + reset() + } + }) + + it('lets the mock of a request middleware end the request with a response', async () => { + const gate = createMiddleware().server(({ next }) => next()) + const reset = useGlobalMiddleware({ request: [gate] }) + mockMiddleware(gate, () => new Response(null, { status: 403 })) + + try { + await expect(runInRequest(() => 'unreached')).rejects.toThrow( + /ended the request with status 403/, + ) + } finally { + reset() + } + }) + + it('needs a middleware', () => { + expect(() => + mockMiddleware({} as AnyFunctionMiddleware, ({ next }) => next()), + ).toThrow('mockMiddleware() needs a middleware') + }) +}) + +describe('runMiddleware', () => { + it('calls the server function of a function middleware with the input', async () => { + const middleware = createMiddleware({ type: 'function' }) + .validator((input: { id: string }) => input) + .server(({ data, next }) => { + if (getCookie('session') !== 'abc') { + throw new Error('not signed in') + } + return next({ + context: { user: { id: data.id } }, + sendContext: { seen: true }, + }) + }) + + await runInRequest({ headers: { cookie: 'session=abc' } }, async () => { + const next = vi.fn(() => 'the handler result') + const run = await runMiddleware(middleware, { data: { id: '42' } }, next) + + expect(run.context).toEqual({ user: { id: '42' } }) + expect(run.sendContext).toEqual({ seen: true }) + expect(run.result).toBe('the handler result') + expect(next).toHaveBeenCalledWith({ + context: { user: { id: '42' } }, + sendContext: { seen: true }, + }) + }) + + await runInRequest(async () => { + await expect( + runMiddleware(middleware, { data: { id: '42' } }), + ).rejects.toThrow('not signed in') + }) + }) + + it('merges the context of the input with what the middleware adds', async () => { + const parent = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { tenant: 'acme' } }), + ) + const middleware = createMiddleware({ type: 'function' }) + .middleware([parent]) + .server(({ next, context }) => + next({ context: { greeting: `hello ${context.tenant}` } }), + ) + + const run = await runInRequest(() => + runMiddleware(middleware, { context: { tenant: 'other' } }), + ) + + // (only this middleware ran: `parent` would have set `acme`) + expect(run.context).toEqual({ tenant: 'other', greeting: 'hello other' }) + expect(run.result).toBeUndefined() + }) + + it('calls the server function of a request middleware for the request of the scope', async () => { + const middleware = createMiddleware().server( + async ({ next, request, pathname, handlerType }) => { + if (!request.headers.get('authorization')) { + return new Response(null, { status: 401 }) + } + const result = await next({ context: { pathname, handlerType } }) + result.response.headers.set('x-checked', 'yes') + return result + }, + ) + + await runInRequest({ url: '/admin' }, async () => { + const next = vi.fn() + const run = await runMiddleware(middleware, {}, next) + + expect(run.response.status).toBe(401) + expect(next).not.toHaveBeenCalled() + }) + + await runInRequest( + { url: '/admin', headers: { authorization: 'Bearer x' } }, + async () => { + const run = await runMiddleware( + middleware, + {}, + () => new Response('page', { status: 203 }), + ) + + expect(run.context).toEqual({ + pathname: '/admin', + handlerType: 'router', + }) + expect(run.response.status).toBe(203) + expect(run.response.headers.get('x-checked')).toBe('yes') + await expect(run.response.text()).resolves.toBe('page') + }, + ) + }) + + it('treats a thrown response of a request middleware as its answer', async () => { + const middleware = createMiddleware().server(() => { + throw new Response(null, { status: 302, headers: { location: '/login' } }) + }) + + const run = await runInRequest(() => runMiddleware(middleware, {})) + + expect(run.response.status).toBe(302) + expect(run.response.headers.get('location')).toBe('/login') + }) + + it('applies what a request middleware set through the response helpers', async () => { + const middleware = createMiddleware().server(({ next }) => { + setResponseHeader('x-frame-options', 'DENY') + return next() + }) + + const run = await runInRequest(() => + runMiddleware(middleware, { handlerType: 'serverFn' }), + ) + + expect(run.response.headers.get('x-frame-options')).toBe('DENY') + }) + + it('runs the real server function of a middleware that is mocked', async () => { + const middleware = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { source: 'real' } }), + ) + mockMiddleware(middleware, ({ next }) => + next({ context: { source: 'mock' } }), + ) + + const run = await runInRequest(() => runMiddleware(middleware, {})) + + expect(run.context).toEqual({ source: 'real' }) + }) + + it('has to be called inside runInRequest', async () => { + const middleware = createMiddleware({ type: 'function' }).server( + ({ next }) => next(), + ) + + await expect(runMiddleware(middleware, {})).rejects.toThrow( + 'runMiddleware() has to be called inside runInRequest()', + ) + }) + + it('needs a middleware with a server function', async () => { + const clientOnly = createMiddleware({ type: 'function' }).client( + ({ next }) => next(), + ) + + await expect( + runInRequest(() => runMiddleware(clientOnly, {})), + ).rejects.toThrow('the middleware has no server function') + }) +}) diff --git a/packages/start-server-core/vite.config.ts b/packages/start-server-core/vite.config.ts index 09e3bf9539..f191fd99bc 100644 --- a/packages/start-server-core/vite.config.ts +++ b/packages/start-server-core/vite.config.ts @@ -44,6 +44,7 @@ export default mergeConfig( './src/request-response.ts', './src/constants.ts', './src/virtual-modules.ts', + './src/testing/index.ts', './src/fake-start-server-fn-resolver.ts', './src/empty-plugin-adapters.ts', ], diff --git a/packages/start-storage-context/src/async-local-storage.ts b/packages/start-storage-context/src/async-local-storage.ts index bbde704629..b79464149f 100644 --- a/packages/start-storage-context/src/async-local-storage.ts +++ b/packages/start-storage-context/src/async-local-storage.ts @@ -57,7 +57,11 @@ export function getStartContext(opts?: { const context = startStorage.getStore() if (!context && opts?.throwIfNotFound !== false) { throw new Error( - `No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`, + `No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.${ + process.env.NODE_ENV === 'test' + ? ` In a test, run this code inside runInRequest(), which the testing/server entry of your Start package exports (for example '@tanstack/react-start/testing/server').` + : '' + }`, ) } return context as any diff --git a/packages/vue-start/package.json b/packages/vue-start/package.json index bf6b79e636..918219916d 100644 --- a/packages/vue-start/package.json +++ b/packages/vue-start/package.json @@ -50,6 +50,24 @@ "default": "./dist/esm/client-rpc.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/server": { + "import": { + "types": "./dist/esm/testing/server.d.ts", + "default": "./dist/esm/testing/server.js" + } + }, "./server-rpc": { "import": { "types": "./dist/esm/server-rpc.d.ts", diff --git a/packages/vue-start/src/testing.ts b/packages/vue-start/src/testing.ts new file mode 100644 index 0000000000..0384b6fb65 --- /dev/null +++ b/packages/vue-start/src/testing.ts @@ -0,0 +1,10 @@ +export { + mockServerFn, + resetServerFnMocks, +} from '@tanstack/start-client-core/testing' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from '@tanstack/start-client-core/testing' diff --git a/packages/vue-start/src/testing/client-rpc.ts b/packages/vue-start/src/testing/client-rpc.ts new file mode 100644 index 0000000000..80b041a388 --- /dev/null +++ b/packages/vue-start/src/testing/client-rpc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-client-core/testing/client-rpc' diff --git a/packages/vue-start/src/testing/server.ts b/packages/vue-start/src/testing/server.ts new file mode 100644 index 0000000000..ec2ad1c8d8 --- /dev/null +++ b/packages/vue-start/src/testing/server.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/testing' diff --git a/packages/vue-start/vite.config.ts b/packages/vue-start/vite.config.ts index dc421ef7ff..17b824ec6d 100644 --- a/packages/vue-start/vite.config.ts +++ b/packages/vue-start/vite.config.ts @@ -30,6 +30,9 @@ export default mergeConfig( './src/index.ts', './src/client.tsx', './src/client-rpc.ts', + './src/testing.ts', + './src/testing/client-rpc.ts', + './src/testing/server.ts', './src/ssr-rpc.ts', './src/server-rpc.ts', './src/server.tsx', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4328f4fab6..0e18b142c5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -513,7 +513,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) benchmarks/memory/client: dependencies: @@ -589,7 +589,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) benchmarks/memory/server: dependencies: @@ -659,7 +659,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) benchmarks/ssr: dependencies: @@ -726,7 +726,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) e2e/e2e-utils: devDependencies: @@ -747,7 +747,7 @@ importers: version: 4.2.3(@types/node@25.0.9)(@typescript/typescript6@6.0.2)(rollup@4.63.1)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) e2e/eslint-plugin-start: devDependencies: @@ -780,7 +780,7 @@ importers: version: 5.9.2 vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) e2e/react-router/basepath-file-based: dependencies: @@ -4326,6 +4326,98 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-start/vitest-app: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../packages/react-start + react: + specifier: ~19.2.9 + version: 19.2.9 + react-dom: + specifier: ~19.2.9 + version: 19.2.9(react@19.2.9) + devDependencies: + '@testing-library/react': + specifier: 'catalog:' + version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.9))(@types/react@19.2.9)(react-dom@19.2.9(react@19.2.9))(react@19.2.9) + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: 'catalog:' + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/browser-playwright': + specifier: 5.0.4 + version: 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) + jsdom: + specifier: 'catalog:' + version: 25.0.1(supports-color@10.2.2) + playwright: + specifier: ^1.63.0 + version: 1.63.0 + typescript: + specifier: npm:@typescript/typescript6@^6.0.2 + version: '@typescript/typescript6@6.0.2' + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + + e2e/react-start/vitest-library: + dependencies: + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../packages/react-start + react: + specifier: ~19.2.9 + version: 19.2.9 + react-dom: + specifier: ~19.2.9 + version: 19.2.9(react@19.2.9) + devDependencies: + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: 'catalog:' + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/browser-playwright': + specifier: 5.0.4 + version: 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) + jsdom: + specifier: 'catalog:' + version: 25.0.1(supports-color@10.2.2) + playwright: + specifier: ^1.63.0 + version: 1.63.0 + typescript: + specifier: npm:@typescript/typescript6@^6.0.2 + version: '@typescript/typescript6@6.0.2' + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + e2e/react-start/website: dependencies: '@tanstack/react-router': @@ -10193,7 +10285,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: ^5.0.4 - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) examples/react/start-bare: dependencies: @@ -10718,7 +10810,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: ^5.0.4 - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) web-vitals: specifier: ^5.1.0 version: 5.1.0 @@ -13005,7 +13097,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@7.0.1(@testing-library/dom@10.4.1)(vitest@5.0.4))(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: ^5.0.4 - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) examples/solid/start-basic: dependencies: @@ -13446,7 +13538,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: ^5.0.4 - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) web-vitals: specifier: ^5.1.0 version: 5.1.0 @@ -14089,7 +14181,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/eslint-plugin-router: dependencies: @@ -14123,7 +14215,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/eslint-plugin-start: dependencies: @@ -14157,7 +14249,7 @@ importers: version: 5.9.2 vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/history: devDependencies: @@ -14181,7 +14273,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/react-router: dependencies: @@ -14254,7 +14346,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) zod: specifier: 'catalog:' version: 4.5.4 @@ -14315,7 +14407,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/react-router-ssr-query: dependencies: @@ -14373,7 +14465,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/react-start: dependencies: @@ -14449,7 +14541,7 @@ importers: version: 6.1.2 vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/react-start-client: dependencies: @@ -14510,7 +14602,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/react-start-rsc: dependencies: @@ -14589,7 +14681,7 @@ importers: version: 6.1.2 vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/react-start-server: dependencies: @@ -14650,7 +14742,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-cli: dependencies: @@ -14684,7 +14776,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-core: dependencies: @@ -14730,7 +14822,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-devtools: dependencies: @@ -14782,7 +14874,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-devtools-core: dependencies: @@ -14828,7 +14920,7 @@ importers: version: 2.11.10(@testing-library/jest-dom@7.0.1(@testing-library/dom@10.4.1)(vitest@5.0.4))(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-generator: dependencies: @@ -14886,7 +14978,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-plugin: dependencies: @@ -14922,7 +15014,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vite-plugin-solid: specifier: ^2.11.10 || ^3.0.0-0 - version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) zod: specifier: 'catalog:' version: 4.5.4 @@ -14971,7 +15063,7 @@ importers: version: 6.1.2 vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) webpack: specifier: ^5.104.1 version: 5.110.3(@swc/core@1.15.33(@swc/helpers@0.5.23))(clean-css@5.3.3)(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.29)(sharp@0.35.5(@types/node@25.0.9))(svgo@4.0.0)(webpack-cli@5.1.4) @@ -15004,7 +15096,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-utils: dependencies: @@ -15056,7 +15148,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/router-vite-plugin: dependencies: @@ -15081,7 +15173,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/solid-router: dependencies: @@ -15139,7 +15231,7 @@ importers: version: 2.11.10(@testing-library/jest-dom@7.0.1(@testing-library/dom@10.4.1)(vitest@5.0.4))(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) zod: specifier: 'catalog:' version: 4.5.4 @@ -15182,7 +15274,7 @@ importers: version: 2.11.10(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/solid-router-ssr-query: dependencies: @@ -15228,7 +15320,7 @@ importers: version: 2.11.10(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/solid-start: dependencies: @@ -15292,7 +15384,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/solid-start-client: dependencies: @@ -15335,7 +15427,7 @@ importers: version: 2.11.10(@testing-library/jest-dom@7.0.1(@testing-library/dom@10.4.1)(vitest@5.0.4))(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/solid-start-server: dependencies: @@ -15381,7 +15473,7 @@ importers: version: 2.11.10(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/start-client-core: dependencies: @@ -15421,7 +15513,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/start-fn-stubs: devDependencies: @@ -15442,7 +15534,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/start-plugin-core: dependencies: @@ -15470,6 +15562,9 @@ importers: '@tanstack/router-utils': specifier: workspace:* version: link:../router-utils + '@tanstack/start-client-core': + specifier: workspace:* + version: link:../start-client-core '@tanstack/start-server-core': specifier: workspace:* version: link:../start-server-core @@ -15545,7 +15640,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/start-server-core: dependencies: @@ -15600,7 +15695,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/start-static-server-functions: dependencies: @@ -15640,7 +15735,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/start-storage-context: dependencies: @@ -15671,7 +15766,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/valibot-adapter: devDependencies: @@ -15719,7 +15814,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/virtual-file-routes: devDependencies: @@ -15743,7 +15838,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) packages/vue-router: dependencies: @@ -15801,7 +15896,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vue: specifier: 'catalog:' version: 3.5.25(@typescript/typescript6@6.0.2) @@ -15844,7 +15939,7 @@ importers: version: 6.1.2 vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vue: specifier: 'catalog:' version: 3.5.25(@typescript/typescript6@6.0.2) @@ -15884,7 +15979,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vue: specifier: 'catalog:' version: 3.5.25(@typescript/typescript6@6.0.2) @@ -15945,7 +16040,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vue: specifier: 'catalog:' version: 3.5.25(@typescript/typescript6@6.0.2) @@ -15985,7 +16080,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vue: specifier: 'catalog:' version: 3.5.25(@typescript/typescript6@6.0.2) @@ -16031,7 +16126,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) vue: specifier: 'catalog:' version: 3.5.25(@typescript/typescript6@6.0.2) @@ -16079,7 +16174,7 @@ importers: version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: 'catalog:' - version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) zod: specifier: ^3.24.2 version: 3.25.57 @@ -16497,6 +16592,9 @@ packages: '@better-fetch/fetch@1.3.1': resolution: {integrity: sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g==} + '@blazediff/core@1.10.0': + resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} + '@braidai/lang@1.1.2': resolution: {integrity: sha512-qBcknbBufNHlui137Hft8xauQMTZDKdophmLFv05r2eNmdIv/MlPuP4TdUknHG68UdWLgVZwgxVe735HzJNIwA==} @@ -22692,6 +22790,17 @@ packages: vite: ^8.3.4 vue: ^3.2.25 + '@vitest/browser-playwright@5.0.4': + resolution: {integrity: sha512-RYbUmphqONHDcpjMHLNQRy47XbQHHnZokBgtjM8MSPGSiqwBcqwYufdSYEceOwk6zZjKUr3ps5HgjbiXo7sOTg==} + peerDependencies: + playwright: '*' + vitest: 5.0.4 + + '@vitest/browser@5.0.4': + resolution: {integrity: sha512-pRRkI2am/lmhGiaeHkVVLQb7SZyCOe5ytjVNQ0zLNZjA1xb+7aNTRqaaPeMJzWM958/5IrxJ50yTUpKSsigHMw==} + peerDependencies: + vitest: 5.0.4 + '@vitest/expect@4.1.4': resolution: {integrity: sha512-iPBpra+VDuXmBFI3FMKHSFXp3Gx5HfmSCE8X67Dn+bwephCnQCaB7qWK2ldHa+8ncN8hJU8VTMcxjPpyMkUjww==} @@ -27065,6 +27174,10 @@ packages: engines: {node: '>=20'} hasBin: true + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -29037,6 +29150,16 @@ packages: '@testing-library/jest-dom': optional: true + vite-plugin-solid@2.11.16: + resolution: {integrity: sha512-qguFUmqY2ICuoGHrZjm+cWpvKkqVyWDMptipC/BIEGr9q6wEzwTWYOjM9pEWJ+yoTuF6T5OpysI2Okdy7rsVlQ==} + peerDependencies: + '@testing-library/jest-dom': ^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0 + solid-js: 1.9.12 + vite: ^8.3.4 + peerDependenciesMeta: + '@testing-library/jest-dom': + optional: true + vite-tsconfig-paths@6.1.1: resolution: {integrity: sha512-2cihq7zliibCCZ8P9cKJrQBkfgdvcFkOOc3Y02o3GWUDLgqjWsZudaoiuOwO/gzTzy17cS5F7ZPo4bsnS4DGkg==} peerDependencies: @@ -29509,6 +29632,18 @@ packages: utf-8-validate: optional: true + ws@8.23.0: + resolution: {integrity: sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + xml-name-validator@4.0.0: resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} engines: {node: '>=12'} @@ -30254,6 +30389,8 @@ snapshots: '@better-fetch/fetch@1.3.1': {} + '@blazediff/core@1.10.0': {} + '@braidai/lang@1.1.2': {} '@bramus/specificity@2.4.2': @@ -30663,7 +30800,7 @@ snapshots: '@codspeed/core': 6.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) tinybench: 6.2.2 vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) - vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) transitivePeerDependencies: - debug - supports-color @@ -35698,7 +35835,7 @@ snapshots: picocolors: 1.1.1 redent: 3.0.0 optionalDependencies: - vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) '@testing-library/react@16.2.0(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.9))(@types/react@19.2.9)(react-dom@19.2.9(react@19.2.9))(react@19.2.9)': dependencies: @@ -36714,6 +36851,136 @@ snapshots: vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vue: 3.5.25(typescript@6.0.2) + '@vitest/browser-playwright@5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@vitest/browser': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + playwright: 1.63.0 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser-playwright@5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@vitest/browser': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + playwright: 1.63.0 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + + '@vitest/browser-playwright@5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@vitest/browser': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + playwright: 1.63.0 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser-playwright@5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@vitest/browser': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + playwright: 1.63.0 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser@5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/ui': 5.0.4(vitest@5.0.4) + '@vitest/utils': 5.0.4 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + ws: 8.23.0 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser@5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/ui': 5.0.4(vitest@5.0.4) + '@vitest/utils': 5.0.4 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + ws: 8.23.0 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + + '@vitest/browser@5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/ui': 5.0.4(vitest@5.0.4) + '@vitest/utils': 5.0.4 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + ws: 8.23.0 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser@5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/ui': 5.0.4(vitest@5.0.4) + '@vitest/utils': 5.0.4 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + ws: 8.23.0 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + '@vitest/expect@4.1.4': dependencies: '@standard-schema/spec': 1.1.0 @@ -36822,7 +37089,7 @@ snapshots: pathe: 2.0.3 sirv: 3.0.2 tinyrainbow: 3.2.0 - vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) '@vitest/utils@4.1.4': dependencies: @@ -40400,7 +40667,7 @@ snapshots: cssstyle: 4.2.1 data-urls: 5.0.0 decimal.js: 10.6.0 - form-data: 4.0.5 + form-data: 4.0.6 html-encoding-sniffer: 4.0.0 http-proxy-agent: 7.0.2(supports-color@10.2.2) https-proxy-agent: 7.0.6(supports-color@10.2.2) @@ -40416,7 +40683,7 @@ snapshots: whatwg-encoding: 3.1.1 whatwg-mimetype: 4.0.0 whatwg-url: 14.1.0 - ws: 8.20.0 + ws: 8.21.0 xml-name-validator: 5.0.0 transitivePeerDependencies: - bufferutil @@ -41800,6 +42067,8 @@ snapshots: dependencies: playwright-core: 1.63.0 + pngjs@7.0.0: {} + possible-typed-array-names@1.1.0: {} postcss-loader@8.2.0(@typescript/typescript6@6.0.2)(postcss@8.5.6)(webpack@5.97.1): @@ -43987,6 +44256,21 @@ snapshots: transitivePeerDependencies: - supports-color + vite-plugin-solid@2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + '@types/babel__core': 7.20.5 + babel-preset-solid: 1.9.10(@babel/core@7.29.7(supports-color@10.2.2))(solid-js@1.9.12) + merge-anything: 5.1.7 + solid-js: 1.9.12 + solid-refresh: 0.6.3(solid-js@1.9.12)(supports-color@10.2.2) + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitefu: 1.1.3(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + optionalDependencies: + '@testing-library/jest-dom': 6.6.3 + transitivePeerDependencies: + - supports-color + vite-tsconfig-paths@6.1.1(@typescript/typescript6@6.0.2)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: debug: 4.4.3(supports-color@10.2.2) @@ -44128,7 +44412,7 @@ snapshots: - msw optional: true - vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) @@ -44147,12 +44431,13 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 25.0.9 + '@vitest/browser-playwright': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) '@vitest/ui': 5.0.4(vitest@5.0.4) jsdom: 25.0.1(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) @@ -44171,12 +44456,13 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 25.0.9 + '@vitest/browser-playwright': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) '@vitest/ui': 5.0.4(vitest@5.0.4) jsdom: 25.0.1(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) @@ -44195,12 +44481,13 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 25.0.9 + '@vitest/browser-playwright': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) '@vitest/ui': 5.0.4(vitest@5.0.4) jsdom: 25.0.1(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) @@ -44219,12 +44506,13 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 25.0.9 + '@vitest/browser-playwright': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) '@vitest/ui': 5.0.4(vitest@5.0.4) jsdom: 27.0.0(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) @@ -44243,12 +44531,13 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 25.0.9 + '@vitest/browser-playwright': 5.0.4(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) '@vitest/ui': 5.0.4(vitest@5.0.4) jsdom: 29.1.1(@noble/hashes@2.0.1) transitivePeerDependencies: - msw - vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/browser-playwright@5.0.4)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) @@ -44267,6 +44556,7 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 '@types/node': 25.0.9 + '@vitest/browser-playwright': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@5.9.2))(playwright@1.63.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vitest@5.0.4) '@vitest/ui': 5.0.4(vitest@5.0.4) jsdom: 29.1.1(@noble/hashes@2.0.1) transitivePeerDependencies: @@ -44881,6 +45171,8 @@ snapshots: ws@8.21.0: {} + ws@8.23.0: {} + xml-name-validator@4.0.0: {} xml-name-validator@5.0.0: {} diff --git a/scripts/e2e/run-as-installed.md b/scripts/e2e/run-as-installed.md new file mode 100644 index 0000000000..793fad4c4f --- /dev/null +++ b/scripts/e2e/run-as-installed.md @@ -0,0 +1,137 @@ +# Running an e2e project as an installed project + +`scripts/e2e/run-as-installed.mjs` runs a command in a copy of an e2e project +whose `@tanstack/*` dependencies are installed the way a user's package +manager installs them. + +## Why + +An e2e project in this repository depends on `@tanstack/*` with the +`workspace:` protocol. pnpm installs such a dependency as a link to the +package's directory: + +``` +e2e/react-start/vitest-library/node_modules/@tanstack/react-start + -> packages/react-start +``` + +In a user's project the same package is a directory inside `node_modules`: + +``` +node_modules/.pnpm/@tanstack+react-start@1.x/node_modules/@tanstack/react-start +``` + +Vite and Vitest look at the real path of a file to decide how to treat it, and +the two layouts get different answers: + +| Question | Linked (`packages/react-start/...`) | Installed (`node_modules/...`) | +| ------------------------------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| Does Vitest run the file through Vite's plugins? | Always. It is source code to Vitest. | Only when a pattern of `server.deps.inline` matches. Otherwise Node loads it as it is. | +| Does Vite pre-bundle what the file imports? | Yes, when the import is first seen. | Only what `optimizeDeps.include` names. Any other import is served as it is. | +| Can the project import a package it does not depend on? | The repository root's dependencies, from the directories above. | No. pnpm gives a project only its own dependencies. | + +So a run inside the repository cannot show a mistake in what our plugins tell +Vite or Vitest about dependencies: `resolve.noExternal`, `resolve.external`, +`optimizeDeps` and the inline list of a test runner. Every `@tanstack/*` file +goes through the Start compiler there, whatever the plugin says. + +Two bugs were found this way in November 2026, in projects whose tests passed +in the repository: + +- A package that depends on `@tanstack/react-start` but not on + `@tanstack/react-router` failed in Vitest's browser mode. Start asked Vite to + pre-bundle `@tanstack/react-store` by a path through the router, which did + not resolve from the project, and the browser got the store's CommonJS + dependency as it is. +- In a jsdom test, Node loaded `@tanstack/start-client-core` as it is, without + the Start compiler. Its functions with a client and a server implementation + then ran the server one. Vitest's translation of the wildcards in Start's + `resolve.noExternal` does not match a package name with a dash. Start works + around it: in a test run it names its packages with regular expressions + (`createTestRunNoExternal` in + `packages/start-plugin-core/src/vite/planning.ts`, which documents the + workaround and when it can go). + +## What the script does + +1. It runs `pnpm --filter deploy `, with a new directory + under the system's temporary directory. `pnpm deploy` copies the project and + installs its dependencies into the copy from the workspace's lockfile, so + the versions are the ones the repository uses. A workspace package is + packed as for publishing (the files its `files` field names) and installed + like a package from the registry. +2. It runs the given command in the copy, with the copy's `node_modules/.bin` + first on `PATH`. +3. It removes the copy and exits with the command's status. + +The copy is outside the repository on purpose. From a directory inside it, +Node and Vite would walk up to the repository's own `node_modules` and +workspace root. + +## Using it + +In the e2e project's `package.json`: + +```json +{ + "scripts": { + "test:e2e": "pnpm run test:e2e:linked && pnpm run test:e2e:installed", + "test:e2e:linked": "vitest run", + "test:e2e:installed": "node ../../../scripts/e2e/run-as-installed.mjs vitest run" + }, + "nx": { + "targets": { + "test:e2e": { + "inputs": [ + "buildProduction", + "^production", + "dependentTaskOutputs", + "{workspaceRoot}/scripts/e2e/run-as-installed.mjs" + ] + } + } + } +} +``` + +The run in place stays, because it is the quick one while working on a +package. The `inputs` add the script to what Nx hashes for the target. + +To look at a copy after a failure: + +```sh +node ../../../scripts/e2e/run-as-installed.mjs --keep vitest run +``` + +## In CI + +`pnpm test:pr` runs `test:e2e` of every affected project, and `test:ci` runs +it for all of them, so the run as a user's project is part of every CI run that +touches these projects. Before it runs the command, the script checks that +each `@tanstack/*` dependency of the project resolves to a package inside the +copy, and fails otherwise. A pass therefore means the tests ran against +installed packages, and not against links that slipped back in. + +## When a project needs it + +When what it tests depends on how a bundler or a test runner treats a package +in `node_modules`: whether the package goes through our compiler, whether its +dependencies are pre-bundled, and whether a package resolves from the project. +`e2e/react-start/vitest-library` and `e2e/react-start/vitest-app` use it. + +The client code of a production build does not differ between the layouts: a +build bundles every file, wherever it is. Server code can differ in the same +way as a test run, because Vite leaves a package in `node_modules` to Node +unless `resolve.noExternal` matches it. So a Playwright project can use the +script as well; none does yet. + +## Limits + +- The packages have to be built first: the copy gets each package's published + files. The `test:e2e` target depends on `^build`. +- It is pnpm's layout. npm and Yarn put more packages where a project can + import them, so pnpm is the stricter case for resolution, but their layouts + are not run. +- `pnpm deploy` needs the registry: it checks the lockfile against the + workspace's supply-chain policies, and it downloads what the store lacks. +- It takes about 7 seconds before the command starts. diff --git a/scripts/e2e/run-as-installed.mjs b/scripts/e2e/run-as-installed.mjs new file mode 100644 index 0000000000..0e8e103298 --- /dev/null +++ b/scripts/e2e/run-as-installed.mjs @@ -0,0 +1,103 @@ +#!/usr/bin/env node +/** + * Runs a command in a copy of an e2e project whose `@tanstack/*` dependencies + * are installed the way a user's package manager installs them, instead of + * being links to `packages/*`. `run-as-installed.md` explains why a project + * needs this and what the copy is. + * + * Usage, from the e2e project's directory: + * + * node ../../../scripts/e2e/run-as-installed.mjs [--keep] [...args] + * + * `--keep` leaves the copy in place and prints where it is. + */ +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +const args = process.argv.slice(2) +const keep = args[0] === '--keep' +if (keep) { + args.shift() +} +const [command, ...commandArgs] = args +if (!command) { + console.error( + 'Usage: node scripts/e2e/run-as-installed.mjs [--keep] [...args]', + ) + process.exit(1) +} + +const packageJson = JSON.parse(readFileSync('package.json', 'utf8')) +const projectName = packageJson.name +const tanstackDependencies = Object.keys({ + ...packageJson.dependencies, + ...packageJson.devDependencies, +}).filter((name) => name.startsWith('@tanstack/')) + +// The copy lives outside the repository. From a directory inside it, Node and +// Vite would walk up to the repository's own `node_modules` and workspace +// root, and a package the project does not depend on would resolve anyway. +const directory = realpathSync( + mkdtempSync(path.join(tmpdir(), 'tanstack-installed-')), +) +const copy = path.join(directory, 'project') + +function run(executable, executableArgs, options = {}) { + const result = spawnSync(executable, executableArgs, { + stdio: 'inherit', + // (`pnpm` and the binaries of `node_modules/.bin` are `.cmd` files on Windows) + shell: process.platform === 'win32', + ...options, + }) + if (result.error) { + throw result.error + } + return result.status ?? 1 +} + +/** + * Fails unless every `@tanstack/*` dependency of the project is a package + * inside the copy. If a change to pnpm's settings or to how `deploy` works + * left a link back into `packages/*`, the run would be a linked one again, + * and it would pass without testing what this script is for. + */ +function assertInstalled() { + const nodeModules = path.join(copy, 'node_modules') + for (const name of tanstackDependencies) { + const location = realpathSync(path.join(nodeModules, name)) + if (!location.startsWith(nodeModules + path.sep)) { + throw new Error( + `${name} is not installed in the copy: it resolves to ${location}. The run would test the linked workspace package.`, + ) + } + console.log(`${name}: installed in the copy`) + } +} + +let status = 1 +try { + // `pnpm deploy` copies the project and installs its dependencies into the + // copy from the workspace's lockfile. A workspace package is packed as for + // publishing and installed like a package from the registry. + status = run('pnpm', ['--filter', projectName, 'deploy', copy]) + if (status === 0) { + assertInstalled() + const binaries = path.join(copy, 'node_modules', '.bin') + status = run(command, commandArgs, { + cwd: copy, + env: { + ...process.env, + PATH: `${binaries}${path.delimiter}${process.env.PATH}`, + }, + }) + } +} finally { + if (keep) { + console.log(`The installed copy is kept at ${copy}`) + } else { + rmSync(directory, { recursive: true, force: true }) + } +} +process.exit(status)